我遇到了同样的问题,我想构建 2 个不同的 AMI(一个用于暂存,一个用于生产),它们之间的唯一区别是在配置期间应用的 ansible 组。在@Rickard ov Essen 的答案的基础上,我使用jq 编写了一个bash 脚本来复制配置的构建器部分。
这是我的packer.json 文件:
{
"builders": [
{
"type": "amazon-ebs",
"name": "staging",
"region": "ap-southeast-2",
"source_ami_filter": {
"filters": {
"virtualization-type": "hvm",
"name": "ubuntu/images/hvm-ssd/ubuntu-xenial-16.04-amd64-server-*",
"root-device-type": "ebs"
},
"owners": ["099720109477"],
"most_recent": true
},
"instance_type": "t2.nano",
"ssh_username": "ubuntu",
"force_deregister": true,
"force_delete_snapshot": true,
"ami_name": "my-ami-{{ build_name }}"
}
],
"provisioners": [
{
"type": "ansible",
"playbook_file": "provisioning/site.yml",
"groups": ["{{ build_name }}"]
}
]
}
ansible 供应者使用变量build_name 来选择要运行的ansible 组。
然后我有一个运行打包程序构建的 bash 脚本 build.sh:
#!/bin/bash
jq '.builders += [.builders[0] | .name = "production"]' packer.json > packer_temp.json
packer build packer_temp.json
rm packer_temp.json
您可以在this jqplay 上看到packer_temp.json 文件的样子。
如果您需要添加更多 AMI,您可以继续添加更多 jq 过滤器:
jq '.builders += [.builders[0] | .name = "production"] | .builders += [.builders[0] | .name = "test"]
这将为 test 添加另一个 AMI。