Ansible is a configuration management tool which configures and manages systems for multi-node software deployment. It is an orchestration tool which prevents an agent from running continuously on a server to fetch the desired configurations. Unlike Chef and Puppet, it uses a push mechanism to push the desired changes on the servers using ssh-agent.
Here, we will learn how to launch an AWS EC2 instance using ansible. We will write an Ansible playbook to launch the instance. The playbooks are written in “.yml” format.
The easiest way to start is to create a playbook calling the ec2 module with the parameters you want to pass to AWS to create your host. In this post I will show a little more scalable way to do this, where the parameters are variables and you can easily have multiple types of hosts sharing the same playbook and role.
Prerequisite:
- Ansible
- Python boto library
- Set up the AWS access and secret keys in the environment settings
(best is inside the ~./boto)
To Install Python-PIP
The solution is organized in 3 parts:
- A generic Ansible role that uses ec2 module to provision
- Yaml files with variables that will be used as parameters for each type of EC2 host
- Playbook that combines the variables file with the role
Setup Environment
Run the following commands to install the required dependencies for Ansible and AWS.
# pip install --upgrade pip # pip install boto # yum install ansible
To Install ansible on Ubuntu Click Install Ansible
To Get KEY
Log into your AWS account to get your “AWS_ACCESS_KEY_ID” and “AWS_SECRET_ACCESS_KEY”. Go to “Identity and Access Management”. Create a new user or select an exiting one. Go to “Security Credentials” and click “Create Access Key”.
Ansible’s EC2 module uses python-boto library to call AWS API, and boto needs AWS credentials in order to function.
There are many ways to set your AWS credentials. One of them is to create a file under your user home folder:
# touch ~/.boto
Then edit the file and add the following:
# vim ~/.boto [Credentials] aws_access_key_id = HIDDEN aws_secret_access_key = HIDDEN
For more information, check Boto documentation. To learn how to create AWS credentials, check this documentation.
To Create the EC2 Instance(s):
In order to create the EC2 Instance, please modified these parameters that you can find inside the “ec2_launch.yml” file under “vars”:
- region # where is want to launch the instance(s), USA, Australia, Ireland etc
- count # Number of instance(s), you want to create
Once, you have mentioned these parameter, please run the following command:
# ansible-playbook -i hosts ec2_launch.yml
Contents of hosts file:
# vim hosts
[local]
localhost
[testserver]
Contents of ec2_launch.yml file: