I need to add an additional user account so that I can connect using SSH. How can I do this?

Adding an additional SSH user to an Amazon EC2 instance might be necessary for accountability, compliance, or operational reasons. You can add an additional account by using the cloud-init utility.

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.

Note: Cloud-init must be installed and configured for these instructions to work. For more information, see SSH.

These instructions create a new user account, set the appropriate ownership and file permissions for the SSH directory and files contained in it, and append the specified SSH public key to the authorized_keys file. The new user account functions identically to the default behavior of the ec2-user.

Note: You must stop your instance; any data on ephemeral volumes is lost.

Stop the EC2 Instance:

  • In the Amazon EC2 console, select the instance, choose Actions, Instance State, and then choose Stop.
    Note:
    If Stop is disabled, either the instance is already stopped or its root device is an instance store volume.

Find the public key:

Linux / OSX:

# ssh-keygen -y -f /path/to/keypair.pem

Windows:

Update the public key:

  • Choose Actions, Instance Settings, and then choose View/Change User Data.
  • Copy and paste this command into the User Data field and update the ssh-rsa line with the corresponding public key, and then choose Save.
#cloud-config
cloud_final_modules:
- [users-groups,always]
users:
  - name: <username>
    groups: [ wheel ]
    sudo: [ "ALL=(ALL) NOPASSWD:ALL" ]
    shell: /bin/bash
    ssh-authorized-keys: 
    - ssh-rsa AAAAB3Nz<your public key>...

For example, to create the "example_user" account, the userdata script might look similar to this.

#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>...
  • Choose Actions, select Instance State, and then choose Start.
  • After the instance is started, you should be able to log in as the newly created user.

Note: Modifying the user data of an instance is done by using the ModifyInstanceAttribute API method; IAM policies can be created to restrict this method.


Did this page help you? Yes | No

Back to the AWS Support Knowledge Center

Need help? Visit the AWS Support Center

Published: 2017-09-06