ansible_playbook語法中的循環語句歸納


ansible_playbook語法中的循環語句歸納

種類一、標准循環
添加多個用戶

- name: add several users
  user: name={{ item }} state=present groups=wheel
  with_items:
     - test1
     - test2
添加多個用戶,並將用戶加入不同的組內
- name: add several users
  user: name={{ item.name }} state=present groups={{ item.groups }}
  with_items:
    - { name: 'test1', groups: 'wheel' }
    - { name: 'test2', groups: 'root' }

種類二、錨點嵌套循環

嵌套循環主要實現一對多,多對多的合並。

- hosts: abc
  gather_facts: False
  tasks:
  - name: debug loops
    debug: msg="name is {{ item[0] }} vaule is {{ item[1] }} num is {{ item[2] }} num is {{ item[3] }}"
    with_nested:
      - ['悟空','豬八戒','唐僧']
      - ['a','b','c']
      - ['1','2','3']
      - ['w1','w2','w3']
  tags:
    loops

可以將代碼復制至xxx.yaml 文件中

通過:ansible-playbook loops.yaml --syntax-check 檢查語法

通過:ansible-playbook loops.yaml --list-tasks 查看標簽

通過:ansible-playbook loops.yaml --tags=loops 來執行對應標簽的任務,這里定義了loops任務,仔細觀察執行后的結果就會發現嵌套循環的規律也就很容易理解嵌套循環了

 種類三、錨點遍歷字典
輸出用戶的姓名和電話

- hosts: abc
  gather_facts: False
  tasks:
    - name: Print phone records
  #item.key 相當於 aliceitem.value.name 相當於 Alice Appleworthitem.value.telephone 相當於123-456-789
#此方法為Python字典方式key:value 方式調用
debug
: msg="User {{ item.key }} is {{ item.value.name }} ({{ item.value.telephone }})" with_dict: {'alice':{'name':'Alice Appleworth', 'telephone':'123-456-789'},'bob':{'name':'Bob Bananarama', 'telephone':'987-654-3210'} } tags: print #"msg": "User alice is Alice Appleworth (123-456-789)"

 

 

 種類四、錨點並行遍歷列表

  tasks:
    - debug: "msg={{ item.0 }} and {{ item.1 }}"
      with_together:
      - [ 'a', 'b', 'c', 'd','e' ]
      - [ 1, 2, 3, 4 ]
  tags:
    pwd

 如果列表數目不匹配則用Null 補全

種類五、錨點遍歷列表和索引

- hosts: abc
  gather_facts: False
  tasks:
    - name: indexed loop demo
      debug: "msg='at array position {{ item.0 }} there is a value {{ item.1 }}'"
      with_indexed_items: [a,b,c,d,e,f,g]
  tags:
    indexed

輸出結果:

[root@node2 ansible-playbooks]# ansible-playbook indexed.yaml --tags=indexed

PLAY [abc] **********************************************************************************************************************************************************************************************************************************

TASK [indexed loop demo] ********************************************************************************************************************************************************************************************************************
ok: [127.0.0.1] => (item=(0, u'a')) => {
    "changed": false, 
    "item": [
        0, 
        "a"
    ], 
    "msg": "at array position 0 there is a value a"
}
ok: [127.0.0.1] => (item=(1, u'b')) => {
    "changed": false, 
    "item": [
        1, 
        "b"
    ], 
    "msg": "at array position 1 there is a value b"
}
ok: [127.0.0.1] => (item=(2, u'c')) => {
    "changed": false, 
    "item": [
        2, 
        "c"
    ], 
    "msg": "at array position 2 there is a value c"
}
ok: [127.0.0.1] => (item=(3, u'd')) => {
    "changed": false, 
    "item": [
        3, 
        "d"
    ], 
    "msg": "at array position 3 there is a value d"
}
ok: [127.0.0.1] => (item=(4, u'e')) => {
    "changed": false, 
    "item": [
        4, 
        "e"
    ], 
    "msg": "at array position 4 there is a value e"
}
ok: [127.0.0.1] => (item=(5, u'f')) => {
    "changed": false, 
    "item": [
        5, 
        "f"
    ], 
    "msg": "at array position 5 there is a value f"
}
ok: [127.0.0.1] => (item=(6, u'g')) => {
    "changed": false, 
    "item": [
        6, 
        "g"
    ], 
    "msg": "at array position 6 there is a value g"
}

PLAY RECAP **********************************************************************************************************************************************************************************************************************************
127.0.0.1                  : ok=1    changed=0    unreachable=0    failed=0  
輸出結果:ansible-playbook indexed.yaml --tags=indexed

