Gunjan Sharma
Gunjan Sharma

Reputation: 25

How to create addition EC2 user in linux AMI via UserData with ssh permission

Problem statement- Create additional user pretty much same what been explained Here, only thing which I am doing is instead of generating new key pair I am using same key pair which is being used for ec2-user.

Now if I run following commands manually login into ec-2 instance it working without any issue and I am able to ssh with same key as test-user

sudo adduser test-user
sudo su - test-user
mkdir .ssh
chmod 700 .ssh
cd .ssh
curl http://169.254.169.254/latest/meta-data/public-keys/0/openssh-key >> authorized_keys
chmod 600 authorized_keys

But if I keep same instruction in user data section of instance to run on boot up, It only create test-user but doesn't perform rest of the steps. I don't found much detail also on /var/log/cloud-init-output.log

#!/bin/bash
sudo adduser test-user
sudo su - test-user
mkdir .ssh
chmod 700 .ssh
cd .ssh
curl http://169.254.169.254/latest/meta-data/public-keys/0/openssh-key >> authorized_keys
chmod 600 authorized_keys

Upvotes: 0

Views: 4791

Answers (2)

mj3c
mj3c

Reputation: 1695

  1. First, make sure cloud-init is installed on your instance

    sudo yum install cloud-init
    
  2. Stop the instance (not terminate)

  3. Update user data with the following script (make sure to replace <YOUR-PUBLIC-SSH-KEY> with your key (eg. ssh-rsa abc123...)

    #cloud-config
    cloud_final_modules:
    - [users-groups,always]
    users:
      - name: username
        groups: [ wheel ]
        sudo: [ "ALL=(ALL) NOPASSWD:ALL" ]
        shell: /bin/bash
        ssh-authorized-keys: 
        - <YOUR-PUBLIC-SSH-KEY>
    
  4. Start your instance

Now you should be able to login the same way as for ec2-user.

More information here: https://aws.amazon.com/premiumsupport/knowledge-center/ec2-user-account-cloud-init-user-data/

Upvotes: 1

Gunjan Sharma
Gunjan Sharma

Reputation: 25

Apparently scripts entered as user data are executed as the root user, so any files you create will be owned by root. So you have to change the ownership of .those file to test-user. Below command need to be executed in the end.

chown -R test-user:test-user /home/test-user/

Upvotes: 1

Related Questions