Managing aws resources using Ansible is efficient and reliable. In this document we will create an ec2 instance using Ansible under a new vpc and subnet. For that we will do the following
1) Creating a VPC
2)Creating a subnet
3)Creating an internet gateway and routing table for vpc
3)Creating a security group
4)Creating an ec2 instance
Our directory structure for ansible playbook is as follows
Here we have an aws role which will execute creating of a new ec2 instance under new vpc and subnet.
The main.yaml file under tasks is as follows:
Here in our playbook first we will create a VPC.We will specify region,name,cidr-block over here.We will register it as my_vpc. On next step we will save its id which we will use while creating subnet. Similarly we create Internet gateway and routing table to that vpc.
Then we will create a n security group allowing traffic through certain ports.Next we created a ssh key pair for our ec2 instance and saved the private key in our local sytem and finally we created ec2 instance using an image id.
We can see certain variables mentioned in our playbook.We have to place it under roles/aws/tasks/main.yaml. Our variable file is as follows
This file contains various variables that we mentioned in our tasks/main.yaml file.
Then comes our main file which conains name of roles that we are going to execute.It will be as follows:
Now execute our playbook by
#ansible-playbook main.yaml
We can see our playbook being executed and new ec2-instance being created.