Ansible Loop循环控制
Ansible 2.5之前主要使用with_ <lookup>关键字来创建循环,循环关键字基本上类似于with_list,with_items。
Ansible 2.5开始官网推荐使用Loop来进行循环控制。
示例1 Loop数组循环:
--- - name: create user hosts: dev tasks: - name: create user user: name: "{{ item }}" state: present loop: - user01 - user02 - user03 - name: set password shell: echo '12345678' | passwd --stdin "{{ item }}" loop: - user01 - user02 - user03
示例2 vars传递数组给Loop循环
--- - name: create user hosts: dev vars: users: - user01 - user02 - user03 tasks: - name: create user user: name: "{{ item }}" state: present loop: "{{ users }}" - name: set password shell: echo '12345678' | passwd --stdin "{{ item }}" loop: "{{ users }}"
示例3 Loop字典循环:
--- - name: create user hosts: dev tasks: - name: create user and group user: name: "{{ item.name }}" group: "{{ item.groups }}" loop: - {name: 'user01', groups: 'wheel'} - {name: 'user02', groups: 'root'}
示例4 vars传递字典给Loop循环
--- - name: loop test hosts: dev vars: users: - user: 'user01' group: 'wheel' - user: 'user02' group: 'root' tasks: - name: debug user: name: "{{ item.user }}" group: "{{ item.group }}" loop: "{{ users }}"
示例5 vars传递字典给Loop循环,并使用dict filter
--- - name: loop test hosts: dev vars: users: user: 'user01' groups: 'root' tasks: - name: debug debug: msg: "{{ item.key }} {{ item.value }}" loop: "{{ users|dict2items }}" # dict2items 是 jinjia2 filter
官网参考文档:
loops: https://docs.ansible.com/ansible/latest/user_guide/playbooks_loops.html
filters: https://docs.ansible.com/ansible/latest/user_guide/playbooks_filters.html