地形“循环”没用吗?还是我错过了什么?

时间:2019-03-12 23:49:37

标签: terraform

我今天写了一些使用“循环”的配置,但是直到后来我才想知道这是否是正确的路径,因为terraform将状态文件中的资源保留为列表/数组。

请考虑以下配置:

Greeter

运行“ terraform apply”将创建用户,并在状态文件中创建以下资源:

  • aws_iam_user.users [0]
  • aws_iam_user.users [1]
  • aws_iam_user.users [2]

但是,例如,如果我删除了前两个用户之一,就像这样:

locals {
    users_list = [ "ab", "cd", "ef" ]
}

resource "aws_iam_user" "users" {
    count = "${length(local.users_list)}"
    name = "${local.users_list["${count.index}"]}"
    path = "/"
}

然后terraform将尝试更改状态文件([0]->“ cd”,[1]->“ ef”)中的资源,以及用户本身在AWS中的资源,这可能是灾难性的,因为每个用户都将拥有自己的密钥,这样做会造成混乱。这也与其他资源类型有关,尽管有些资源可以删除并再次创建不会造成混乱,但这仍然是错误的。

那么,对我的问题,就像标题中一样-也许我把这一切弄错了?还是这只是它的工作方式? (使整个“循环”机制失效)

1 个答案:

答案 0 :(得分:3)

v0.11.x之前的

terraform实际上并不正式支持循环。 count.index作为循环的使用方式来自博客Terraform tips & tricks: loops, if-statements, and gotchas

从0.12版本开始(当前仍处于测试版),它支持带有新关键字for_each的循环,但是我仍然不能保证它是否可以解决您所提出的问题。 / p>

因此,我详细说明了问题所在以及如何解决该问题,像@Aniket Chopade这样的人都可以了解此问题的出处。

更改本地人后,

$ terraform apply -auto-approve
aws_iam_user.users[0]: Refreshing state... (ID: ab)
aws_iam_user.users[1]: Refreshing state... (ID: cd)
aws_iam_user.users[2]: Refreshing state... (ID: ef)
aws_iam_user.users[2]: Destroying... (ID: ef)
aws_iam_user.users[1]: Modifying... (ID: cd)
  name: "cd" => "ef"
aws_iam_user.users[0]: Modifying... (ID: ab)
  name: "ab" => "cd"
aws_iam_user.users[2]: Destruction complete after 2s

Error: Error applying plan:

2 error(s) occurred:

* aws_iam_user.users[0]: 1 error(s) occurred:

* aws_iam_user.users.0: Error updating IAM User ab: EntityAlreadyExists: User with name cd already exists.
    status code: 409, request id: 24853da7-452c-11e9-a853-bf4c89d8ebba
* aws_iam_user.users[1]: 1 error(s) occurred:

* aws_iam_user.users.1: Error updating IAM User cd: EntityAlreadyExists: User with name ef already exists.
    status code: 409, request id: 24839027-452c-11e9-b3d5-3deb12943195

我必须taint这些资源,将它们标记为要销毁,然后再次应用。

$ terraform taint aws_iam_user.users.1
The resource aws_iam_user.users.1 in the module root has been marked as tainted!

$ terraform taint aws_iam_user.users.0
The resource aws_iam_user.users.0 in the module root has been marked as tainted!

$ terraform apply -auto-approve
...
aws_iam_user.users[0]: Destroying... (ID: ab)
aws_iam_user.users[1]: Destroying... (ID: cd)
aws_iam_user.users[0]: Destruction complete after 2s
aws_iam_user.users[0]: Creating...
  arn:           "" => "<computed>"
  force_destroy: "" => "false"
  name:          "" => "cd"
  path:          "" => "/"
  unique_id:     "" => "<computed>"
aws_iam_user.users[1]: Destruction complete after 2s
aws_iam_user.users[1]: Creating...
  arn:           "" => "<computed>"
  force_destroy: "" => "false"
  name:          "" => "ef"
  path:          "" => "/"
  unique_id:     "" => "<computed>"

我的结论是,在当前情况下,taint会迫使Terraform创建新资源的资源如果您更改列表中的顺序