playbook 循环

发布时间: 更新时间: 总字数:925 阅读时间:2m 作者: 分享 复制网址

ansible playbook 循环

说明

  • ansible 2.6 版本开始,官方开始推荐使用 loop/lookup 关键字代替 with_X 风格的关键字
    • ansible-doc -t lookup -l
  • lookup('插件名', 被处理数据或参数)

with_items

---
- hosts: testservers
  remote_user: root
  gather_facts: no
  tasks:
  - debug:
      msg: "{{item}}"
    with_items:
    - 1
    - 2
    - 3

  - debug:
      msg: "{{item}}"
    with_items: [ 1, 2, 3 ]

  - debug:
      msg: "{{item}}"
    with_items:  # with_items 将嵌套在大列表中的每个小列表都 `展开`,与 with_flattened 效果相同
    - [ 1, 2, 3 ]
    - [ a, b ]

  - debug:
      msg: "{{item}}"
    with_list:  # with_list 不展开嵌套的小列表,使用 loop: 替代
    - [ 1, 2, 3 ]
    - [ a, b ]

  - debug:
      msg: "{{item}}"
    with_together:  # with_together 将两个列表中的元素 `对齐合并` [1,a], [2, b], [3, null]
    - [ 1, 2, 3 ]
    - [ a, b ]

with_cartesian

  • 将每个小列表中的元素按照 笛卡尔的方式 组合后,循环的处理每个组合
  - file:
      state: directory
      path: "/tmp/{{item.0}}/{{item.1}}"
    with_cartesian:
    - [ a, b, c ]
    - [ test1, test2 ]

效果同

mkdir -p /testdir/{a,b,c}/{test1,test2}

with_nested

功能同 with_cartesian

indexed_items/with_indexed_items

  • with_indexed_items 在循环处理列表时为列表中的每一项添加 数字索引,从0开始
    • with_indexed_items 会将嵌套的两层列表 展开,并按照顺序为每一项编号
  - debug:
      msg: "idnex is :{{item.0}},value is {{item.1}}"
    with_indexed_items:
    - test1
    - [test2, test3]
    # 推荐写法
    # loop: "{{ lookup('indexed_items',['a','b','c']) }}"
    # loop_control:  # 控制循环的行为
    #   pause: test1
    # loop_control:
    #   label: "{{item.key}}"
  • 输出
ok: [h-1] => (item=[0, 'test1']) => {
    "msg": "idnex is :0,value is test1"
}
ok: [h-1] => (item=[1, 'test2']) => {
    "msg": "idnex is :1,value is test2"
}
ok: [h-1] => (item=[2, 'test3']) => {
    "msg": "idnex is :2,value is test3"
}

range/with_sequence

  • with_sequence 按照顺序生成数字序列
    • “start=1 end=5 stride=1”,从1开始,到5结束(包括),步长为1,即从1到5每次增加1
    • format 参数支持格式化输出,如 format="number is %0.2f"
  tasks:
  - debug:
      msg: "{{item}}"
    with_sequence: start=1 end=5 stride=1
    # with_sequence:  # 以下两个和上面通效果
    #   start=1
    #   end=5
    #   stride=1
    # with_sequence: count=5
    # loop: "{{ range(2, 7, 2) | list }}"

random/with_random_choice

with_random_choice 从列表的多个值中随机返回一个值

  - debug:
      msg: "{{item}}"
      # msg: "{{ testlist | random }}"
    with_random_choice:
    - 1
    - 2
    - 3
    - 4
    - 5

dict/with_dict

with_dict 操作字典

  • 键值对中: 被放入 key 关键字中, 被放入 value 关键字中
  • value 支持嵌套,通过 item.<value>.<key> 获取值
---
- hosts: testservers
  remote_user: root
  gather_facts: no
  vars:
    users:
      alice: female
      bob: male
  tasks:
  - debug:
      msg: "User name: {{item.key}}, User grnder: {{item.value}}"
    with_dict: "{{ users }}"
    # loop: "{{ lookup('dict',users) }}"
    # loop: "{{ users | dict2items }}"
  - debug:
      msg: "{{item.0}} -- {{item.1}}"
    loop: "{{ users | dictsort }}"

输出

ok: [h-1] => (item={'key': 'alice', 'value': 'female'}) => {
    "msg": "User name: alice, User grnder: female"
}
ok: [h-1] => (item={'key': 'bob', 'value': 'male'}) => {
    "msg": "User name: bob, User grnder: male"
}

subelements/with_subelements

with_subelements

---
- hosts: testservers
  remote_user: root
  gather_facts: no
  vars:
    users:
    - name: bob
      gender: male
      hobby:
        - Skateboard
        - VideoGame
    - name: alice
      gender: female
      hobby:
        - Music
  tasks:
  - debug:
      msg: "{{ item.0.name }} 's hobby is {{item.1}}"
    with_subelements:
    - "{{users}}"
    - hobby
  - debug:
      msg: "{{item.0.name}}'s hobby is {{item.1}}"
    loop: "{{users | subelements('hobby')}}"

输出

ok: [h-1] => (item=[{'name': 'bob', 'gender': 'male'}, 'Skateboard']) => {
    "msg": "bob 's hobby is Skateboard"
}
ok: [h-1] => (item=[{'name': 'bob', 'gender': 'male'}, 'VideoGame']) => {
    "msg": "bob 's hobby is VideoGame"
}
ok: [h-1] => (item=[{'name': 'alice', 'gender': 'female'}, 'Music']) => {
    "msg": "alice 's hobby is Music"
}

file/with_file

  • with_file 循环获取文件的内容,即 {{item}} 为文件的内容
  tasks:
  - debug:
      msg: "{{item}}"
      # msg: "{{ lookup('file', '/testdir/testdir/a.log','/etc/hosts') }}"
      # msg: "{{ lookup('file', '/testdir/testdir/a.log', wantlist=true) }}"
      # msg: "{{ query('file','/testdir/testfile') }}"
      # msg: "{{ q('file','/testdir/testfile') }}" # query 简写形式
      # msg: "{{ lookup('file','/testdir/testfil',errors='ignore') }}" # 忽略错误
    with_file:
    - /testdir/testdir/a.log
    - /etc/hosts

with_fileglob

  • with_fileglob 获取指定目录中匹配符合模式的文件名
  tasks:
  - debug:
      msg: "{{item}}"
    with_fileglob:
    - /testdir/*
    - /etc/test*.???

flatten/with_flattened

  vars:
    testlist:
    - a
    - [b,c]
    - d
  tasks:
  - debug:
      msg: "{{item}}"
    # with_flattened
    loop: "{{testlist | flatten}}"
    # loop: "{{testlist | flatten(levels=1)}}"
Home Archives Categories Tags Statistics
本文总阅读量 次 本站总访问量 次 本站总访客数