RHCE8 练习题:生成主机文件

  • 将一个初始模板文件从 http://materials.example.com/cd/exam_rhce8/hosts.j2 下载到 /home/student/ansible 以便使用该模板文件生成以下文件:
    • 针对每个清单主机包含一行内容,其格式与 /etc/hosts 相同
  • 创建名为 /home/student/ansible/hosts.yml 的playbook ,它将使用此模板在dev主机组中的主机上生成文件 /etc/myhosts
    • 该playbook运行后,dev主机组中的主机上的文件/etc/myhosts 应针对每个受管主机 包含一行内容
    • address fqdn hostname

Answer:

下载模板并编辑

wget -O /home/student/ansible/hosts.j2 http://materials.exmaple.com/cd/exam_rhc8/hosts.j2
vim /home/student/ansible/hosts.j2
*****
*****
{% for host in groups.all %}
{{ hostvars[host].ansible_facts.default_ipv4.address }} {{ hostvars[host].ansible_facts.fqdn }} {{ hostvars[host].ansible_facts.hostname }}
{% endfor %}

编写hosts.yml

vim /home/student/ansible/hosts.yml
---
- name: create myhosts
  hosts: all
  tasks:
    - name: hosts.j2
      template:
        src: hosts.j2
        dest: /etc/myhosts
      when: inventory_hostname in groups.dev
ansible-playbook hosts.yml

验证

ansible dev -a 'cat /etc/myhosts'

file