思考以下代码,使用两次service模块来保证两个服务处于运行状态
---
- name: loop
hosts: 172.16.10.9
tasks:
- name: httpd is running
service:
name: httpd
state: started
- name: firewalld is running
service:
name: firewalld
state: started
...
这两个任务可以重新编写一个循环,只需要一个任务就可以确保两个服务都在运行
---
- name: loop
hosts: all
tasks:
- name: loop running
service:
name: "{{ item }}"
state: started
loop:
- httpd
- firewalld
...
还可以对代码进行优化
使用vars给loop提供一个列表
---
- name: loop
hosts: all
vars:
mail_services:
- httpd
- firewalld
tasks:
- name: loop running
service:
name: "{{ item }}"
state: stopped
loop: "{{ mail_services }}"
...
loop列表并不仅是简单列表,以下内容中,列表中每个项实际是一个散列或是字典,每个散列有两个键,即name和groups,当前item循环变量中每个键都可以通过item.name和item.groups进行检索
---
- name: user
hosts: all
tasks:
- name: create user
user:
name: chaijin
state: present
groups: root
...
---
- name: user
hosts: all
tasks:
- name: create user
user:
name: "{{ item.name }}"
state: present
groups: "{{ item.groups }}"
loop:
- name: jane
groups: root
- name: xiaohong
groups: root
...
~
Ansible可以使用conditionals在符合特定的条件时执行任务或者play
使用场景
when:适用于有条件的运行任务,他要测试的条件为值,如果条件满足,则执行该任务,若不满足,跳过该任务
---
- name: true and false
hosts: 172.16.10.9
vars:
run_my_task: True
tasks:
- name: httpd
yum:
name: httpd
when: run_my_task
...
~
操作 | 示例 |
---|---|
等于(字符串) | ansible——machine==“x86_64” |
等于(数字) | max_memory==512 |
变量存在 | min_memory is defined |
变量不存在 | min_memory is not defined |