terraform

Pass variables to a child module


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.


Solution

  • 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      = []
    }