Ansible的流程控制
playbook的流程控制
不管是shell
还是各大编程语言中,流程控制,条件判断这些都是必不可少的,在我们使用Ansible
的过程中,条件判断的使用频率极其高。
例如:
1.我们使用不同的系统的时候,可以通过判断系统来对软件包进行安装。
2.在nfs
和rsync
安装过程中,客户端服务器不需要推送配置文件,之前我们都是写多个play,会影响效率。
3.我们在源码安装nginx的时候,执行第二遍就无法执行了,此时我们就可以进行判断是否安装过。
#### 根据不同的系统安装apach
tasks:
- name: "shut down Debian flavored systems"
command: /sbin/shutdown -t now
when: ansible_facts['os_family'] == "Debian"
- hosts: all
tasks:
- name: Install CentOS Httpd
yum:
name: httpd
state: present
#官方
when: ansible_facts['os_family'] == "CentOS"
#非官方
when: ansible_distribution == "CentOS"
- name: Install Ubuntu Httpd
apt:
name: apache2
state: present
when: ansible_facts['os_family'] == "Debian"
使用括号进行分组
- hosts: aaa01 # 替换为具体的主机名
tasks:
- name: " CentOS 6 和 Debian 24 系统创建 111 目录"
command: mkdir 111
when: (ansible_facts['distribution'] == "CentOS" and ansible_facts['distribution_major_version'] == "6") or (ansible_facts['distribution'] == "Ubuntu" and ansible_facts['distribution_major_version'] == "24")
也可以指定多条件为列表
- hosts: aaa01 # 替换为具体的主机名
tasks:
- name: "创建 目录"
command: mkdir 2222
when:
- ansible_facts['distribution'] == "Ubuntu"
- ansible_facts['distribution_major_version'] == "24"
条件运算
- hosts: all
tasks:
- shell: 'echo "这是德便linux系统 ,系统版本大于6" >22.txt'
when: ansible_facts['os_family'] == "Debian" and ansible_facts['lsb']['major_release']|int >= 6
定义循环语句
在之前的学习过程中,我们经常会有传送文件,创建目录之类的操作,创建2个目录就要写两个file模块来创建,如果要创建100个目录,我们需要写100个file模块?,只要有循环即可,减少重复性代码。
- hosts: all
tasks:
- name: start service
systemd:
name: "{{ item }}"
state: started
with_items:
- httpd
- php-fpm
- mariadb
#### 定义变量循环
- name: ensure a list of packages installed
apt:
name: "{{ packages }}"
vars:
packages:
- httpd
- httpd-tools
- hosts: web_group
tasks:
- name: ensure a list of packages installed
apt: name= "{{ item }}" state=present
with_items:
- nginx
- mariadb-server
定义字典循环
#### 创建用户
cat loop.yml
- hosts: web_group
tasks:
- name: Add Users
user:
name: "{{ item.name }}"
groups: "{{ item.groups }}"
state: present
with_items:
- { name: 'zls', groups: 'linux' }
- { name: 'egon', groups: 'python' }
#### copy文件
- hosts: web_group
tasks:
- name: copy conf and code
copy:
src: "{{ item.src }}"
dest: "{{ item.dest }}"
mode: "{{ item.mode }}"
with_items:
- { src: "./httpd.conf", dest: "/etc/httpd/conf/", mode: "0644" }
- { src: "./upload_file.php", dest: "/var/www/html/", mode: "0600" }