生成主机文件
将一个初始模板文件从 http://materials/hosts.j2 下载到 /home/greg/ansible
完成该模板,以便用它生成以下文件:针对每个清单主机包含一行内容,其格式与 /etc/hosts 相同
创建名为 /home/greg/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.9 workstation.lab.example.com workstation
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
#编写模版文件
vim hosts.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 %}
#编写playbook
vim /home/greg/ansible/hosts.yml
如下:
---
- hosts: all
tasks:
- name: /etc/myhosts
template:
src: hosts.j2
dest: /etc/myhosts
when: inventory_hostname in groups['dev']
#查看
ansible dev -m shell -a 'cat /etc/myhosts'