Search code examples
amazon-web-servicesterraformterraform-provider-awsserverless

Managing secret in AWS Secret manager


I am deploying network VPC in AWS using Terraform. We have a standard-defined CIDR range for VPC within the R&D organization.

Here is my Terraform block to create VPC.

    resource "aws_vpc" "my_vpc" {
  cidr_block = var.vpc_cidr   # "10.32.0.0/24"
  instance_tenancy = "default"
  tags = {
    "Name" = "file-transfer-vpc-${var.environment}"
  }
}

I am wondering if I can invoke third-party API in Terraform to get

vpc_cidr

and pass it to the VPC module from the main.tf file. Terraform documentation doesn't have any example of third-party API.

Currently, I have defined CIDR manually in .tfvar file and used the below commands to pass when Terraform is running.

terraform plan -var-file="dev.auto.tfvars"
terraform apply -var-file="dev.auto.tfvars"

Please help if anyone has implemented a similar use case before.

Thanks in advance.


Solution

  • One approach I like to use in these use-cases is data resources. You can simply provide the name of the VPC, and using a data resource fetch all the data of this resource from AWS at runtime.

    This is an example from TF docs

    variable "vpc_id" {}
    
    data "aws_vpc" "selected" {
      id = var.vpc_id
    }
    
    resource "aws_subnet" "example" {
      vpc_id            = data.aws_vpc.selected.id
      availability_zone = "us-west-2a"
      cidr_block        = cidrsubnet(data.aws_vpc.selected.cidr_block, 4, 1)
    }
    

    This way you only need to keep the logic names as vars, and not the internal data (such as CIDRs, subnet addressing, etc.)

    You can use data blocks to fetch information about many types of resources. Check out Terraform Data Sources docs.

    I also post a blogpost on why I prefer to use data sources over remote state here.