在 Ansible 中使用 GCP(Google云平台) j2 模板时,可能会遇到需要嵌套变量和查找变量的情况。以下是解决该问题的步骤和代码示例:
[gcp_instance]
instance1 ansible_host=1.2.3.4 ip_address=10.0.0.1 region=us-central1-a project=my-project
{% for host in groups['gcp_instance'] %}
{"name": "{{ hostvars[host].project }}-{{ hostvars[host].region }}-{{ host }}",
"type": "instance",
"properties": {
"networkInterfaces": [{"network": "projects/{{ hostvars[host].project }}/global/networks/default"}],
"zone": "{{ hostvars[host].region }}",
"machineType": "projects/{{ hostvars[host].project }}/zones/{{ hostvars[host].region }}/machineTypes/n1-standard-1",
"disks": [
{
"boot": true,
"autoDelete": true,
"initializeParams": {
"sourceImage": "projects/debian-cloud/global/images/family/debian-9"
}
}],
"metadata": {
"items": [
{"key": "startup-script", "value": "{{ lookup('template', './startup.sh.j2') }}"}
]
}
}}
{% endfor %}
#!/bin/bash
echo "My external IP address is {{ ip_address }}"
通过上述步骤,即可在 GCP 上使用 Ansible j2 模板,并嵌套和查找变量。