Terraform – 使用count的嵌套循环

我正在尝试在terraform中使用嵌套循环。 我有两个列表variableslist_of_allowed_accountslist_of_images ,并寻找迭代列表list_of_images ,然后迭代列表list_of_allowed_accounts

这是我的terraform代码。

 variable "list_of_allowed_accounts" { type = "list" default = ["111111111", "2222222"] } variable "list_of_images" { type = "list" default = ["alpine", "java", "jenkins"] } data "template_file" "ecr_policy_allowed_accounts" { template = "${file("${path.module}/ecr_policy.tpl")}" vars { count = "${length(var.list_of_allowed_accounts)}" account_id = "${element(var.list_of_allowed_accounts, count.index)}" } } resource "aws_ecr_repository_policy" "repo_policy_allowed_accounts" { count = "${length(var.list_of_images)}" repository = "${element(aws_ecr_repository.images.*.id, count.index)}" count = "${length(var.list_of_allowed_accounts)}" policy = "${data.template_file.ecr_policy_allowed_accounts.rendered}" } 

这是一个等同于我正在尝试做的事情。

 for image in alpine java jenkins do for account_id in 111111111 2222222 do // call template here using variable 'account_id' and 'image' done done 

Terraform没有直接支持这种嵌套迭代,但我们可以用一些算术来伪造它。

 variable "list_of_allowed_accounts" { type = "list" default = ["1111", "2222"] } variable "list_of_images" { type = "list" default = ["alpine", "java", "jenkins"] } data "template_file" "ecr_policy_allowed_accounts" { count = "${length(var.list_of_allowed_accounts) * length(var.list_of_images)}" template = "${file("${path.module}/ecr_policy.tpl")}" vars { account_id = "${var.list_of_allowed_accounts[count.index / length(var.list_of_images)]}" image = "${var.list_of_images[count.index % length(var.list_of_images)]}" } } resource "aws_ecr_repository_policy" "repo_policy_allowed_accounts" { count = "${data.template_file.ecr_policy_allowed_accounts.count}" repository = "${var.list_of_images[count.index % length(var.list_of_images)]}" policy = "${data.template_file.ecr_policy_allowed_accounts.*.rendered[count.index]}" } 

由于我们要为每个帐户和图像组合创build一个策略模板,所以template_file数据块上的count是两个相乘的。 然后,我们可以使用除法和模运算从count.index返回到每个列表中的单独索引。

由于我没有你的政策模板的副本,我只是使用占位符; 这个configuration因此给出了以下计划:

 + aws_ecr_respository_policy.repo_policy_allowed_accounts.0 policy: "policy allowing 1111 to access alpine" repository: "alpine" + aws_ecr_respository_policy.repo_policy_allowed_accounts.1 policy: "policy allowing 1111 to access java" repository: "java" + aws_ecr_respository_policy.repo_policy_allowed_accounts.2 policy: "policy allowing 1111 to access jenkins" repository: "jenkins" + aws_ecr_respository_policy.repo_policy_allowed_accounts.3 policy: "policy allowing 2222 to access alpine" repository: "alpine" + aws_ecr_respository_policy.repo_policy_allowed_accounts.4 policy: "policy allowing 2222 to access java" repository: "java" + aws_ecr_respository_policy.repo_policy_allowed_accounts.5 policy: "policy allowing 2222 to access jenkins" repository: "jenkins" 

每个策略实例都适用于不同的帐户ID和图像对,涵盖所有组合。

基本上问题是在数据“template_file”中,account_id不能被设置为你认为的方式,因为在你的情况计数只是另一个variables,永远不会增加/改变。 只是说,因为我想念你的问题到底是什么。