修改檔案–不同群組不同內容

  1. 修改 shelli1.yml 腳本成 shell2.yml,dev, test, prod 群組主機的 /etc/issue,寫入字串不同。
    [deyu1@kvm19 ansible]$ vim shell2.yml 
    [deyu1@kvm19 ansible]$ cat shell2.yml
    ---
    - hosts: all
      tasks:
        - ansible.builtin.shell: 
            echo 'Development {{inventory_hostname}}' > /etc/issue
          when: '"dev" in group_names'
        - ansible.builtin.shell: 
            echo 'Test {{inventory_hostname}}' > /etc/issue
          when: '"test" in group_names'
        - ansible.builtin.shell: 
            echo 'Production {{inventory_hostname}}' > /etc/issue
          when: '"prod" in group_names'
    
  2. ansible-playbook 執行腳本 shell2.yml。
    [deyu1@kvm19 ansible]$ ansible-playbook shell2.yml 
    
    PLAY [all] *********************************************************************
    
    TASK [Gathering Facts] *********************************************************
    ok: [kvm14]
    ok: [kvm15]
    ok: [kvm11]
    ok: [kvm12]
    ok: [kvm13]
    
    TASK [shell] *******************************************************************
    skipping: [kvm12]
    skipping: [kvm15]
    skipping: [kvm13]
    skipping: [kvm14]
    changed: [kvm11]
    
    TASK [shell] *******************************************************************
    skipping: [kvm11]
    skipping: [kvm15]
    skipping: [kvm13]
    skipping: [kvm14]
    changed: [kvm12]
    
    TASK [shell] *******************************************************************
    skipping: [kvm11]
    skipping: [kvm12]
    skipping: [kvm15]
    changed: [kvm13]
    changed: [kvm14]
    
    PLAY RECAP *********************************************************************
    kvm11 : ok=2 changed=1  unreachable=0  failed=0  skipped=0  rescued=0  ignored=0
    kvm12 : ok=2 changed=1  unreachable=0  failed=0  skipped=0  rescued=0  ignored=0
    kvm13 : ok=2 changed=1  unreachable=0  failed=0  skipped=0  rescued=0  ignored=0
    kvm14 : ok=2 changed=1  unreachable=0  failed=0  skipped=0  rescued=0  ignored=0
    kvm15 : ok=1 changed=0  unreachable=0  failed=0  skipped=0  rescued=0  ignored=0
    
  3. ansible 使用 shell 模組查看主機 dev, test, prod 等主機的 /etc/issue 檔案內容,符合要求。
    [deyu1@kvm19 ansible]$ ansible all -m shell -a "cat /etc/issue"
    kvm15 | CHANGED | rc=0 >>
    \S
    Kernel \r on an \m
    kvm12 | CHANGED | rc=0 >>
    Test kvm12
    kvm14 | CHANGED | rc=0 >>
    Production kvm14
    kvm13 | CHANGED | rc=0 >>
    Production kvm13
    kvm11 | CHANGED | rc=0 >>
    Development kvm11