我们可以在Ansible Playbook中使用Jinja2模板语言实现。具体步骤为:
---
- name: Deploy app
hosts: app_servers
vars:
db_host: "{{ hostvars[database_server]['ansible_default_ipv4']['address'] }}"
db_port: "{{ hostvars[database_server]['port'] }}"
# template.j2
database:
host: {{ db_host }}
port: {{ db_port }}
- name: Generate configuration file
template:
src: template.j2
dest: /etc/app/config.yml
这样,就可以基于其他主机的变量构建模板文件了。