Ansible流程控制

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.先决条件

rsync配置文件
vim /etc/rsync.passwd

uid = www
gid = www
port = 873
fake super = yes
use chroot = no
max connections = 200
timeout = 600
ignore errors
read only = false
list = false
auth users = rsync_backup
secrets file = /etc/rsync.passwd
log file = /var/log/rsyncd.log
#####################################
[backup]
comment = welcome to oldboyedu backup!
path = /backup

# 3.编辑rsync playbook

[root@m01 rsync]# cat rsync.yml
- hosts: all
  tasks:
    - name: Install Rsync Server
      yum:
        name: rsync
      when: ansible_hostname == 'nfs' or ansible_hostname == 'backup'
    - name: Configure Rsync Conf
      copy:
        src: /root/rsync/rsyncd.conf
        dest: /etc/rsyncd.conf
      when: ansible_hostname == 'backup'
    - name: Create Rsync Passwd File
      copy:
        content: rsync_backup:123
        dest: /etc/rsync.passwd
        mode: 0600
      when: ansible_hostname == 'backup'
    - name: Create backup dir
      file:
        path: /backup
        state: directory
      when: ansible_hostname == 'backup'
    - name: Start Rsync Server
      service:
        name: rsyncd
        state: started
        enabled: yes
      when: ansible_hostname == 'backup'
    - name: Create nfs Passwd File
      copy:
        content: '123'
        dest: /etc/rsync.passwd
        mode: 0600
      when: ansible_hostname == 'nfs'

playbook循环语句

在之前的学习过程中,我们经常会有传送文件,创建目录之类的操作,创建2个目录就要写两个file模块来创建,如果
要创建100个目录,我们需要写100个file模块???妈耶~~ 当然不是,只要有循环即可,减少重复性代码。

循环语法

[root@m01 ~]# cat test_items.yml
- hosts: all
  tasks:
    - name: Start ge zhong fuwu
      service:
      name: "{{ item }}"
      state: stopped
    when: ansible_hostname is match 'web*'
    with_items:
      - nginx
      - php-fpm
    - name: Start nfs
      service:
        name: "{{ item }}"
        state: stopped
      when: ansible_hostname == 'nfs'
      with_items:
        - rsyncd
        - nfs-server

字典循环

pkg:httpd
key:value

1.创建用户

[root@m01 ~]# cat test_items.yml
- hosts: all
  tasks:
    - name: Create Group
      group:
        name: "{{ item }}"
      with_items:
        - linux
        - av
    - name: Create User
      user:
        name: "{{ item.name }}"
        group: "{{ item.group }}"
      with_items:
        - {name: "zls",group: "linux"}
        - {name: "cls",group: "av"}

2.推送配置文件

- name: Push All Conf
  copy:
    src: "{{ item.src }}"
    dest: "{{ item.dest }}"
  with_items:
    - {src: "/root/ansible/nginx.conf",dest: "/etc/nginx/nginx.conf"}
    - {src: "/root/ansible/blog.drz.com.conf",dest: "/etc/nginx/conf.d/blog.drz.com.conf"}
    - {src: "/root/ansible/www.conf",dest: "/etc/php-fpm.d/www.conf"}

playbook handlers(触发器)

handler用来执行某些条件下的任务,比如当配置文件发生变化的时候,通过notify触发handler去重启服务。
在saltstack中也有类似的触发器,写法相对Ansible简单,只需要watch,配置文件即可。

handlers:
  - name: Restart Rsync
    service:
      name: rsyncd
      state: restarted

[root@m01 rsync]# cat rsync.yml
- hosts: all
  tasks:
    - name: Install Rsync Server
      yum:
        name: rsync
      when: ansible_hostname == 'nfs' or ansible_hostname == 'backup'
    - name: Configure Rsync Conf
      copy:
        src: /root/rsync/rsyncd.conf
        dest: /etc/rsyncd.conf
      when: ansible_hostname == 'backup'
      notify:
        - Restart PHP
        - Restart Nginx
    - name: Create Rsync Passwd File
      copy:
      content: rsync_backup:123
      dest: /etc/rsync.passwd
      mode: 0600
    when: ansible_hostname == 'backup'
    - name: Create backup dir
      file:
        path: /backup
        state: directory
      when: ansible_hostname == 'backup'
    - name: Start Rsync Server
      service:
        name: rsyncd
        state: started
        enabled: yes
      when: ansible_hostname == 'backup'
    - name: Create nfs Passwd File
      copy:
        content: '123'
        dest: /etc/rsync.passwd
        mode: 0600
      when: ansible_hostname == 'nfs'
