UserAlice
UserAlice

Reputation: 105

Using local variables

I am trying to understand: - how to use locals as defined here.

So, I have a directory structure like this: my-example/ modules/ test/ security-groups/ main.tf vpc/ main.tf

code in my-examples/modules/test/vpc/main.tf:

variable "vpc_name" {
  default = "Test"
}

resource "aws_vpc" "test_vpc" {
  cidr_block            = "172.31.0.0/16"
  enable_dns_support    = true
  enable_dns_hostnames  = true

  tags {
    Name = "${var.vpc_name}:VPC"
    Environment = "${var.vpc_name}"
  }
}

locals {
  id_vpc = "${aws_vpc.test_vpc.id}"
}

module "security_groups" {
  source = "../security-groups"
  id_vpc = "${local.id_vpc}"
}

The idea is to be able to use id_vpc in my-examples/modules/security-group/main.tf like so:

resource "aws_security_group" "bastion_sg" {
  vpc_id = id_vpc
  name = "Bastion-SG"

  ingress {
    from_port = 22
    to_port = 22
    protocol = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }

}

Yet, I keep getting this error: Errors:

  * 1 error(s) occurred:

  * module root: module security_groups: id_vpc is not a valid parameter

Can someone please explain to me why the local variable isn't being evaluated? It would be greatly apprecaited. Thank you.

Upvotes: 3

Views: 10221

Answers (2)

Calum Halpin
Calum Halpin

Reputation: 2105

Local values are accessed like local.<name>. See the docs.

Using Local Values

Once a local value is declared, you can reference it in expressions as local.<NAME>.

Note: Local values are created by a locals block (plural), but you reference them as attributes on an object named local (singular). Make sure to leave off the "s" when referencing a local value!

resource "aws_instance" "example" {
  # ...

  tags = local.common_tags
}

A local value can only be accessed in expressions within the module where it was declared.

Upvotes: 0

BMW
BMW

Reputation: 45333

the name in module security_groups looks fine. But you do have issue with the code in module security_groups

Please change

from

resource "aws_security_group" "bastion_sg" {
  vpc_id = id_vpc
  name = "Bastion-SG"
  ...
}

to

resource "aws_security_group" "bastion_sg" {
   vpc_id = ${var.id_vpc}
  name = "Bastion-SG"
  ...
}

And define variable id_vpc in the module as well.

Upvotes: 5

Related Questions