【问题标题】:create AMIs from a list with packer使用打包程序从列表中创建 AMI
【发布时间】:2022-01-23 05:10:30
【问题描述】:

假设我有一个变量列表。如何使用它们动态创建多个图像?

variable "targets" {
  type = list(string)
  default = [
    "foo",
    "bar",
    "barz"
  ]
}

source "amazon-ebs" "ubuntu" {
    ...
}

build {
  for_each = var.targets
  name     = each.value
  source "amazon-ebs.ubuntu" {
    ami_name = "${each.value}-{{timestamp}}"
  }
  provisioner "ansible" {
    playbook_file = "playbook.yaml"
    extra_arguments = [
      "--extra-vars", "target=${each.value}",
    ]
  }
}

我收到了错误

An argument named "for_each" is not expected here.

【问题讨论】:

    标签: packer


    【解决方案1】:

    没有像 for_each 这样的东西来迭代构建器。

    但是,您可以通过以下方式实现所需的功能:

    • 定义一个map variable,其中包含一个键/值对,其中包含源名称和相应的值
    • 定义多个源,一个用于您希望构建的每个映像
    • 利用only construct 运行基于源的配置器

    完整示例:

    variable "targets" {
      default = {
        values: {
          first-example: "foo",
          second-example: "bar"
        }
      }
    }
    
    source "null" "first-example" {
      communicator = "none"
    }
    
    source "null" "second-example" {
      communicator = "none"
    }
    
    build {
    
      source "null.first-example" {
        name = "example1"
      }
      source "null.second-example" {
        name = "example2"
      }
    
      sources = [
        "null.first-example",
        "null.second-example"
      ]
    
      provisioner "shell-local" {
        only = [ "null.first-example" ]
        inline = ["echo ${var.targets.values.first-example}"]
      }
      provisioner "shell-local" {
        only = [ "null.second-example" ]
        inline = ["echo ${var.targets.values.second-example}"]
      }
    }
    

    运行packer build .时,上面会输出:

    null.first-example:
    null.first-example: echo foo
    null.first-example: foo
    null.second-example:
    null.second-example: echo bar
    null.second-example: bar
    

    【讨论】:

    • 我觉得这样没用。您将问题从多个构建器转移到多个来源。如果您在没有预定义源的输入中再添加一项,我仍然必须多次声明某些内容,这也会中断。毕竟,这些是在 bz 用户中传递的变量。我不想知道他们的名字和数量。可能我也有跨源重复配置。
    • @TheFool 这很有用,因为您可以将所有变量移动到variables.pkr.hcl 文件中,然后应用相同的逻辑。
    • @TheFool 我最初的想法是使用一个配置器,根据源的名称,从地图中使用正确的条目,但是这种字符串插值似乎不是支持
    • 至少对我没用。它实际上不是很动态。如果列表中突然多了 3 个项目,你会加点什么?它会破裂的。你需要去编辑你的配置。另外,它比我只写 1 个源代码和 3 个小型构建器时更加冗长。如果我必须对它们进行硬编码,我更愿意只编写单独的构建器,仅此而已。你所做的似乎是很多开销而没有实际收益。
    • @TheFool 祝你好运,我不认为你会找到不同的解决方案。
    猜你喜欢
    • 2018-07-14
    • 2017-09-30
    • 2019-01-14
    • 2022-11-25
    • 1970-01-01
    • 2014-09-10
    • 2018-09-27
    • 1970-01-01
    • 2022-01-22
    相关资源
    最近更新 更多