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.
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/
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With