将变量传递给子模块

问题描述 投票:0回答:2

我正在尝试使用以下语法将变量从

root module
传递到
child module

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

当我尝试在模块内访问

account_id
时,会抛出错误。

terraform
2个回答
32
投票

您需要声明模块在模块级别本身使用的任何变量:

variable "account_id" {
}

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

7
投票

James 是正确的,但他的语法仅适用于字符串变量。对于其他人,您必须指定“空白默认值”:

variable "passed_list_var" {
    default = []
}

variable "passed_map_var" {
    default = {}
}
© www.soinside.com 2019 - 2024. All rights reserved.