AWS – EC2 User Data: Preparing Ubuntu Instance For Ansible Management (AWS / Ansible)

I have used previous blog posts to discuss using Ansible to create / manage AWS EC2 instances, and using Terraform with Ansible to create / manage AWS EC2 instances. However, there are people that prefer to use the AWS web console over Infrastructure as Code (IaC).

If you find yourself in the situation of creating new EC2 instances from the console and already use Ansible then the “User Data” option of “Configure Instance Details” (currently Step 3) of the EC2 instance creation can be used to create a user (e.g. Ansible), create the user’s home directory with .ssh authorized_keys file and appropriate permissions and add the user to the sudo group.

The following script accomplishes this:

#!/usr/bin/env bash

useradd -m -d /home/ansible -s /bin/bash ansible

mkdir /home/ansible/.ssh

touch /home/ansible/authorized_keys

echo 'PLACE PUBLIC SSH KEY HERE' >> /home/ansible/.ssh/authorized_keys

chown -R ansible:ansible /home/ansible/.ssh

chmod 700 /home/ansible/.ssh

chmod 600 /home/ansible/.ssh/authorized_keys

usermod -a G sudo ansible

Note: Make sure to replace ‘PLACE PUBLIC SSH KEY HERE’ with a copy of the public key that you use with Ansible.

As long as your AWS security group has been set up to allow SSH in from the IP address you run Ansible from, you should now be able to SSH in as ansible@IP_ADDRESS_OF_EC2_INSTANCE using the private key paired to the public key entered in the script.

If you would prefer not to script / use User Data, then at the final step of AWS EC2 creation make sure to choose an SSH key that can also be used with Ansible.

Posted in AWS