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.

share|improve this question
    
It uses a system called cloud-init. I think the key is also available on the metadata service. – datasage Mar 5 '14 at 17:19
up vote 14 down vote accepted

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.

share|improve this answer
    
Brilliant, thank you!!! – apinstein Mar 6 '14 at 18:28

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.