Ansible流程控制
playbook条件语句
不管是shell还是各大编程语言中,流程控制,条件判断这些都是必不可少的,在我们使用Ansible的过程中,条件判断的使用频率极其高。
例如: 1.我们使用不同的系统的时候,可以通过判断系统来对软件包进行安装。
2.在nfs和rsync安装过程中,客户端服务器不需要推送配置文件,之前我们都是写多个play,会影响效率。
3.我们在源码安装nginx的时候,执行第二遍就无法执行了,此时我们就可以进行判断是否安装过。
官方写法
- hosts: web_group
tasks:
- name: remove wget
yum:
name: wget
state: present
#when: ansible_hostname == 'web01'
when: ansible_facts['hostname'] == 'web01'
判断分组
tasks:
- name: "shut down CentOS 6 and Debian 7 systems"
command: /sbin/shutdown -t now
when: (ansible_distribution == "CentOS" and ansible_distribution_major_version =="6") or
(ansible_distribution == "Debian" and ansible_distribution_major_version =="7")
# 多条件想组合用()括起来
判断多条件用列表
tasks:
- name: "shut down CentOS 6 systems"
command: /sbin/shutdown -t now
when:
- ansible_distribution == "CentOS"
- ansible_distribution_major_version == "6"
# 也可以用列表
判断条件运算
ansible_python['version']['major']|int >=1
tasks:
- shell: echo "only on Red Hat 6, derivatives, and later"
when: ansible_facts['os_family'] == "RedHat" and ansible_facts['lsb'] ['major_release']|int >= 6
模糊匹配
- hosts: all
tasks:
- name: Install Nginx
yum:
name: nginx
state: present
when: ansible_hostname is match 'web*'
条件语句判断实战:rsync
# 1.发送公钥
vim ssh_key.sh
#!/bin/bash
. /etc/init.d/functions
ip='5 6 7 8 9 31 41 51 61'
passwd=1
for n in $ip;do
ping -c 1 172.16.1.$n &>/dev/null
if [ $? -eq 0 ];then
sshpass -p $passwd ssh-copy-id -i ~/.ssh/id_rsa.pub 172.16.1.$n &>/dev/null
if [ $? -eq 0 ];then
action "172.16.1.$n ssh-key" /bin/true
else
action "172.16.1.$n ssh-key" /bin/false
fi
fi
done
# 2.先决条件
vim rsyncd.conf
uid = www
gid = www
port = 873
fake super = yes
use chroot = no
max connections = 200
timeout