with_items 迭代

目录

字符串

字典


当有需要重复性执行的任务时,可以使用迭代机制

对迭代项的引用,固定变量名为“item”

要在task中使用with_items给定要迭代的元素列表
 列表格式:
    字符串
    字典


字符串

[root@ansible ~]# vim item.yml
  
---
- hosts: web
  remote_user: root

  tasks:
   - name: create files
     file: name=/root/{{ item }} state=touch
     with_items:
      - ip.sh
      - var.yml
      - 111.txt

[root@ansible ~]# ansible-playbook  item.yml   

PLAY [web] *********************************************************************

TASK [Gathering Facts] *********************************************************
ok: [192.168.60.4]
ok: [192.168.60.3]

TASK [create files] ************************************************************
changed: [192.168.60.3] => (item=ip.sh)
changed: [192.168.60.4] => (item=ip.sh)
changed: [192.168.60.4] => (item=var.yml)
changed: [192.168.60.3] => (item=var.yml)
changed: [192.168.60.4] => (item=111.txt)
changed: [192.168.60.3] => (item=111.txt)

PLAY RECAP *********************************************************************
192.168.60.3               : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
192.168.60.4               : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

字典

[root@ansible ~]# vim item2.yml                 
---
#this is item dictionary!
- hosts: web
  remote_user: root

  tasks:
   - name: create group
     group: name={{item}} state=present
     with_items:
      - app
      - web
   - name: create user
     user: name={{item.name}} group={{item.group}} state=present
     with_items:
      - {name: 'app',group: 'app'}
      - {name: 'web',group: 'web'}

[root@ansible ~]# ansible-playbook  item2.yml   

PLAY [web] *********************************************************************

TASK [Gathering Facts] *********************************************************
ok: [192.168.60.4]
ok: [192.168.60.3]

TASK [create group] ************************************************************
changed: [192.168.60.4] => (item=app)
changed: [192.168.60.3] => (item=app)
changed: [192.168.60.4] => (item=web)
changed: [192.168.60.3] => (item=web)

TASK [create user] *************************************************************
changed: [192.168.60.4] => (item={u'group': u'app', u'name': u'app'})
changed: [192.168.60.3] => (item={u'group': u'app', u'name': u'app'})
changed: [192.168.60.3] => (item={u'group': u'web', u'name': u'web'})
changed: [192.168.60.4] => (item={u'group': u'web', u'name': u'web'})

PLAY RECAP *********************************************************************
192.168.60.3               : ok=3    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
192.168.60.4               : ok=3    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0 

上一篇:ansible学习03


下一篇:实施任务控制