简体   繁体   中英

How to reference a resource created by a Terraform module

I'm using the AWS VPC Terraform module to create a VPC. Additionally, I want to create and attach an Inte.net Gateway to this VPC using the aws_inte.net_gateway resource .

Here is my code:

module "vpc" "vpc_default" {
  source = "terraform-aws-modules/vpc/aws"

  name = "${var.env_name}-vpc-default"
  cidr = "10.0.0.0/16"
  enable_dns_hostnames = true
}

resource "aws_internet_gateway" "vpc_default_igw" {
  vpc_id = "${vpc.vpc_default.id}"

  tags {
    Name = "${var.env_name}-vpc-igw-vpcDefault"
  }
}

When I run terraform init , I get the following error:

Initializing modules... - module.vpc

Error: resource 'aws_inte.net_gateway.vpc_default_igw' config: unknown resource 'vpc.vpc_default' referenced in variable vpc.vpc_default.id

How can I reference a resource created by a Terraform module?

Since you're using a module, you need to change the format of the reference slightly. Module Outputs use the form ${module.<module name>.<output name>} . It's also important to note, you can only reference values outputted from a module.

In your specific case, this would become ${module.vpc.vpc_id} based on the VPC Module's Outputs .

Note you can have multiple module instances in a single file:

module "vpc1" "vpc_default" {}
module "vpc2" "vpc_default" {}
module "vpc3" "vpc_default" {}
module "vpc4" "vpc_default" {}

${module.vpc1.vpc_id}
${module.vpc2.vpc_id}
${module.vpc3.vpc_id}
${module.vpc4.vpc_id}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM