ansible☞playbook-循环

阅读量: zyh 2020-05-04 11:35:44
Categories: > Tags:

常见的循环

---
- hosts: localhost
  remote_user: zyh
  gather_facts: no
  tasks:
    - name: show debug info
      debug:
        msg: "{{ item }}"
      with_items:
        - [ a,b ]
        - [ A,B, [ D,E,F ]]
  • with_list 输出最表层元素,在简例中,会输出 [ a,b ] 和 [ A,B, [ D,E,F ] ]

  • with_item 递归输出所有层元素

  • with_together 合并两个列表,元素按照对应下标结合,如果某一方列表元素缺失,则用null代替

  • with_indexed_items 最表层所有列表合并为一个新列表并循环。item由{ list.index: list.value } 构成。在简例中,新列表是[ a,b,A,B, [ D,E,F ]]

msg: “Index:{{ item.0 }}, Value:{{ item.1 }}”


```bash
ok: [localhost] => (item=[0, u'a']) => {
    "msg": "Index:0, Vaule:a"
}
ok: [localhost] => (item=[1, u'b']) => {
    "msg": "Index:1, Vaule:b"
}
ok: [localhost] => (item=[2, u'A']) => {
    "msg": "Index:2, Vaule:A"
}
ok: [localhost] => (item=[3, u'B']) => {
    "msg": "Index:3, Vaule:B"
}
ok: [localhost] => (item=[4, [u'D', u'E', u'F']]) => {
    "msg": "Index:4, Vaule:[u'D', u'E', u'F']"
}
  • with_random_choice 随机输出一个最表层列表元素,简例中输出 [a,b] 或者 [ A,B, [ D,E,F ]]

dict 字典循环

---
- hosts: localhost
  remote_user: zyh
  gather_facts: no
  tasks:
    - name: show debug info
      debug:
        msg: "Name:{{ item.key }}, gender:{{ item.value }}"
      with_dict:
        Zhangsan: male
        Lisi: female

输出所有字典

sequence 序列循环

---
- hosts: localhost
  remote_user: zyh
  gather_facts: no
  tasks:
    - name: show sequence info
      debug:
        msg: "{{ item }}"
      with_sequence:
        start=1
        end=5
        stride=2
        format="I'm %0.4f"
  • with_sequence 获取奇偶数,start和end是起止点,stride 是步长(步长可以为负值),format是格式化

nested 嵌套循环

---
- hosts: localhost
  remote_user: zyh
  gather_facts: no
  tasks:
    - name: show nested info
      debug:
        msg: "mkdir /mnt/{{ item.0 }}/{{ item.1 }}"
      with_nested:
        - [ a,b ]
        - [ A,B,C ]

两个列表做笛卡尔积, 例如构建环境目录

subelements 子元素循环

---
- hosts: localhost
  gather_facts: no
  connection: local
  vars:
          users:
                  - name: Bob
                    gender: male
                    age: 18
                    content:
                            - eating
                            - sleeping
                            - play ogre
                  - name: Maris
                    gender: female
                    age: 20
                    content:
                            - eating
                            - sleeping
                            - shopping

  tasks:
          - name: test vars 2
            debug:
                    msg: "{{ item.0.name }} - {{ item.0.gender }} - {{ item.1 }}"
            with_subelements:
              - "{{ users }}"
              - content

分解 , 选中列表内某一个列表元素 content, 与作为一个临时整体的剩余元素构建笛卡尔积,形成 item

file 文件循环

with_file:
  /mnt/a.ini
  /mnt/b.ini

始终循环获取ansible主机里文件的内容。(与目标主机无关)

fileglob 寻找通配符匹配的文件

with_fileglob:
  - /home/zyh/test/dirA/*
  - /home/zyh/test/dirB/[0-9].ini

始终循环获取ansible主机指定目录中匹配的文件名和路径。(与目标主机无关)