Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reference a resource created by a Terraform module

Tags:

I'm using the AWS VPC Terraform module to create a VPC. Additionally, I want to create and attach an Internet Gateway to this VPC using the aws_internet_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_internet_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?

like image 633
GuiTeK Avatar asked Oct 14 '18 16:10

GuiTeK


People also ask

How do you reference a module Terraform?

Modules on the public Terraform Registry can be referenced using a registry source address of the form <NAMESPACE>/<NAME>/<PROVIDER> , with each module's information page on the registry site including the exact address to use.

What is the name assigned by Terraform to reference this resource?

A block resource "azurerm_resource_group" "dev" declares a resource with the address azurerm_resource_group. dev in the current module, so azurerm_resource_group. dev is how you'd refer to this object from expressions elsewhere in the same module.

What is the difference between module and resources in Terraform?

Using modules in terraform is similar to using resources except we use module clause for modules instead of resource clause. In modules, we only specify a name, which is used elsewhere in the configuration to reference module outputs. Source parameter is a required field for modules.

What is source in Terraform module?

The source argument in a module block tells Terraform where to find the source code for the desired child module. Terraform uses this during the module installation step of terraform init to download the source code to a directory on local disk so that it can be used by other Terraform commands.


1 Answers

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.

like image 64
Jamie Starke Avatar answered Oct 02 '22 16:10

Jamie Starke