Project goal
Using Ansible on localhost:
- Launch EC2 instances with tags
- Wait until they are running
- Retrieve public IPs / SSH in
- Destroy instances when the lab is done
Control Node → Ansible playbook → AWS API → EC2 (+ public IP)
Prerequisites
ansible-galaxy collection install amazon.aws
pip3 install boto3 botocore
aws sts get-caller-identityIAM for demos often uses AmazonEC2FullAccess. Prefer least privilege in real accounts.
Ensure you have:
- A key pair name in the target region
- A security group that allows SSH from your IP
- A valid AMI ID for the region
Create instances
mkdir -p playbooks
vim playbooks/create-ec2.yml---
- hosts: localhost
connection: local
gather_facts: false
vars:
ec2_region: ap-southeast-1
ec2_image: ami-0df7a207adb9748c7
ec2_type: t2.micro
ec2_key: prod-managed-node-1
ec2_sg: default
tasks:
- name: Create EC2 instances
amazon.aws.ec2_instance:
name: "{{ item }}"
region: "{{ ec2_region }}"
image_id: "{{ ec2_image }}"
instance_type: "{{ ec2_type }}"
key_name: "{{ ec2_key }}"
security_group: "{{ ec2_sg }}"
network:
assign_public_ip: true
wait: true
tags:
ManagedBy: ansible
Project: day5
loop:
- managed-node-1
- managed-node-2
- managed-node-3
register: ec2
- name: Show results
debug:
var: ec2ansible-playbook playbooks/create-ec2.ymlVerify in the AWS console (EC2 → Instances) and SSH:
ssh -i your-key.pem ubuntu@<PUBLIC_IP>Discover with Ansible
Point dynamic inventory at the new hosts, or query with the AWS modules:
ansible-inventory -i aws_ec2.yml --graph
ansible all -i aws_ec2.yml -m pingDelete instances
---
- hosts: localhost
connection: local
gather_facts: false
tasks:
- name: Terminate lab instances
amazon.aws.ec2_instance:
region: ap-southeast-1
state: absent
filters:
tag:Project: day5
wait: trueansible-playbook playbooks/delete-ec2.ymlFull lifecycle
Configure AWS credentials
↓
Create EC2 (Ansible)
↓
Dynamic inventory / SSH
↓
Configure with playbooks (Days 1–4)
↓
Destroy when finished
Ansible vs Terraform for EC2
| Ansible | Terraform |
|---|---|
| Great for config + occasional creates | Strong for long-lived infra + state |
| Same tool as your config playbooks | Clear plan/apply for networking |
Many teams still let Terraform own VPCs/instances and Ansible own configuration — Day 5 shows you can provision with Ansible when that fits the workflow.
Replace AMI, key pair, region, and security group with values from your account. Always terminate lab instances to avoid ongoing charges.