在Ansible中,可以使用主机变量来为不同的主机在配置文件中的同一变量赋予不同的值。以下是一个代码示例:
[webservers]
web1 ansible_host=192.168.1.10 http_port=8080
web2 ansible_host=192.168.1.11 http_port=8080
web3 ansible_host=192.168.1.12 http_port=8080
---
- name: Configure web servers
hosts: webservers
become: true
tasks:
- name: Set http_port variable
set_fact:
http_port: "{{ http_port }}"
- name: Generate configuration file
template:
src: templates/config.j2
dest: /etc/myapp/config.conf
http_port = {{ http_port }}
在这个示例中,{{ http_port }}是一个变量,将会根据每个主机的变量值来替换。然后,Ansible会根据模板生成配置文件。
这样,每个主机在配置文件中的同一变量http_port都可以根据其在inventory文件中定义的变量值而不同。