Download an initial template file from http://example.classroom.com/cd/materials/hosts.j2 to /home/student/ansible
Complete the template so that it can be used to generate a file with a line for each inventory host in the same format as /etc/hosts
Download the file from http://example.classroom.com/cd/materials/hosts.yml to /home/student/ansible/hosts.yml. This playbook will use the template to generate the file /etc/myhosts on hosts in the dev host group.
- Do not make any changes to the playbook.
When the playbook is run, the file /etc/myhosts on hosts in the dev host group should have a line for each managed host:
127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4
::1 localhost localhost.localdomain localhost6 localhost6.localdomain6
172.25.250.10 node1.example.com node1
172.25.250.11 node2.example.com node2
172.25.250.12 node3.example.com node3
172.25.250.13 node4.example.com node4
172.25.250.14 node5.example.com node5
NOTE: The order in which the inventory host names appear is not important.
【題前說明】
這一題要做的是去data主機下載兩個檔案,一個是hosts.j2作為template;另一個是hosts.yml作部署用檔案,比較困難的是又要用到查詢ansible facts的能力,將查詢到的node上的facts,寫在hosts.j2裡面當作變數,並且作一個迴圈,讓最後ansible跑部署的時候把五台node的IP address、FQDN和Hostname寫成一個myhost檔,然後只放在dev群組的主機指定路徑底下。
一.解題過程:
[student@workstation ansible]$ wget http://example.classoom.com/cd/exam_ehce8/hosts.yml
[student@workstation 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.fqdn }} {{ hostvars[host].ansible_facts.hostname }}
{% endfor %}
---
- name: create myhosts
hosts: all
tasks:
- name: create myhosts
template:
src: hosts.j2
dest: /etc/myhosts
when: ansible_hostname in groups.dev
---
- name: remove hosts.yml
hosts: 127.0.0.1
tasks:
- name: remove hosts.yml
file:
path: /home/student/ansible/hosts.yml
state: absent
- name: remove hosts.j2
hosts: 127.0.0.1
tasks:
- name: remove hosts.j2
file:
path: /home/student/ansible/hosts.j2
state: absent
- name: remove dev myhosts
hosts: dev
tasks:
- name: remove dev myhosts
file:
path: /etc/myhosts
state: absent
沒有留言:
張貼留言