How to connect to AWS EC2 instance from Ansible

Sat, Feb 4, 2017

Ansible #Ansible #AWS

In this post we going to see how to connect to AWS EC2 instances from Ansible. In my last post we’ve seen how to connect to Docker container from Ansible, the process is more or less the same, except we will configure the inventory file differently.

First we will need to launch an EC2 instance in AWS, if you don’t have any yet. In our case the EC2 instance will need a public IP, but if your Ansible playbook is running from one of the instances in your VPC, you can use the private IP instead. At the last step of launching the instance, we will be asked to select an existing key pair or create a new one(refer to the following image). alt text

It is very important to keep the key pair in a safe place because once you lose your key pair you will no long be able to login to this instance again. Save your key pair locally and run the following command.

thor$ chmod 600 your-key.pem

Ok now we have an EC2 instance running and a keypair, we can proceed to configure the inventory file now.

ec2-instance ansible_host=<<ec2-instance-ip>> ansible_user=ec2-user ansible_ssh_private_key_file=/location/of/the/keypair/your-key.pem

Let’s try to run ping module.

thor$ ansible -i inventory all -m ping
ec2-instance | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}

This approach is quite similar when compare to connect to other platform such as Linux except we will need to specify the key pair in the inventory file.