Bootstrap FreeKB - Amazon Web Services (AWS) - Create Subnet using Terraform
Amazon Web Services (AWS) - Create Subnet using Terraform


Let's say you have the following files on your Terraform server.

├── required_providers.tf
├── virtual_private_clouds (directory)
│   ├── data.tf
│   ├── outputs.tf
│   ├── provider.tf
│   ├── resources.tf

 

required_providers.tf will almost always have this.

terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
    }
  }
}

 

Let's say provider.tf has the following. In this example, the "default" profile in /home/username/.aws/config and /home/username/.aws/credentials is being used. This assumes you have setup Terraform as described in Amazon Web Services (AWS) - Getting Started with Terraform.

provider "aws" {
  alias   = "default"
  profile = "default"
  region  = "default"
}

 

And resources.tf in your virtual_private_clouds directory could have something like this.

resource "aws_vpc" "my_aws_vpc" {
  cidr_block = "10.0.0.0/16"
}

resource "aws_subnet" "my_aws_subnet" {
  for_each = {
    "us-east-1a" = "10.0.1.0/24"
    "us-east-1b" = "10.0.2.0/24"
    "us-east-1c" = "10.0.3.0/24"
  }

  vpc_id            = aws_vpc.my_aws_vpc.id
  availability_zone = each.key
  cidr_block        = each.value

  tags = {
    Name = "${each.key}-subnet"
  }
}

 

You may need to reissue the terraform init command.

~]# terraform init
Initializing the backend...
Initializing modules...
Initializing provider plugins...
Terraform has been successfully initialized!

 

The terraform plan command can be used to see what Terraform will try to do.

terraform plan

 

By default, the terraform.tfstate file should be found in your root module directory (/usr/local/terraform/aws in this example).

  • If the VPC Subnet does not exist and the terraform.tfstate file does not contain the VPC Subnet, Terraform will create the VPC Subnet.
  • If the VPC Subnet exists and the terraform.tfstate file contains the VPC Subnet and a difference is found between the vpc.tf file and the terraform.tfstate file, Terraform will update the VPC Subnet.
  • If the VPC Subnet exists and the terraform.tfstate file contains the VPC Subnet and the VPC Subnet is removed from the vpc.tf file, Terraform will destroy (delete) the VPC Subnet.

The terraform apply command can be used to create, update or delete the VPC Subnet.

terraform apply

 

In this example, three Virtual Private Cloud (VPC) Subnets were created.

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter c4e8b4 in the box below so that we can be sure you are a human.