Create a playbook called /home/student/ansible/hwreport.yml that produces an output file called /root/hwreport.txt on all managed nodes with the following information:
Inventory host name
Total memory in MB
BIOS version
Size of disk device sda
Size of disk device sdb
Each line of the output file contains a single key=value pair.
Your playbook should:
Download the file from http://example.classroom.com/cd/exam_rhce8/hwreport.empty and save it as /root/hwreport.txt
Modify /root/hwreport.txt with the correct values
If a hardware item does not exist, the associated value should be set to NONE
【題前說明】
這是會用到大量變數概念的題目,解法也很多種,我學的只是一種比較懶惰的寫法,分數可能不高,但仍可以達到題目所要求的結果。首先要去data主機上下載hwreport.empty檔到本地的/root底下,將檔名改成hwreport.txt,檔案裡面的參數很重要,要依照裡面的參數來編輯ansible用部署的變數。基本的邏輯是:key去讀取hwreport.txt裡面的所對應文字當標題,並當作變數的參照;value根據ansible facts去每一台node抓取資料會來當值,並放置到所對應的key後面,若沒有找到相對應的值則輸出NONE。敘述這段好像在繞口令,這題也是我在練習時花免多時間去理解的,難度大概可以排名前三。
一.解題過程:
[student@workstation ansible]$ wget http://example.classroom.com/cd/exam_rhce8/hwreport.empty
\\可以先把hwreport.empty下載下來看裡面的內容
[student@workstation ansible]$ cat hwreport.empty
# Hardware report
HOST=inventoryhostname
MEMORY=memory_in_MB
BIOS=BIOS_version
DISK_SIZE_SDA=disk_sda_size
DISK_SIZE_SDB=disk_sdb_size
[student@workstation ansible]$ vim hwreport.yml
---
- name: create hwreport
hosts: all
vars:
hw:
- hw_key: HOST
hw_value: "{{ ansible_hostname | default('NONE',true) }}"
- hw_key: MEMORY
hw_value: "{{ ansible_memtotal_mb | default('NONE',true) }}"
- hw_key: BIOS
hw_value: "{{ ansible_bios_version | default('NONE',true) }}"
- hw_key: DISK_SIZE_SDA
hw_value: "{{ ansible_devices.sda.size | default('NONE',true) }}"
- hw_key: DISK_SIZE_SDB
hw_value: "{{ ansible_devices.sdb.size | default('NONE',true) }}"
tasks:
- name: fetch hwreport
get_url:
url: http://example.classroom.com/cd/exam_rhce8/hwreport.empty
dest: /root/hwreport.txt
- name: modify content
lineinfile:
path: /root/hwreport.txt
regexp: "^{{ item.hw_key }}"
line: "{{ item.hw_key}}={{ item.hw_value }}"
loop: "{{ hw }}"
二.驗證結果
[student@workstation ansible]$ ansible-playbook -C hwreport.yml \\試跑看看
[student@workstation ansible]$ ansible-playbook hwreport.yml
驗證看看是否每一台node都有抓到檔案 |
三.恢復解題前的環境
[student@workstation ansible]$ vim 13-lab-hwreport-stop.yml
---
- name: remove hwreport file
hosts: all
tasks:
- name: remove hwreport file
file:
path: /root/hwreport.txt
state: absent
- name: remove hwreport.yml
hosts: 127.0.0.1
tasks:
- name: remove hwrepot.yml
file:
path: /home/student/ansible/hwreport.yml
state: absent
- name: remove hwreport.empty
file:
path: /home/student/ansible/hwreport.empty
state: absent
[student@workstation ansible]$ ansible-play 13-lab-hwreport-stop.yml
沒有留言:
張貼留言