|
- 生成主机文件
- 将一个初始模板文件从 http://classroom.example.com/content/hosts.j2 下载到/home/student/ansible
- 完成该模板,以便用它生成以下文件:针对每个清单主机包含一行内容,其格式与/etc/hosts 相同
- 创建名为/home/student/ansible/hosts.yml 的 playbook,它将使用此模板在 dev 主机组中的主机上生成文件/etc/myhosts 。
- 该 playbook 运行后, dev 主机组中主机上的文件/etc/myhosts 应针对每个受管主机包含一行内容:
- 127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4
- ::1 localhost localhost.localdomain localhost6 localhost6.localdomain6
- 172.25.250.10 servera.lab.example.com servera
- 172.25.250.11 serverb.lab.example.com serverb
- 172.25.250.12 serverc.lab.example.com serverc
- 172.25.250.13 serverd.lab.example.com serverd
- 注:清单主机名称的显示顺序不重要。
复制代码
不正确的做法(只用事实变量):
- [student@workstation ansible]$ cat hosts.j2
复制代码 127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4
::1 localhost localhost.localdomain localhost6 localhost6.localdomain6
{% for host in groups['all'] %}
{{ ansible_default_ipv4['address'] }} {{ ansible_fqdn }} {{ ansible_hostname }}
{% endfor %}
hosts.yml:
- ---
- - name: Create myhosts
- hosts: dev
- tasks:
- - name: Create myhosts
- template:
- src: hosts.j2
- dest: /etc/myhosts
复制代码- [student@workstation ansible]$ ansible dev -m shell -a 'cat /etc/myhosts'
复制代码 servera | CHANGED | rc=0 >>
127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4
::1 localhost localhost.localdomain localhost6 localhost6.localdomain6
172.25.250.10 servera.lab.example.com servera
172.25.250.10 servera.lab.example.com servera
172.25.250.10 servera.lab.example.com servera
172.25.250.10 servera.lab.example.com servera
结合了静态的清单和动态的事实(可以实现在A机上看到B机的实际情况,A机和B机都是受管节点,他们之间互相“检举”):
https://www.botangdb.com/forum.php?mod=viewthread&tid=1491&page=1&extra=#pid2549
host.j2:
- 127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4
- ::1 localhost localhost.localdomain localhost6 localhost6.localdomain6
- {% for host in groups['all'] %}
- {{ hostvars[host]['ansible_default_ipv4']['address'] }} {{ hostvars[host]['ansible_fqdn'] }} {{ hostvars[host]['ansible_hostname'] }}
- {% endfor %}
复制代码
hosts.yml:
- ---
- - name: Create myhosts
- hosts: all
- tasks:
- - name: Create myhosts
- template:
- src: hosts.j2
- dest: /etc/myhosts
- when:
- ansible_hostname in groups['dev']
复制代码
|
|