A practical way to provision instances on Amazon Web Service EC2 with Ansible.

Welcome, this article shows a simple approach to use Ansible for provisioning an AWS EC2 instance.

Ansible is a configuration management tool widely used to provision IT environments, deploy software or be integrated to CI/CD pipelines. There are lots of Ansible modules developed to ease tasks related to AWS cloud management.

The following steps will be performed along the article to demonstrate the power around the integration of Ansible and AWS Cloud:

  • Create AWS user
  • Install Ansible and Ansible EC2 module dependencies
  • Create SSH keys
  • Create Ansible structure
  • Run Ansible to provision the EC2 instance
  • Connect to the EC2 instance via SSH

Create AWS user

Open the AWS Console, search for IAM (Identity and Access Management) and follow this steps to create a user and take note of the Access Key and Secret Key that will be used by Ansible to set up the instances.

Install Ansible and the EC2 module dependencies

This article was written with Ansible version 2.8.0 and Python version 2.7.

Create SSH keys to connect to the EC2 instance after provisioning

Create the Ansible directory structure

Optionally, you can use Git (or SVN) to keep the version control of this directory.

Create Ansible Vault file to store the AWS Access and Secret keys.

The password provided here will be asked every time the playbook is executed or when editing the pass.yml file.

This article will follow the approach above, however, if you don’t want to provide the password every time, an insecure approach can create the pass.yml file by specifying a hashed password file:

With hashed password file you must specify the vault-password-file argument when running Ansible playbook and won’t be asked for the password:

Edit the pass.yml file and create the keys global constants

Create the variables ec2_access_key and ec2_secret_key and set the values gathered after user creation (IAM).

Directory structure

Open the playbook.yml file and past the following content


Notes about the playbook

  • For security, the playbook will execute by default just the tasks to collect information on AWS. The tasks responsible for provisioning the instance will be performed if specified the tag create_ec2.
  • The first step to create the user (IAM) can also be performed with the Ansible iam module, but here was demonstrated on the AWS Console to show the interaction.

Running Ansible to provision instances

If you execute Ansible without the tags argument the creation tasks won’t be performed.

Create the instance

Get the public DNS

Connect to the EC2 instance via SSH

Congratulations, you’ve automated the EC2 instance provisioning process with Ansible.