Search code examples
amazon-web-servicesamazon-ec2cloud-init

How to replace /root/.ssh/authorized_keys with cloud-config on EC2?


When deploying a new EC2 instance you have to select an SSH key to give access to the machine. I would like to use only the authorised keys specified in the user data for an instance. Is this possible? I've tried using both ssh-authorized-keys:

users:
  - name: user
    ssh-authorized-keys:
      - ssh-rsa [...] my_key

and write_files:

write_files:
  - content: |
        ssh-rsa [...] my_key
    path: /home/user/.ssh/authorized_keys

, but in both cases the original key is added to /root/.ssh/authorized_keys automatically. Do I need to disable root login to disable this key permanently?


Solution

  • The user ec2-user|centos|ubuntu... is the default_user as defined by /etc/cloud/*.cfg

    This is how to skip this default_user behaviour, and setup another user by the user-data:

    #cloud-config
    system_info:
      default_user: ~
    users:
    - name: myname
      sudo: ALL=(ALL) NOPASSWD:ALL
      ssh-authorized-keys:
      - ssh-rsa AAAA[...]O1 myname@myhost
    

    Please note that the keypair selected on AWS console/api is ignored.