🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
当有需要重复性执行某个任务时,可以使用迭代机制,其使用格式为将需要迭代的内容定义为item,并通过with_items语句来表明迭代的元素列表即可 ~~~ --- - hosts: webserver user: admin become: yes tasks: - name: add users user: name={{ item.name }} state=present groups={{ item.groups }} with_items: - { name: 'testuser01', groups: 'wheel' } - { name: 'testuser02', groups: 'root' } ~~~ 嵌套循环 ~~~ - 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' ] ~~~ 遍历字典 ~~~ --- - hosts: webserver user: admin become: yes 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'} } ~~~ 遍历文件 ~~~ --- - hosts: all tasks: - debug: "msg={{ item }}" with_file: - first_example_file - second_example_file ~~~ 遍历目录 (文件匹配循环) ~~~ --- - hosts: all tasks: - file: dest=/etc/fooapp state=directory - copy: src={{ item }} dest=/etc/fooapp/ owner=root mode=600 with_fileglob: - /playbooks/files/fooapp/* ~~~ 重试循环until ~~~ - action: shell /usr/bin/foo register: result until: result.stdout.find("all systems go") != -1 retries: 5 重试此时 delay: 10 间隔时间 ~~~