Create new EC2 instance in AWS cloud using Ansible Playbook
Ansible Playbook for provisioning a new EC2 instance in AWS
We will learn how to create Ansible Playbook for provisioning a new EC2 instance in the AWS cloud. Please follow the below steps in the machine where you have installed Ansible.
Pre-requisites:
Ansible is installed and Boto is also installed on the Ubuntu EC2 instance.
Make sure you create an IAM role with the AmazonEC2FullAccess policy and attach the role to an EC2 instance.
Steps to create an EC2 instance using Ansible:
Login to the EC2 instance using Git bash or ITerm/putty where you installed Ansible. Execute the below command:
Edit Ansible hosts or inventory files:
sudo vi /etc/ansible/hosts
Add the below two lines at the end of the file:
[localhost]
local
cd ~
mkdir playbooks
cd playbooks/
Create Ansible playbook
sudo vi create_ec2.yml
---
- name: provisioning EC2 instances using Ansible
hosts: localhost
connection: local
gather_facts: False
tags: provisioning
vars:
keypair: MyEC2Key #Create Your Own KeyPair
instance_type: t2.small
image: ami-020db2c14939a8efb #Write your own AMI id
wait: yes
group: webserver
count: 1
region: us-east-2 #Write your suitable region
security_group: my-jenkins-security-grp
tasks:
- name: Task # 1 - Create my security group
local_action:
module: ec2_group
name: "{{ security_group }}"
description: Security Group for webserver Servers
region: "{{ region }}"
rules:
- proto: tcp
from_port: 22
to_port: 22
cidr_ip: 0.0.0.0/0
- proto: tcp
from_port: 8080
to_port: 8080
cidr_ip: 0.0.0.0/0
- proto: tcp
from_port: 80
to_port: 80
cidr_ip: 0.0.0.0/0
rules_egress:
- proto: all
cidr_ip: 0.0.0.0/0
register: basic_firewall
- name: Task # 2 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: Task # 3 Add Tagging to EC2 instance
local_action: ec2_tag resource={{ item.id }} region={{ region }} state=present
with_items: "{{ ec2.instances }}"
args:
tags:
Name: MyTargetEc2Instance
now execute the ansible playbook by:
sudo ansible-playbook create_ec2.yml
Fix the warnings by executing the below command:
pip install --upgrade requests==2.20.1
If everything is good, you should see the new instance created on the AWS console. make sure you can connect to that instance.
That's it!! That is how you create a new EC2 instance using Ansible.
Conclusion
Ansible and Terraform together form a flexible workflow for spinning up servers with the needed software and hardware configurations. Running Ansible directly as part of the Terraform deployment process allows you to have the servers up and bootstrapped with dependencies for your development work and applications much faster.