amazon-web-servicesterraformterraform-provider-aws

Passing variable from one module to another


I am creating a Terraform module for AWS VPC creation.

Here is my directory structure

➢  tree -L 3
.
├── main.tf
├── modules
│   ├── subnets
│   │   ├── main.tf
│   │   ├── outputs.tf
│   │   └── variables.tf
│   └── vpc
│       ├── main.tf
│       ├── outputs.tf
│       └── variables.tf
└── variables.tf

3 directories, 12 files

In the subnets module, I want to grab the vpc id of the vpc (sub)module.

In modules/vpc/outputs.tf I use:

output "my_vpc_id" {
  value = "${aws_vpc.my_vpc.id}"
}

Will this be enough for me doing the following in modules/subnets/main.tf ?

resource "aws_subnet" "env_vpc_sn" {
   ...
   vpc_id                  = "${aws_vpc.my_vpc.id}"
}

Solution

  • Your main.tf (or wherever you use the subnet module) would need to pass this in from the output of the VPC module and your subnet module needs to take is a required variable.

    To access a module's output you need to reference it as module.<MODULE NAME>.<OUTPUT NAME>:

    In a parent module, outputs of child modules are available in expressions as module... For example, if a child module named web_server declared an output named instance_ip_addr, you could access that value as module.web_server.instance_ip_addr.

    So your main.tf would look something like this:

    module "vpc" {
      # ...
    }
    
    module "subnets" {
      vpc_id = "${module.vpc.my_vpc_id}"
      # ...
    }
    

    and subnets/variables.tf would look like this:

    variable "vpc_id" {}