Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding to authorized_keys via AWS EC2 Instance User Data

Recently I made the silly mistake of clearing the contents of my user's ~/.ssh/authorized_keys file on my AWS instance. As such, I can no longer ssh onto the instance.

I realised I could add these keys back via AWS EC2 instance user data. However as of yet I have had no luck with this. I stopped my instance, added the following to the user data and started it again:

#!/bin/bash
> /home/myUser/.ssh/authorized_keys
echo "ssh-rsa aaa/bbb/ccc/ddd/etc== mykeypair" >> /home/myUser/.ssh/authorized_keys
chown myUser:myUser /home/myUser/.ssh/authorized_keys
chmod 600 /home/myUser/.ssh/authorized_keys

This should empty the file, add the public keypair and ensure the correct permissions are present on the file.

However my private key is still being rejected.

I know the keys are correct so it must be something to do with my instance user data. I have also tried prepending 'sudo' to all commands.

like image 569
x3nr0s Avatar asked May 02 '18 10:05

x3nr0s


2 Answers

Try to use cloud-init directives instead of shell

#cloud-config
cloud_final_modules:
- [users-groups,always]
users:
  - name: example_user
    groups: [ wheel ]
    sudo: [ "ALL=(ALL) NOPASSWD:ALL" ]
    shell: /bin/bash
    ssh-authorized-keys: 
    - ssh-rsa AAAAB3Nz<your public key>...

The default behavior is to execute once-per-instance. However, these instructions add the key on every reboot or restart of the instance. If the user data is removed, the default functionality is restored. These instructions are for use on all OS distributions that support cloud-init directives.

https://aws.amazon.com/premiumsupport/knowledge-center/ec2-user-account-cloud-init-user-data/

like image 109
Sudharsan Sivasankaran Avatar answered Nov 15 '22 07:11

Sudharsan Sivasankaran


From the official docs:

By default, user data and cloud-init directives only run during the first boot cycle when you launch an instance. However, AWS Marketplace vendors and owners of third-party AMIs may have made their own customizations for how and when scripts run.

https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/user-data.html

So modifying user data after you shut down your instance will not be useful in most cases.

Solution: you can detach your EBS volume, attach it to an EC2 instance you can connect to, mount the volume, fix authorized_keys, than connect the volume back to the affected instance.

like image 42
Sergey Kovalev Avatar answered Nov 15 '22 09:11

Sergey Kovalev