ansible循环和判断
文章目录
一、循环
1、with_items迭代列表
比如Linux中依次需要安装多个软件包时,我们可以使用with_items迭代功能进行实现
例如:
安装httpd、samba、samba-client软件包时
[student@ansible ansible]$ vim b.yml
- name: install packages
hosts: node1
tasks:
- name: yum_repo1
yum_repository:
file: server
name: baseos
description: rhel8
baseurl: file:///mnt/BaseOS
enabled: yes
gpgcheck: no
- name: yum_repo2
yum_repository:
file: server
name: appstream
description: appstream
baseurl: file:///mnt/AppStream
enabled: yes
gpgcheck: no
- name: mount cdrom
mount:
src: /dev/cdrom
path: /mnt
fstype: iso9660
state: mounted
- name: install pks
yum:
name: "{
{item}}"
state: present
with_items:
- httpd
- samba
- samba-client
2 、with_dict迭代字典
item.key对应着是字典的键,item.value对应着字典的值
[student@ansible ansible]$ vim c.yml
---
- name: test
hosts: node1
tasks:
- name: debug
debug:
msg: "{
{item.key}} & {
{item.value}}"
with_dict:
address: 1
netmask: 2
gateway: 3
3、with_fileglob迭代文件
比如拷贝多个文件到受控主机上时,可以使用
[student@ansible ansible]$ vim d.yml
---
- name: test
hosts: node1
tasks:
- name: cp file
copy:
src: "{
{item}}"
dest: /tmp/
with_fileglob:
- /tmp/*.sh
- /tmp/*.py
4、with_lines迭代行
With_lines可以将命令行的输出结果按行迭代
[student@ansible ansible]$ vim e.yml
---
- name: test
hosts: node1
tasks:
- name: cp file
copy:
src: "{
{item}}"
dest: /tmp/
with_lines:
- find /etc/ansible -name "*.yml"
5、with_nested嵌套迭代
a和b分别与1、2、3连接组合
[student@ansible ansible]$ vim f.yml
---
- name: test
hosts: node1
tasks:
- name: debug
debug:
msg: "{
{item[0]}} & {
{item[1]}}"
with_nested:
- [a,b]
- [1,2,3]
6、with_sequence 排序列(start是从什么开始,end结束 stride每隔多少)
[student@ansible ansible]$ vim g.yml
---
- name: test
hosts: node1
tasks:
- name: debug
debug:
msg: "{
{item}}"
with_sequence:
start=1
end=5
stride=1
7、with_random_choice 随机获得列表中的一个值
---
- name: test
hosts: node1
tasks:
- name: debug
debug:
msg: "{
{item}}"
with_random_choice:
- 1
- 2
- a
- b
- c
8、loop
现在loop已经替代了with,更多的是loop配合过滤器进行使用
过滤器:
常用字符串有关的过滤器
---
- name: test
hosts: node1