變數不存在

  1. 下載變數格式檔 report1.orig。
    [deyu1@kvm19 ansible]$ wget http://dywang.csie.cyut.edu.tw/materials/report1.orig
    
  2. 查看需要列出報告 report1.orig 的變數。
    # Variables report
    HOST=inventoryhostname
    BIOS=BIOS_version
    VDA_SIZE=disk_vda_size
    VDB_SIZE=disk_vdb_size
    OS=os_family
    
  3. 撰寫 report1.yml 腳本,因為 kvm12 沒有 vdb 硬碟,ansible_devices.vdb.size 不會有定義,執行腳本會報錯無法完成。所以 value 設定使用 var|default('NONE'),當變數 var 不在在時,value 設定成預設值 'NONE',其他變數也都設定預設值 'NONE'。
    [deyu1@kvm19 ansible]$ vim report1.yml 
    [deyu1@kvm19 ansible]$ cat report1.yml 
    ---
    - name: Report variables
      hosts: test
      tasks:
        - copy:
            src: report1.orig
            dest: /root/report1.txt
        - lineinfile:
            path: /root/report1.txt
            regexp: "^{{item.key}}"
            line: "{{item.key}}={{item.value}}"
          loop:
            - { key: "HOST", value: "{{inventory_hostname | default('NONE')}}" }
            - { key: "BIOS", value: "{{ansible_bios_version | default('NONE')}}" }
            - { key: "VDA_SIZE", value: "{{ansible_devices.vda.size | default('NONE')}}" }
            - { key: "VDB_SIZE", value: "{{ansible_devices.vdb.size | default('NONE')}}" }
            - { key: "OS", value: "{{ansible_os_family | default('NONE')}}" }
    
  4. ansible-playbook 執行腳本 report1.yml。
    [deyu1@kvm19 ansible]$ ansible-playbook report1.yml 
    
    PLAY [Report variables] ********************************************************
    
    TASK [Gathering Facts] *********************************************************
    ok: [kvm12]
    
    TASK [copy] ********************************************************************
    changed: [kvm12]
    
    TASK [lineinfile] **************************************************************
    changed: [kvm12] => (item={'key': 'HOST', 'value': 'kvm12'})
    changed: [kvm12] => (item={'key': 'BIOS', 'value': '0.5.1'})
    changed: [kvm12] => (item={'key': 'VDA_SIZE', 'value': '4.00 GB'})
    changed: [kvm12] => (item={'key': 'VDB_SIZE', 'value': 'NONE'})
    changed: [kvm12] => (item={'key': 'OS', 'value': 'RedHat'})
    
    PLAY RECAP *********************************************************************
    kvm12 : ok=3 changed=2 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
    
  5. ansible 使用 shell 模組查看主機 test 的 /root/report1.txt,內容確實已改成變數查詢結果,且 VDB_SIZE=NONE
    [deyu1@kvm19 ansible]$ ansible test -m shell -a "cat /root/report1.txt"
    kvm12 | CHANGED | rc=0 >>
    # Variables report
    HOST=kvm12
    BIOS=0.5.1
    VDA_SIZE=4.00 GB
    VDB_SIZE=NONE
    OS=RedHat