1. 程式人生 > >ansible_playbook語法中的循環語句歸納

ansible_playbook語法中的循環語句歸納

分表 獲取 install tle playbook 查找 報錯 ride eth

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

- name: add several users
  user: name={{ item }} state=present groups=wheel
  with_items:
     - testuser1
     - testuser2

添加多個用戶,並將用戶加入不同的組內。

- name: add several users
  user: name={{ item.name }} state=present groups={{ item.groups }}
  with_items:
    - { name: ‘testuser1‘, groups: ‘wheel‘ }
    - { name: ‘testuser2‘, groups: ‘root‘ }

種類二、錨點嵌套循環
分別給用戶授予3個數據庫的所有權限

- name: give users access to multiple databases
  mysql_user: name={{ item[0] }} priv={{ item[1] }}.*:ALL append_privs=yes password=foo
  with_nested:
    - [ ‘alice‘, ‘bob‘ ]
    - [ ‘clientdb‘, ‘employeedb‘, ‘providerdb‘ ]

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

tasks:
  - name: Print phone records
    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‘} }

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

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

如果列表數目不匹配,用None補全

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

 - name: indexed loop demo
    debug: "msg=‘at array position {{ item.0 }} there is a value {{ item.1 }}‘"
    with_indexed_items: [1,2,3,4]

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

種類六、錨點遍歷文件列表的內容

---
- hosts: all
  tasks:
       - debug: "msg={{ item }}"
      with_file:
        - first_example_file
        - second_example_file

種類七、錨點遍歷目錄文件
with_fileglob匹配單個目錄中的所有文件,非遞歸匹配模式。

---
- hosts: all
  tasks:
    - file: dest=/etc/fooapp state=directory
    - copy: src={{ item }} dest=/etc/fooapp/ owner=root mode=600
      with_fileglob:
        - /playbooks/files/fooapp/*

當在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

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

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

錨點查找第一個匹配文件

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

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

種類十、錨點隨機選擇with_random_choice
隨機選擇列表中得一個值

- debug: msg={{ item }}
  with_random_choice:
     - "go through the door"
     - "drink from the goblet"
     - "press the red button"
     - "do nothing"

循環程序的結果
tasks:

  • debug: "msg={{ item }}"
    with_lines: ps aux
    種類十一、錨點循環子元素
    定義好變量
#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

種類十三、錨點隨機選擇with_random_choice
隨機選擇列表中得一個值

- debug: msg={{ item }}
  with_random_choice:
     - "go through the door"
     - "drink from the goblet"
     - "press the red button"
     - "do nothing"

合並列表

安裝所有列表中的軟件

- name: flattened loop demo
  yum: name={{ item }} state=installed
  with_flattened:
     - [ ‘foo-package‘, ‘bar-package‘ ]
     - [ [‘one-package‘, ‘two-package‘ ]]
     - [ [‘red-package‘], [‘blue-package‘]]

註冊變量使用循環

- 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 }}"

循環主機清單

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

- debug: msg={{ item }}
  with_items: "{{ groups[‘all‘] }}"

輸出所有執行的主機

- debug: msg={{ item }}
  with_items: play_hosts

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

  • debug: msg={{ item }}
    with_inventory_hostnames: all

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

  • debug: msg={{ item }}
    with_inventory_hostnames: all:!www
    改變循環的變量項
# 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


作者:Jeson老師
鏈接:https://www.imooc.com/article/22753
來源:慕課網

ansible_playbook語法中的循環語句歸納