0%

RHCE (EX294) - 生成主机文件

生成主机文件

将一个初始模板文件从 http://materials/hosts.j2 下载到 /home/greg/ansible

完成该模板,以便用它生成以下文件:针对每个清单主机包含一行内容,其格式与 /etc/hosts 相同

创建名为 /home/greg/ansible/hosts.yml 的 playbook,它将使用此模板在 dev 主机组中的主机上生成文件 /etc/myhosts

该 playbook 运行后,dev 主机组中主机上的文件 /etc/myhosts 应针对每个受管主机包含一行内容:

1
2
3
4
5
6
7
8
127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4
::1 localhost localhost.localdomain localhost6 localhost6.localdomain6

172.25.250.9 node1.lab.example.com node1
172.25.250.10 node2.lab.example.com node2
172.25.250.11 node3.lab.example.com node3
172.25.250.12 node4.lab.example.com node4
172.25.250.13 node5.lab.example.com node5

注:清单主机名称的显示顺序不重要。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
[greg@control ansible]$ wget http://materials/hosts.j2
[greg@control ansible]$ 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_facts']['default_ipv4']['address'] }} {{ hostvars[host]['ansible_facts']['nodename'] }} {{ hostvars[host]['ansible_facts']['hostname'] }}
{% endfor %}
[greg@control ansible]$ vim /home/greg/ansible/hosts.yml
---
- name: 生成主机文件
hosts: all
tasks:
- name: Template a file to /etc/myhosts
template:
src: hosts.j2
dest: /etc/myhosts
when: inventory_hostname in groups['dev']
[greg@control ansible]$ ansible-playbook hosts.yml
[greg@control ansible]$ ansible dev -a 'cat /etc/myhosts'
node1 | CHANGED | rc=0 >>
127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4
::1 localhost localhost.localdomain localhost6 localhost6.localdomain6

172.25.250.9 node1.lab.example.com node1
172.25.250.10 node2.lab.example.com node2
172.25.250.13 node5.lab.example.com node5
172.25.250.11 node3.lab.example.com node3
172.25.250.12 node4.lab.example.com node4