EC2 + Ansible + AWS CLI

jerome.decoster
3 min readDec 8, 2021

--

Creating EC2 instances with AWS CLI. Uptading them with Ansible.

The Goal

  • Create a Load balancer and EC2 instances via Autoscaling
  • EC2 machines host an Apache site installed via a user-data script
  • Do everything using AWS CLI
  • Ping the machines with Ansible
  • Update the Apache site with Ansible via a playbook
  • Machine inventory will be dynamic : a bash script using AWS CLI

Install and setup the project

Get the code from this github repository :

To setup the project, run the following command :

# create load balancer + instances using autoscaling
$ make ec2-create

This command will :

Now we have 2 instances :

A Load balancer :

A Launch template :

A very simple website :

You can get the Load Balancer URL with :

# get load balancer dns
$ make load-balancer-dns

Ping the EC2 machines using Ansible

To ping the machin we use :

# ping ec2 instances with ansible
$ make ansible-ping

This command execute a simple command :

$ ansible aws -m ping

But this command is executed in a specific playbook context

The ansible.cfg file execute a bash inventory file

[defaults]
inventory = ./inventory.sh
remote_user = ec2-user
private_key_file = ../ec2-ansible.pem

The inventory.sh file is an executable file :

  • Some aws cli commands collect the instances ids and public address IP
  • A bash script build and output some specific JSON data

If we run this script directly in the terminal we get a JSON :

By executing our command we must answer yes to the SSH question several times :

It’s rather unpleasant because it interrupts the flow of the script.

Update our site with Ansible

We will update all our EC2 machines with Ansible

Our playbook is very simple :

  • We are replacing the home page with a new template
  • We restart the Apache service

The template is very simple :

Ansible facts are a lot of data related to your remote systems, including operating systems, IP addresses, attached filesystems, and more.

We update our ec2 instances with this simple command :

By updating our browser we see that the update has been made :

The demonstration is over. We can delete our resources with this command :

# destroy all resources
$ make destroy

Warning : deleting resources can take a long time and sometimes fail along the way.

It is important to verify via the AWS website that the resources have indeed disappeared.

In this case, you have to delete them manually, which is not necessarily very easy.

--

--