Automating EC2 creation - Stopping - Starting using Ansible
Requirements
Requirements (on host that executes modules):
- python 3
- awscli
- boto - Ansible will connect to AWS using the boto SDK. So, we need to install the boto and boto3 packages. :
$ pip3 install boto boto3
add this configuration to the ansible hosts file
Here is the hosts file:
[local]
localhost ansible_python_interpreter=/usr/share/python3
you can fallow below commands ro find path
root@ip-172-31-23-165:/home/ubuntu# python3 --version
Python 3.10.6
root@ip-172-31-23-165:/home/ubuntu# whereis python 3
python: /usr/share/python3
Note that we set the ansible_python_interpreter
configuration option to /usr/share/python3. The ansible_python_interpreter
configuration option is usually set per-host as an inventory variable associated with a host.
EC2 Creation
create a file named ec2-creation.yml
---
- name: stop EC2 instance
hosts: all
gather_facts: yes
vars:
region: us-east-1
instance_type: t2.nano
ami: ami-08c40ec9ead489470 # Ubuntu 20.04 LTS
keypair: Laptop # pem file name
subnetid: subnet-057cf54a81b45d203
tasks:
- name: Create an ec2 instance
ec2:
key_name: "{{ keypair }}"
group: default # security group name
instance_type: "{{ instance_type }}"
image: "{{ ami }}"
wait: true
region: "{{ region }}"
count: 1 # default
count_tag:
Name: Demo
instance_tags:
Name: Demo
vpc_subnet_id: "{{ subnetid }}"
assign_public_ip: yes
state: stopped
register: ec2
execute this playbook
anisble-playbook ec2-creation.yml
EC2 Stopping
create the playbook named ec2-stop.yml
- name: stop EC2 instance
hosts: all
gather_facts: yes
vars:
instance_ids:
- 'i-0aca0590e709cc531'
region: us-east-1
tasks:
- name: Stop the sandbox instances
ec2:
instance_ids: '{{ instance_ids }}'
region: '{{ region }}'
state: stopped
wait: True
vpc_subnet_id: subnet-057cf54a81b45d203
assign_public_ip: yes
Execute them same way using command
ansible-playbook ec2-stop.yml
EC2-Starting
create the playbook named ec2-start.yml
- name: stop EC2 instance
hosts: all
gather_facts: yes
vars:
instance_ids:
- 'i-0aca0590e709cc531'
region: us-east-1
tasks:
- name: Stop the sandbox instances
ec2:
instance_ids: '{{ instance_ids }}'
region: '{{ region }}'
state: started
wait: True
vpc_subnet_id: subnet-057cf54a81b45d203
assign_public_ip: yes
Execute them same way using command
ansible-playbook ec2-start.yml
Comments
Post a Comment