Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does EC2 install the public key from your keypair?

Tags:

amazon-ec2

I am debugging creation of a custom AMI and it's not clear to me how EC2 actually installs the public key of your keypair onto your AMI... I presume it goes into ~someuser/.ssh/authorized_keys, but I cannot figure out if this is done exactly once, on every boot, or how the target user is determined.

like image 271
apinstein Avatar asked Mar 05 '14 16:03

apinstein


1 Answers

More specifically cloud-init is a Python module that gets run every time an instance starts.

You can browse through the code here:

 /usr/lib/python2.7/dist-packages/cloudinit

They parts that get the key are the DataSource.py and DataSourceEc2.py files. They query the metadata using the URL: http://169.254.169.254/2011-01-01/meta-data/public-keys/.

The find the list of keys using that URL and then pick them up one of by one. (It's usually one). Ultimately they query: http://169.254.169.254/2011-01-01/meta-data/public-keys/0/openssh-key/ then they copy that key to the default cloud-init user's ~/.ssh/authorized_keys file.

The default cloud-init user (as well as all the cloud-init config) is defined in the /etc/cloud/cloud.cfg file. This in excerpt of a cloud.cfg file:

user: ubuntu
disable_root: 1
preserve_hostname: False
# datasource_list: ["NoCloud", "ConfigDrive", "OVF", "MAAS", "Ec2", "CloudStack"]

cloud_init_modules:
 - bootcmd
 - resizefs
 - set_hostname
 - update_hostname
 - update_etc_hosts
 - ca-certs
 - rsyslog
 - ssh

cloud_config_modules:
 - disk-setup
 - mounts
 - ssh-import-id
 - locale
 - set-passwords
 - grub-dpkg
 ...

It's basically a yaml format config file.

For more information on cloud-init you can read their public docs here:

http://cloudinit.readthedocs.org/en/latest/index.html

Hope this helps.

like image 103
Rico Avatar answered Oct 19 '22 21:10

Rico