当使用循环变量item编写:
---
- name: test
hosts: web
tasks:
- name: apache and vsftpd are running
service:
name: "{{ item }}"
state: started
loop:
- httpd
- vsftpd
...
- name: User Test
user:
name: "{{ item.name }}"
state: present
groups: "{{ item.groups }}"
loop:
- name: westos
groups: westos
- name: redhat
groups: root
##########早些版本的循环,使用with_#########
vars:
data:
- user1
- user2
- user3
tasks:
- name: "with_items"
debug:
msg: "{{ item }}"
with_items: "{{ data }}"
---
- name: loop register test
gather_facts: no
hosts: localhost
tasks:
- name: loop echo task
shell: "echo This is my item: {{ item }}"
loop:
- one
- two
register: echo_results #注册变量
- name: Show echo results variable
debug:
var: echo_results #显示变量结果
...
迭代上面 playbook 的结果(即使用上面 item 的结果)
关键字:when
条件用于仅再符合特定条件时执行任务或 play
---
- name: Boolean test
hosts: all
vars:
my_service: my_service
tasks:
- name: "{{ my_service }} is installed"
yum:
name: "{{ my_service }}"
when: my_service is defined
...
等于(字符串) A == "B"
等于(数字) A == 100
小于 <
大于 >
小于等于 <=
大于等于 >=
不等于 !=
变量存在 xxx is defined
变量不存在 xxx is not defined
布尔值 true 1、true、yes
布尔值 false 0、false、no
第一个变量的值存在,且在第二个变量的列表中 A in B
(1)测试多个条件: or:两个条件一个为真即可;and:两个条件必须都为真
(2)when 支持使用列表描述条件:
when:
- ansible_distribution_version == "8.0"
- ansible_kernel == "4.18.0-80.1.2.el8_0.x86_64"
######再如:########
when:
( ansible_distribution == "RedHat" and ansible_distribution_major_version == "8" )
or
( ansible_distribution == "CentOS" and ansible_distribution_major_version == "7" )
示例1:当循环变量挂载到根下并且大小不超过300M时,安装数据库。
---
- name: keyword
hosts: all
tasks:
- name: install db if enough space
yum:
name: mariadb-server
state: latest
loop: "{{ ansible_mounts }}" #此变量是事实,已知的
when: item.mount == "/" and item.size_available > 300000000 #挂载到根下,大小不超过300M
...
示例二:只有当vsftpd服务运行时,才能重启Apache
---
- name: Restart httpd if vsftpd is running
hosts: all
tasks:
- name: Get vsftpd status
command: /usr/bin/systemctl is-active vsftpd #判断状态
ignore_errors: yes #如果vsftpd没运行或失败,则忽略,继续执行下面动作
register: result #定义变量保存结果
- name: Restart httpd
service:
name: httpd
state: restarted
when: result.rc == 0 #退出码为0,则重启httpd
...
反向测试:当在受管主机中暂停vsftpd服务后,重新执行playbook
############基础写法################
- name: Mariadb is running
hosts: web1
vars:
mariadb_pkgs:
- mariadb-server
- python3-PyMySQL
tasks:
- name: Mariadb is installed
yum:
name: "{{ item }}"
state: present
loop: "{{ mariadb_pkgs }}"
- name: Start Mariadb
service:
name: mariadb
state: started
enabled: true
#修改 playbook,条件变为受管主机使用 rehdat 操作系统时才执行########
---
- name: Mariadb is running
hosts: web1
vars:
mariadb_pkgs:
- mariadb-server
- python3-PyMySQL
tasks:
- name: Mariadb is installed
yum:
name: "{{ item }}"
state: present
loop: "{{ mariadb_pkgs }}"
when: ansible_distribution == "RedHat" #更改条件
...
编辑完成后,先检测主机组系统:ansible web1 -m command -a ‘cat /etc/redhat-release’ -u student --become
检测完成后,再运行playbook