Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Terraform pass variables to a child module

Tags:

terraform

I am trying to pass a variable from the root module to a child module with the following syntax:

main.tf:

provider "aws" {
  version = "~> 1.11"
  access_key = "${var.aws_access_key}"
  secret_key = "${var.aws_secret_key}"
  region     = "${var.aws_region}"
}

module "iam" {
  account_id = "${var.account_id}"
  source = "./modules/iam"
}

 * account_id value is stored on variables.tf in the root folder

/modules/iam/iam.tf

resource "aws_iam_policy_attachment" "myName" {
    name       = "myName"
    policy_arn = "arn:aws:iam::${var.account_id}:policy/myName" <-- doesnt work
    groups     = []
    users      = []
    roles      = []
}

when I try to access within the module to account_id an error is thrown.

like image 241
Broshi Avatar asked Mar 28 '18 13:03

Broshi


2 Answers

You need to declare any variables that a module uses at the module level itself:

variable "account_id" {
}

resource "aws_iam_policy_attachment" "myName" {
    name       = "myName"
    policy_arn = "arn:aws:iam::${var.account_id}:policy/myName"
    groups     = []
    users      = []
    roles      = []
}
like image 191
James Thorpe Avatar answered Nov 19 '22 18:11

James Thorpe


James is correct but his syntax will work just for string variables. With others you have to specify the 'blank default':

variable "passed_list_var" {
    default = []
}

variable "passed_map_var" {
    default = {}
}
like image 32
Ondrej Bardon Avatar answered Nov 19 '22 19:11

Ondrej Bardon