Menu
blog.headdesk.me
blog.headdesk.me

Terraform module: Delete default VPCs

Posted on 2022/08/052022/08/05

Terraform itself does not have the capability to delete default VPCs. In this example, I will use terraform and a shell script to perform the deletion.

The delete-default-vpcs module

The module itself contains just 1 resource, which uses the local exec provisioner to execute a script

resource "null_resource" "shell" {
provisioner "local-exec" {
command = "/bin/bash -c '${path.module}/exec.sh ${var.region-name}'"
}
}

The exec.sh uses aws-cli to delete the default VPC and dependent resources

#!/bin/bash

region=$1
vpc=$(aws ec2 --region ${region} describe-vpcs --filter Name=isDefault,Values=true | jq -r .Vpcs[0].VpcId)
if [ "${vpc}" = "null" ]; then
  echo "Default vpc not exist"
  exit 0
fi

aws ec2 --region ${region} describe-internet-gateways --filter Name=attachment.vpc-id,Values=${vpc} | jq -r '.InternetGateways[0].InternetGatewayId' | while read igw; do
  echo "Removing internet gateway ${igw}"
  aws ec2 --region ${region} detach-internet-gateway --internet-gateway-id ${igw} --vpc-id ${vpc}
  aws ec2 --region ${region} delete-internet-gateway --internet-gateway-id ${igw}
done

aws ec2 --region ${region} describe-subnets --filters Name=vpc-id,Values=${vpc} | jq -r '.Subnets[].SubnetId' | while read subnet; do
  echo "Removing subnet ${subnet}"
  aws ec2 --region ${region} delete-subnet --subnet-id ${subnet}
done

echo "Removing vpc ${vpc}"
aws ec2 --region ${region} delete-vpc --vpc-id ${vpc}

The root module

The root module calling the delete-default-vpcs module looks like this. It uses the aws_regions data source to query enabled regions, then provide it to the delete-default-vpcs module.

data "aws_regions" "current" {}

module delete-default-vpc {
source = "./module/delete-default-vpc"
for_each = data.aws_regions.current.names
region-name = each.value
}

facebookShare on Facebook
TwitterTweet

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Full text search

Recent Posts

  • Terraform and segregated permissions
  • LVM Compression and Deduplication
  • Edit gpg encrypted file with vim
  • Lelit Elizabeth PL92T Pressure Tuning
  • jq transformation
  • aws (8)
  • coffee (1)
  • headfi (1)
  • linux (6)
  • others (58)
  • security (2)
  • tech (36)
  • wordpress (2)

apache aws awscli azure backup clearlinux cloud coffee docker DOCP ec2 EL8 epyc espresso featured gpg jenkins kernel lelit linux lvm meltdown memory MFA mikrotik php python rdp Redhat RHEL roasting rpm Ryzen site-to-site snapshot spectre tech terraform tuning ubuntu ubuntu upgrade vim vpn wordpress xdotool

©2023 blog.headdesk.me | Powered by SuperbThemes & WordPress