handlers:
  - name: Restart Rsync
    service:
      name: rsyncd
      state: restarted
  - name: Rstart NFS
    service:
      name: nfs-server
      state: restarted
  - name: Rstart Nginx
    service:
      name: nginx
      state: restarted
  - name: Rstart PHP
    service:
      name: php-fpm
      state: restarted

注意:
1.无论多少个task通知了相同的handlers,handlers仅会在所有tasks结束后运行一次。
2.Handlers只有在其所在的任务被执行时,才会被运行;如果一个任务中定义了notify调用Handlers,但是由于条件判断等原因,该任务未被执行,那么Handlers同样不会被执行。
3.Handlers只会在每一个play的末尾运行一次;如果想在一个playbook中间运行Handlers,则需要使用meta模块来实现。例如: -meta: flush_handlers。
4.如果一个play在运行到调用Handlers的语句之前失败了,那么这个Handlers将不会被执行。我们可以使用meta模块的--force-handlers选项来强制执行Handlers,即使Handlers所在的play中途运行失败也能执行。
5.不能使用handlers替代tasks

playbook tags (任务标签)

打标签的方式

1.对一个task打一个标签
2.对一个task打多个标签
3.对多个task打一个标签

打标签语法

- name: Push All Conf
  copy:
    src: "{{ item.src }}"
    dest: "{{ item.dest }}"
  with_items:
    - {src: "/root/ansible/nginx.conf",dest: "/etc/nginx/nginx.conf"}
    - {src: "/root/ansible/blog.drz.com.conf",dest: "/etc/nginx/conf.d/blog.drz.com.conf"}
  tags:
    - manager_nginx_server
  notify: Restart nginx
  when: ansible_hostname is match 'web*'

handlers:
  - name: Restart nginx
    service:
      name: nginx
      state: reloaded

执行

-t:执行指定的标签
--skip-tags:跳过指定标签

playbook include(剧本复用)

[root@m01 ansible_project]# cat task.yml
- hosts: all
  tasks:
    - include_tasks: rsync/install_rsync.yml
    - include_tasks: rsync/config_rsync.yml
    - include_tasks: rsync/start_rsync.yml
  handlers:
    - name: Restart Rsync
      service:
        name: rsyncd
        state: restarted

[root@m01 ansible_project]# tree /ansible_project/

/ansible_project/
├── group_vars
├── host_vars
│ ├── backup
│ └── nfs
├── mariadb
├── nfs
├── nginx
├── php
├── rsync
│ ├── config_rsync.yml
│ ├── install_rsync.yml
│ ├── rsyncd.conf
│ └── start_rsync.yml
├── sersync
└── task.yml


[root@m01 ansible_project]# cat rsync/install_rsync.yml
- name: Install rsync
  yum:
    name: "{{ pkg }}"
    state: absent
  when: ansible_hostname == 'nfs' or ansible_hostname == 'backup'

[root@m01 ansible_project]# cat rsync/config_rsync.yml
- name: Configure Rsync Server
  copy:
    src: ./rsyncd.conf
    dest: /etc/rsyncd.conf
  notify: Restart Rsync
  when: ansible_hostname == 'backup'

[root@m01 ansible_project]# cat rsync/start_rsync.yml
- name: Start Rsync
  service:
    name: rsyncd
    state: started
    enabled: yes
  when: ansible_hostname == 'backup'

忽略错误(ignore_errors)

- hosts: web_group
  gather_facts: no
  tasks:
    - name: panduan php
      shell: 'rpm -qa|grep php'
      register: panduan_php
      ignore_errors: yes
    - name: Install php
      shell: 'rpm -Uvh /tmp/*.rpm'
      when: panduan_php.rc != 0

抑制changed

将剧本执行过程中未改变但是还会执行的task结果由黄色强行改为绿色

vim nginx.yml
- hosts: web_group
  gather_facts: no
  tasks:
    - name: check nginx
      shell: '/sbin/nginx -t'
      register: check_nginx
      changed_when:
        - check_nginx.stderr_lines.0.find('ok')
        - false
posted @ 2021-08-16 19:19  远方还很远  阅读(100)  评论(0编辑  收藏  举报