比如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
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
比如拷贝多个文件到受控主机上时,可以使用
[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
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"
a和b分别与1、2、3连接组合
[student@ansible ansible]$ vim f.yml
---
- name: test
hosts: node1
tasks:
- name: debug