ansible--循環(huán)

使用with_items

loops.yml

---
- hosts: all
  tasks: 
    - name: loop
      debug: msg="{{item}}"
      with_items:
        - one
        - two
        - three
        - four
  • with_items是ansible中的一個(gè)模塊

應(yīng)用

使用循環(huán)安裝多個(gè)軟件

---
- hosts: all
  tasks: 
    - name: loop
      yum: name="{{item}}" state="present"
      with_items:
        - nginx
        - zabbix
        - php
        - mysql

使用字典循環(huán)

---
- hosts: all
  tasks:
     - name: loop dicts
       debug: msg="key--->{{item.key}},value--->{{item.value}}"
       with_items:
       - {key: "one", value: "va1"}
       - {value: "two", value: "va2"}

使用嵌套循環(huán)

---
- hosts: all
  tasks:
     - name: loop nested
       debug: msg="key--->{{item[0]}},value--->{{item[1]}}"
       with_nested:
       - ['A', 'B']
       - ['a', 'b', 'c']

使用散列循環(huán)

---
- hosts: all
  gather_facts: no
  vars:
    user:
      shan:
        name: shan
        shell: bash
      ceshi:
        name: ceshi
        shell: zsh
  tasks:
    - name: debug loops
      debug: msg="{{item.key}}"
      with_dict: "{{ user }}"

使用文件循環(huán)

---
- hosts: all
  tasks: 
    - name: debug loops
      debug: msg="{{item}}"
      with_fileglob:
        - ./*.yml

條件判斷循環(huán)

---
- hosts: all
  tasks:
    - name: debug loops
      shell: cat /root/ansible
      register: hosts
      until: hosts.stdout.startswith("Master")
      retries: 5
      delay: 5
  • until: 直到整個(gè)文件以Master開(kāi)始為結(jié)束
  • retries: 5次
  • delay: 延遲五秒

使用jinjia語(yǔ)法的for循環(huán)

---
- hosts: all
  gather_facts: no
  tasks:
    - name: debug loops
      shell: "{{item}}"
      with_items:
        - hostname
        - uname
      register: ret
    - name: display loops
      debug: msg="{% for i in ret.results %}{{ i.stdout }} {% endfor %}"

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容