Terraform将变量传递给子模块

时间:2018-03-28 13:01:02

标签: terraform

我尝试使用以下语法将变量从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时会抛出错误。

2 个答案:

答案 0 :(得分:7)

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

variable "account_id" {
}

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

答案 1 :(得分:1)

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

variable "passed_list_var" {
    default = []
}

variable "passed_map_var" {
    default = {}
}