Terraform将变量传递给子模块

Bro*_*shi 8 terraform

我试图使用以下语法将变量从root modulea 传递给a 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
Run Code Online (Sandbox Code Playgroud)

/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      = []
}
Run Code Online (Sandbox Code Playgroud)

当我尝试在模块内访问时account_id会抛出一个错误.

Jam*_*rpe 14

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

variable "account_id" {
}

resource "aws_iam_policy_attachment" "myName" {
    name       = "myName"
    policy_arn = "arn:aws:iam::${var.account_id}:policy/myName"
    groups     = []
    users      = []
    roles      = []
}
Run Code Online (Sandbox Code Playgroud)


小智 6

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

variable "passed_list_var" {
    default = []
}

variable "passed_map_var" {
    default = {}
}
Run Code Online (Sandbox Code Playgroud)