Search code examples
terraforminfrastructure-as-code

Terraform - populate variable values from same script


I'm very green to terraform; infact this is part of my training.

I'm wondering; is there a way to get terraform to store a specific value (as variable) from the previous command within the same file.

Example:

    resource "aws_vpc" "TestVPC"{
    cidr_block = "192.168.0.0/16"
    instance_tenancy = "default"
    enable_dns_hostnames="True"
    tags{
        Name="TestVpc"
    }
}
resource "aws_subnet" "TestSubnet"{
    vpc_id = "${var.aws_vpc_id}" ##This is where I'd like to populate the aws_vpc_id from the VPC creation step above.
    cidr_block = "192.168.0.0/24"
    map_public_ip_on_launch="True"
    availability_zone = "us-east-2a"
    tags{
        Name="TestSubnet"
    }
}

Help is greatly appreciated.

Thanks.


Solution

  • You can use the output from the creation of the VPC, ${aws_vpc.TestVPC.id}

    Like so:

    resource "aws_vpc" "TestVPC" {
      cidr_block           = "192.168.0.0/16"
      instance_tenancy     = "default"
      enable_dns_hostnames = "True"
    
      tags {
        Name = "TestVpc"
      }
    }
    
    resource "aws_subnet" "TestSubnet" {
      vpc_id                  = "${aws_vpc.TestVPC.id}"
      cidr_block              = "192.168.0.0/24"
      map_public_ip_on_launch = "True"
      availability_zone       = "us-east-2a"
    
      tags {
        Name = "TestSubnet"
      }
    }