This is a working example of Ansible playbook that creates everything from VPC to EC2 instance on AWS.
Have latest tools installed for Ansible. See the packages I had installed below.
python ansible python-boto awscli python-pip phhon3-pip python-boto3 python-botocore
All global variables are listed in ./group_vars/all/vars.
Playbook tasks are all listd in actions within roles ./roles/ec2-vpc-create/tasks/main.yml.
The playbook actions are listed here for reference also.
---
# tasks file for vpc-create
- name: create VPC
ec2_vpc_net:
name: "{{ vpc_name }}"
cidr_block: "{{ vpc_cidr }}"
region: "{{ region }}"
state: present
aws_access_key: "{{ aws_access_key }}"
aws_secret_key: "{{ aws_secret_key }}"
register: vpc
- name: Report VPC variable output
debug:
msg: "{{ vpc.vpc.id }}"
#- name: Check VPC output
# debug: msg="{{ vpc['vpc'.'id'] }}"
- name: associate subnet to the VPC
ec2_vpc_subnet:
# vpc_id: "{{ vpc_id }}"
vpc_id: "{{ vpc.vpc.id }}"
region: "{{ region }}"
state: present
cidr: "{{ subnet_cidr }}"
aws_access_key: "{{ aws_access_key }}"
aws_secret_key: "{{ aws_secret_key }}"
map_public: yes
resource_tags:
Name: "{{ subnet_name }}"
register: subnet
- name: create IGW
ec2_vpc_igw:
vpc_id: "{{ vpc.vpc.id }}"
region: "{{ region }}"
state: present
aws_access_key: "{{ aws_access_key }}"
aws_secret_key: "{{ aws_secret_key }}"
tags:
Name: "{{ igw_name }}"
register: igw
- name: Route IGW
ec2_vpc_route_table:
vpc_id: "{{ vpc.vpc.id }}"
region: "{{ region }}"
state: present
aws_access_key: "{{ aws_access_key }}"
aws_secret_key: "{{ aws_secret_key }}"
subnets:
- "{{ subnet.subnet.id }}"
routes:
- dest: 0.0.0.0/0
gateway_id: "{{ igw.gateway_id }}"
tags:
Name: "{{ route_name }}"
- name: Create Security Group
ec2_group:
name: Web DMZ
description: DMZ Security Group
vpc_id: "{{ vpc.vpc.id }}"
region: "{{ region }}"
state: present
aws_access_key: "{{ aws_access_key }}"
aws_secret_key: "{{ aws_secret_key }}"
rules:
- proto: tcp
ports:
- 80
cidr_ip: 0.0.0.0/0
- proto: tcp
ports:
- 22
cidr_ip: 0.0.0.0/0
register: security_group
- name: create a new ec2 key pair
ec2_key:
aws_access_key: "{{ aws_access_key }}"
aws_secret_key: "{{ aws_secret_key }}"
name: ec2_keypair
region: "{{ region }}"
state: present
register: keypair
- name: Copy EC2 Private Key locally so it can be later on used to SSH into the instance
copy: content= "{{ keypair.key.private_key }}" dest={{ ec2_key_directory }}key.ppk
when: keypair.changed == true
- name: Create EC2 server
ec2:
image: ami-00035f41c82244dab
wait: yes
instance_type: t2.micro
region: "{{ region }}"
state: prsent
group_id: "{{ security_group.group_id }}"
vpc_subnet_id: "{{ subnet.subnet.id }}"
key_name: "{{ keypair.key.name }}"
instance_tags:
Name: AnsibleInstance
count_tag:
Name: apacheserver
# exact_count: 1 # only enabled when state is off
aws_access_key: "{{ aws_access_key }}"
aws_secret_key: "{{ aws_secret_key }}"
Open Source
See my blog at https://blog.kamranshah.com