Launch EC2 Instance using Ansible

In my previous POST, I did publish on installing Ansible in your local ec2 machine.   Now we can spin up an EC2 Machine using Ansible script.

 

1. Export AWS CLI Authentication Keys

Get your access keys by logging into your AWS Console and export them:

Login to Console > Security, Identity & Compliance, IAM > Users > select your username > Security Credentials > Create Access Key

export AWS_SECRET_ACCESS_KEY=xxxxxxxx
export AWS_ACCESS_KEY_ID=xxxxxx

2. Create hosts file and below lines

[local]  #These are host groups
localhost #Represents the host that we are in

[dbserver]  # These are host groups

3. Create Ansible Script to provision an EC2 Instance

cat ec2-prov.yml

— #three hyphens

– name: Provision an EC2 Instance

hosts: local
connection: local
gather_facts: False
tags: provisioning

 

# Variables to create an EC2 Instance

vars:
instance_type: t2.micro
security_group: security_group
image: ami-67589505
keypair: Keypair
region: ap-southeast-2
count: 1

 

# Task to Launch an EC2 Instance

tasks:

 

– name: Launch the new EC2 Instance
local_action: ec2
group={{ security_group }}
instance_type={{ instance_type}}
image={{ image }}
wait=true
region={{ region }}
keypair={{ keypair }}
count={{count}}
register: ec2

 

– name: Add the newly created EC2 instance to the local host group in hosts file
local_action: lineinfile
dest=”./hosts”
regexp={{ item.private_ip }}
insertafter=”[dbserver]” line={{ item.private_ip }}
with_items: ‘{{ ec2.instances }}’

 

– name: Wait for SSH to come up
local_action: wait_for
host={{ item.private_ip }}
port=22
state=started
with_items: ‘{{ ec2.instances }}’

 

– name: Add tag to Instance
local_action: ec2_tag resource={{ item.id }} region={{ region }} state=present
with_items: ‘{{ ec2.instances }}’
args:
tags:
Name: dbserver

4. Run below command to provision an EC2 Instance.

[oracle@ansible]$ ansible-playbook -i ./hosts ec2-prov.yml

Nagulu Polagani

"We are all apprentices in a craft where no one ever becomes a master."