Terminating EC2 instances with Ansible Playbook
Please find a simple Ansible playbook for terminating EC2 instance in AWS using instance id.
Pre-requisites:
Make sure you create an IAM role with AmazonEC2FullAccess policy and attach the role to EC2 instance.
Login to EC2 instance using Git bash or ITerm/putty where you installed Ansible. Execute the below command to edit Ansible hosts or inventory file
sudo vi /etc/ansible/hosts
Add the below two lines in the end of the file:
[localhost]
local
[localhost]
local
save the file and come out of it.
Create the playbook by executing below command:
sudo vi terminate.yml
---
- name: ec2 provisioning using Ansible
hosts: local
connection: local
gather_facts: False
- hosts: local
gather_facts: False
connection: local
vars:
- region: 'us-east-2'
- ec2_id: 'i-05f39cfb80c97df38'
tasks:
- name: Terminate instances
local_action: ec2
state='absent'
instance_ids='{{ ec2_id }}'
region='{{ region }}'
wait=True
This playbook can be executed by two ways. Either mention instance ID in the ansible playbook or pass as an argument. Intstance Id can be taken from AWS mgmt console.
---
- name: ec2 provisioning using Ansible
hosts: local
connection: local
gather_facts: False
- hosts: local
gather_facts: False
connection: local
vars:
- region: 'us-east-2'
- ec2_id: 'i-05f39cfb80c97df38'
tasks:
- name: Terminate instances
local_action: ec2
state='absent'
instance_ids='{{ ec2_id }}'
region='{{ region }}'
wait=True
This playbook can be executed by two ways. Either mention instance ID in the ansible playbook or pass as an argument. Intstance Id can be taken from AWS mgmt console.
ansible-playbook terminate.yml -e ec2_id=i-xxxx
PLAY [ec2 provisioning using Ansible] *********************************************************************
PLAY [local] **********************************************************************************************
TASK [Terminate instances] ********************************************************************************
ok: [local -> localhost]
PLAY RECAP ************************************************************************************************
local : ok=1 changed=0 unreachable=0 failed=0
Comments
Post a Comment