item.0 為索引,item.1為值

種類六、錨點比哪里文件列表內容

- hosts: abc
  gather_facts: False
  tasks:
    - debug:
        msg: "{{ item }}"
      with_file:
        - /home/loops.log
        - /home/newloops.log
      tags:
        pwd
[root@node2 ansible-playbooks]# ansible-playbook test6.yaml --tags=pwd

PLAY [abc] ***********************************************************************************************

TASK [debug] *********************************************************************************************
ok: [127.0.0.1] => (item=hello) => {
    "changed": false, 
    "item": "hello", 
    "msg": "hello"
}
ok: [127.0.0.1] => (item=world) => {
    "changed": false, 
    "item": "world", 
    "msg": "world"
}

PLAY RECAP ***********************************************************************************************
127.0.0.1                  : ok=1    changed=0    unreachable=0    failed=0 
輸出結果:ansible-playbook test6.yaml --tags=pwd

種類七、錨點遍歷目錄文件

with_fileglob 匹配單個目錄中的所有文件,非遞歸模式匹配

- hosts: abc
  gather_facts: False
  tasks:
    - file: dest=/home/loops.log state=directory
    - copy: src={{ item }} dest=/tmp/ owner=root mode=600
      with_fileglob:
        - /home/*.log
      tags:
        pwd
    #- debug: 
    #    msg: "{{ item }}"
    #  with_fileglob:
    #    - /home/*.log
    #    #- /home/newloops.log
    #  tags:
    #    pwd

 

[root@node2 ansible-playbooks]# ansible-playbook test7.yaml --list-tasks

playbook: test7.yaml

  play #1 (abc): abc    TAGS: []
    tasks:
      file      TAGS: []
      copy      TAGS: [pwd]
[root@node2 ansible-playbooks]# ansible-playbook test7.yaml --tags=pwd

PLAY [abc] ***********************************************************************************************

TASK [copy] **********************************************************************************************
changed: [127.0.0.1] => (item=/home/loops.log)
changed: [127.0.0.1] => (item=/home/newloops.log)

PLAY RECAP ***********************************************************************************************
127.0.0.1                  : ok=1    changed=1    unreachable=0    failed=0 
輸出結果:ansible-playbook test7.yaml --list-tasks
[root@node2 ansible-playbooks]# ll /tmp/loops.log 
-rw------- 1 root root 6 Mar 26 12:24 /tmp/loops.log
[root@node2 ansible-playbooks]# ll /tmp/newloops.log 
-rw------- 1 root root 6 Mar 26 12:24 /tmp/newloops.log
當在role中使用with_fileglob的相對路徑時,Ansible解析相對於roles/<rolename>/files目錄的路徑

 種類八、錨點遍歷ini 文件

lookup.ini
[section1]
value1=section1/value1
value2=section1/value2

[section2]
value1=section2/value1
value2=section2/value2

- debug: msg="{{ item }}"
  with_ini: value[1-2] section=section1 file=lookup.ini re=true

獲取section1 里的value1和value2的值

 種類九、錨點重試循環 until

- hosts: abc
  gather_facts: False

  tasks:
    - action: shell /usr/bin/foo
      register: result
      until: result.stdout.find("all systems go") != -1
      retries: 5
      delay:  10
  tags:
    until

"重試次數retries" 的默認值為3,"delay"為5。

錨點查找第一個匹配文件

tasks:
  - debug: "msg={{ item }}"
    with_first_found:
     - "/tmp/a"
     - "/tmp/b"
     - "/tmp/default.conf"

依次尋找列表中的文件,找到就返回。如果列表中的文件都找不到,任務會報錯。

種類十、錨點隨機選擇with_random_choice

隨機選擇列表中的一個值

- hosts: abc
  gather_facts: False
  tasks:
    - debug: msg={{ item }}
      with_random_choice:
        - "go through the door"
        - "drink from the goblet"
        - "press the red button"
        - "do nothing"
  tags:
    random

檢查語法

[root@node2 ansible-playbooks]# ansible-playbook with_random_choice.yaml --syntax-check

playbook: with_random_choice.yaml

查看任務標簽

[root@node2 ansible-playbooks]# ansible-playbook with_random_choice.yaml --list-tasks

playbook: with_random_choice.yaml

  play #1 (abc): abc    TAGS: [random]
    tasks:
      debug     TAGS: [random]
[root@node2 ansible-playbooks]# 

執行任務:

循環程序的結果:

- hosts: abc
  gather_facts: False
  tasks:
    - debug: "msg={{ item }}"
      with_lines: ps aux
  tags:
    with-lines

種類十一、錨點循環子元素

定義好變量

#varfile
---
users:
  - name: alice
    authorized:
      - /tmp/alice/onekey.pub
      - /tmp/alice/twokey.pub
    mysql:
        password: mysql-password
        hosts:
          - "%"
          - "127.0.0.1"
          - "::1"
          - "localhost"
        privs:
          - "*.*:SELECT"
          - "DB1.*:ALL"
  - name: bob
    authorized:
      - /tmp/bob/id_rsa.pub
    mysql:
        password: other-mysql-password
        hosts:
          - "db1"
        privs:
          - "*.*:SELECT"
          - "DB2.*:ALL"
---
- hosts: web
  vars_files: varfile
  tasks:

  - user: name={{ item.name }} state=present generate_ssh_key=yes
    with_items: "{{ users }}"

  - authorized_key: "user={{ item.0.name }} key='{{ lookup('file', item.1) }}'"
    with_subelements:
      - "{{ users }}"
      - authorized

  - name: Setup MySQL users
    mysql_user: name={{ item.0.name }} password={{ item.0.mysql.password }} host={{ item.1 }} priv={{ item.0.mysql.privs | join('/') }}
    with_subelements:
      - "{{ users }}"
      - mysql.hosts

{{ lookup('file', item.1) }} 是查看item.1文件的內容

with_subelements 遍歷哈希列表,然后遍歷列表中的給定(嵌套)的鍵。

種類十二、錨點在序列中循環with_sequence
with_sequence以遞增的數字順序生成項序列。 您可以指定開始,結束和可選步驟值。 參數應在key = value對中指定。 'format'是一個printf風格字符串。

數字值可以以十進制,十六進制(0x3f8)或八進制(0600)指定。 不支持負數。

 

---
- hosts: all

  tasks:

    # 創建組
    - group: name=evens state=present
    - group: name=odds state=present

    # 創建格式為testuser%02x 的0-32 序列的用戶
    - user: name={{ item }} state=present groups=evens
      with_sequence: start=0 end=32 format=testuser%02x

    # 創建4-16之間得偶數命名的文件
    - file: dest=/var/stuff/{{ item }} state=directory
      with_sequence: start=4 end=16 stride=2

    # 簡單實用序列的方法:創建4 個用戶組分表是組group1 group2 group3 group4
    - group: name=group{{ item }} state=present
      with_sequence: count=4

合並列表

安裝所有列表中的軟件

 

- hosts: abc
  gather_facts: False
  tasks:
    - name: flattened loop demo
      yum: name={{ item }} state=installed
      with_flattened:
         - [ 'foo-package', 'bar-package' ]
         - [ ['one-package', 'two-package' ]]
         - [ ['red-package'], ['blue-package']]
  tags:
    yum

 

注冊變量使用循環

- hosts: abc
  gather_facts: False
  tasks:
    - shell: echo "{{ item }}"
      with_items:
        - one
        - two
      register: echo

    - name: Fail if return code is not 0
      fail:
        msg: "The command ({{ item.cmd }}) did not have a 0 return code"
      when: item.rc != 0
      with_items: "{{ echo.results }}"
  tags:
    with

循環主機清單

- hosts: abc
  gather_facts: False
  tasks:
    - debug: msg={{ item }}
      with_items: "{{ groups['all'] }}"
  tags:
    all

輸出所有執行的主機

- hosts: abc
  gather_facts: False
  tasks:
    - debug: msg={{ item }}
      with_items: abc
  tags:
    all

輸出所有主機清單里的主機

- hosts: abc
  gather_facts: False
  tasks:
    - debug: msg={{ item }}
      with_inventory_hostnames: all
  tags:
    all

輸出主機清單中不在www中的所有主機

- hosts: abc
  gather_facts: False
  tasks:
    - debug: msg={{ item }}
      with_inventory_hostnames: all:!www
  tags:
    all
主機清單內容:
[root@node2 ansible-playbooks]# cat /etc/ansible/hosts
[www]
192.168.92.131
192.168.92.132:30022 testvar="80.183"


[abc]
127.0.0.1 http_port=192.68.92.139:80 access_num=100 server_name="www.xxxx.com"

改變循環的變量項

# main.yml
- include: inner.yml
  with_items:
    - 1
    - 2
    - 3
  loop_control:
    loop_var: outer_item
# inner.yml
- debug: msg="outer item={{ outer_item }} inner item={{ item }}"
  with_items:
    - a
    - b
    - c

 

 

 

https://www.cnblogs.com/hwlong/p/9301008.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM