Clean Up AWS Resources Using Ansible - Amazon VPC and EC2
Tags: aws, ec2, vpc, ansible
Published: 2022-04-27 16:48:02

In case you have followed all posts in this series. Here are the deletion tasks (using Ansible) and we have to do it sequentially! This step is important enough because some of the services we used are not free such as EC2 instances and custom AMI.

**Prerequisites:**

1. [AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html) and [set at least one credential](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-files.html);
    
2. [Ansible](https://docs.ansible.com/ansible/latest/installation_guide/intro_installation.html);
    
3. Ansible collection for AWS by running `ansible-galaxy collection install amazon.aws` and `ansible-galaxy collection install community.aws`.
    

Inventory:

```yaml
---

localhost:
  hosts:
    127.0.0.1:
```

Some of the tasks below require to use of ID such as: `image_id` of the custom AMI, `vpc_id`, and `route_table_id`. You can run the following command to get the info:

* `image_id`
    

```bash
$ aws ec2 describe-images --filters "Name=name,Values=amazonlinux2_httpd_ami" --query 'Images[].{Name:Name, ID:ImageId}'
[
    {
        "Name": "amazonlinux2_httpd_ami",
        "ID": "ami-0c1cfb0a18f5e4451"
    }
]
```

* `vpc_id`
    

```bash
$ aws ec2 describe-vpcs --query 'Vpcs[?Tags[?Value==`custom_vpc`]].{VPC:VpcId, CIDR:CidrBlock}' | grep VPC | awk '{ print $2 }' | sed 's/,$//'
"vpc-0a6bbb5ca26b09679"
```

* `route_table_id`
    

```bash
$ aws ec2 describe-route-tables --filters "Name=vpc-id,Values=vpc-0a6bbb5ca26b09679" --query 'RouteTables[].Associations[?Main==`false`].[RouteTableId]'
[
    [
        [
            "rtb-03442f1c5afa52db0"
        ],
        [
            "rtb-03442f1c5afa52db0"
        ],
        [
            "rtb-03442f1c5afa52db0"
        ]
    ],
    []
]
```

Now, let's start creating the deletion tasks!

Playbook: ec2\_del.yml

## 1\. Terminate all EC2 instances

```yaml
- name: ec2_del
  hosts: localhost
  connection: local
  gather_facts: no
  tasks:
    - name: terminate all running instances
      amazon.aws.ec2_instance:
        region: ap-southeast-3
        state: absent
        filters:
          instance-state-name: running
      tags:
        - ec2_delete_all
        - ec2_terminate
```

## 2\. Deregister AMI

```yaml
    - name: deregister ami
      amazon.aws.ec2_ami:
        image_id: ami-0c1cfb0a18f5e4451
        delete_snapshot: True
        state: absent
      tags:
        - ec2_delete_all
        - ec2_ami_delete
```

## 3\. Delete launch template

```yaml
    - name: delete launch template
      community.aws.ec2_launch_template:
        name: amazonlinux2_httpd_template
        state: absent
      tags:
        - ec2_delete_all
        - ec2_template_delete
```

## 4\. Delete security group

```yaml
    - name: delete security group
      amazon.aws.ec2_group:
        name: ssh-web
        state: absent
        region: ap-southeast-3
      tags:
        - ec2_delete_all
        - ec2_sg_delete
```

## 5\. Delete custom route table (non-main)

```yaml
    - name: delete custom route table
      amazon.aws.ec2_vpc_route_table:
        vpc_id: vpc-0a6bbb5ca26b09679
        region: ap-southeast-3
        route_table_id: rtb-03442f1c5afa52db0
        lookup: id
        state: absent
      tags:
        - ec2_delete_all
        - ec2_rt_delete
```

## 6\. Delete internet gateway

```yaml
    - name: delete internet gateway
      amazon.aws.ec2_vpc_igw:
        vpc_id: vpc-0a6bbb5ca26b09679
        state: absent
      tags:
        - ec2_delete_all
        - ec2_igw_delete
```

## 7\. Delete subnets

```yaml
    - name: delete all subnets in a vpc
      amazon.aws.ec2_vpc_subnet:
        vpc_id: vpc-0a6bbb5ca26b09679
        state: absent
        cidr: "{{ item }}"
      loop: 
        - 10.0.1.0/28
        - 10.0.2.0/28
        - 10.0.3.0/28
      tags:
        - ec2_delete_all
        - ec2_subnet_delete
```

## 8\. Delete VPC

Make sure nothing is associated with this VPC before we delete it. That's why I said that we have to do the steps above sequentially.

```yaml
    - name: delete vpc
      amazon.aws.ec2_vpc_net:
        name: custom_vpc
        region: ap-southeast-3
        cidr_block: 10.0.0.0/16
        purge_cidrs: true
        state: absent
      tags:
        - ec2_delete_all
        - ec2_vpc_delete
```

## 9\. Delete key pair

```yaml
    - name: delete keypair
      amazon.aws.ec2_key:
        name: ec2-user
        state: absent
      tags:
        - ec2_delete_all
        - ec2_key_delete
```

**Run the playbook!**

```bash
$ ansible-playbook -i host.yml ec2_del.yml 

PLAY [ec2_del] **********************************************************************************************************************************************************

TASK [terminate all running instances] **********************************************************************************************************************************
changed: [127.0.0.1]

TASK [deregister ami] ***************************************************************************************************************************************************
changed: [127.0.0.1]

TASK [delete launch template] *******************************************************************************************************************************************
changed: [127.0.0.1]

TASK [delete security group] ********************************************************************************************************************************************
changed: [127.0.0.1]

TASK [delete custom route table] ****************************************************************************************************************************************
changed: [127.0.0.1]

TASK [delete internet gateway] ******************************************************************************************************************************************
changed: [127.0.0.1]

TASK [delete all subnets in a vpc] **************************************************************************************************************************************
changed: [127.0.0.1] => (item=10.0.1.0/28)
changed: [127.0.0.1] => (item=10.0.2.0/28)
changed: [127.0.0.1] => (item=10.0.3.0/28)

TASK [delete vpc] *******************************************************************************************************************************************************
changed: [127.0.0.1]

TASK [delete keypair] ***************************************************************************************************************************************************
changed: [127.0.0.1]

PLAY RECAP **************************************************************************************************************************************************************
127.0.0.1                  : ok=9    changed=9    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
```

Alright! We already reached the last post in this series to delete all that we have created. Now you can explore more by using your own value based on what you need. That's it for now! Follow me to get notified when a new post is published and I'm looking forward to your feedback. Thank you!