Total Pageviews


December 15, 2018

AWS DevOps - Part 2 - Provisioning EC2 Instances using Ansible Playbook

by 4hathacker  |  in AWS DevOps at  11:30 PM

Hi folks!

In the very first part of the series, we have discussed a number of ways to launch EC2 instances. Here we will see how to write an Ansible playbook with roles and vars sections to launch an EC2 instance. To get a glimpse of Ansible Basics, feel free to visit the previous Ansible articles

In this article, we will be following a number of steps for EC2 provisioning:
1. Creating a security group for EC2 instance. Note - Only allow ssh access to your own public ip or any trusted IP source you would like to have an access to EC2. DO NOT ALLOW ACCESS RULE IN CIDR_IP.

2. Creating and saving the key in local machine for EC2 instance access

3. Creating an EC2 instance

4. Adding our EC2 instance to Ansible hosts file with its IP. From line 69, an in-memory inventory creation is done for further use in the same playbook. For now, it is not used.

Note: Do not forget to fulfill the boto requirement and credentials entry. Refer previous article. Here, PyCharm Editor with YAML/Ansible Plugin is used for Ansible Playbook implementation. Its better to have some sort of editor handy for easier debugging and best practices.

Now, lets have a look at our file structure.

The main file is site.yml in the CreateEC2s directory. We will be having the Ansible structure for playbook as:
a. group_vars/all - for describing key variables of tasks

b. site.yml - for role creation and task run

c. create/tasks/main.yml - for all activity modules for ec2 as described in above images for EC2 provisioning.

d. hosts - for entry of newly created ec2 details

Lets run and check the Ansible Playbook.

Lets check in AWS Management Console if it worked or not.
1. Security group - 4hathacker_ansibletutorial_security_group with rule configured.
2. Key is saved in the folder as aws-private.pem.
3. Hosts file entries done for ec2 creation.

If you feel comfortable with this article, try to spin up a new EC2 instance post setting up a VPC using Ansible. You can also try to write a simple rollback script in Ansible to terminate all things we did in this article. In the next article, we will be getting hands dirty with CloudFormation.


Like Our Facebook Page

Nitin Sharma's DEV Profile
Proudly Designed by 4hathacker.