一.循环
循环迭代任务
1.简单循环
loop:
- value1 ##赋值列表
- value2
- ...
{
{item}} ##迭代变量名称
实例:
---
- name: create file
hosts: 172.25.0.254
tasks:
- name: file module
file:
name: /mnt/{ {item}}
state: present
loop:
- westos_file1
- westos_file2
2.循环散列或字典列表
---
- name: create file
hosts: 172.25.0.254
tasks:
- name: file module
service:
name: "{ { item.name}}"
state: "{ { item.state }}"
loop:
- name: httpd
state: started
- name: vsftpd
state: stopped
练习:
http://172.25.254.250/RHCE_EXAM/files/hwreport.empty
创建一个名为/home/devops/.ansible/hwreport.yaml 的playbook 它将在所在所有受管节点上含有以下信息的输出文件 /mnt/hwreport.txt 清单主机名称
以MB表示总内存大小
BIOS 版本
磁盘设备 vda 的大小
磁盘设备vdb的大小
输出文件中的每一行含有一个 key=value 对
将它保存到/mnt/hwreport.txt
使用正确的值改为 /mnt/hwreport.txt
如果硬件不存在,相关的值设为NONE
[devops@ansible .ansible]$ cat hwreport.yaml
- name: hwreport
hosts: westos
tasks:
- name: download
get_url:
url: http://172.25.254.250/RHCE_EXAM/files/hwreport.empty
dest: /mnt/hwreport.txt
force: yes
- name: check device
lineinfile:
path: /mnt/hwreport.txt
regexp: "{
{item.start}}"
line: "{
{item.start}}={
{item.reline}}"
loop:
- name: HOST
reline: "HOST={
{ansible_facts['fqdn']}}"
- name: MEMERY
reline: "{
{ansible_facts['memtotal_mb']}}"
- name: BIOS
reline: "{
{ansible_facts['bios_version']}}"
- name: DISK_SIZE_VDA
reline: "{
{ansible_facts['devices']['vda']['size'] | default ('NONE')}}"
- name: DISK_SIZE_VDB
reline: "{
{ansible_facts['devices']['vdb']['size'] | default ('NONE')}}"
[devops@ansible .ansible]$ ansible-playbook hwreport.yaml
在受控主机中查看:
[root@node1 mnt]# cat hwreport