ansible--循环
标准循环with_items:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# vim c1.yml
#练习循环with_items
---
- name: create file
hosts: web
gather_facts: false
tasks:
- name: running
file: path=/tmp/{{ item }} state=touch mode=0644 owner=wang group=wang
with_items:
- test
- lianxi
- hello
# ansible-playbook c1.yml
使用字典的形式:
1
2
3
4
5
6
7
8
9
10
11
12
#练习循环with_items,删除c1创建的文件
---
- name: create file
hosts: web
gather_facts: false
tasks:
- name: running
file: path=/tmp/{{ item.key }} state=absent
with_items:
- {key: test}
- {key: lianxi}
- {key: hello}
嵌套循环with_nested:
1
2
3
4
5
6
7
8
9
10
#练习使用嵌套循环,例子是拷贝的,with_nested.
---
- name: test
hosts: web
tasks:
- name: create user which are used in mysql
mysql_user: name={{ item }} priv={{ item }}
with_nested:
- [ 'wang1', 'wang2' ]
- [ 'clientdb', 'employed', 'providerdb' ]
在这个嵌套循环的例子中,我们创建了两个mysql用户,给每一个用户赋予三种权限。
对文件列表使用循环with_fileglob:
with_fileglob可以以非递归的方式来模式匹配单个目录中的文件。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#使用with_fileglob,把circle中的文件拷贝到客户端的/tmp/circle目录中
---
- name: test
hosts: web
gather_facts: false
tasks:
- name: create directory
file: path=/tmp/circle state=directory owner=wang group=wang
tasks:
- name: cp file
copy: src={{ item }} dest=/tmp/circle/
with_fileglob:
- /root/circle/*
执行:
1
# ansible-playbook c4.yml
在客户端查看一下结果:
1
2
3
4
5
6
# ls
circle
# cd circle/
# ls
c1.ymlc2.ymlc3.ymlc4.yml
#
对哈希表使用循环:
假如你有以下变量:---users:alice: name: Alice Appleworth telephone: 123-456-7890bob: name: Bob Bananarama telephone: 987-654-3210你想打印出每个用户的名称和电话号码.你可以使用 with_dict 来循环哈希表中的元素:tasks:- name: Print phone records debug: msg="User {{ item.key }} is {{ item.value.name }} ({{ item.value.telephone }})" with_dict: "{{users}}"
页:
[1]