ansible任务控制语句使用方法

内容纲要

什么是ansible任务控制语句?

在playbook中,我们可能需要执行不同的任务,或者有不同的目标。当使用任务控制语句之后,可以轻松的实现对角色中不同主机管理的需求。这就是ansible任务控制语句的作用。

任务控制介绍及使用方法

下面我例举出在平时工作中常用的几个任务控制判断条件。
1.when
2.with_items
3.handlers
4.tag
5.ignore_errors

when语句

when最常用的方式是在任务中添加一个判断条件,注意when语句是没有括号的。当你在运行任务时,ansible会评估所有主机,并在条件符合的主机上执行语句。
例子:在selinux为disable的主机上安装apache。

---
- hosts: test
  remote_user: root

  tasks:
  - name: Print Selinux Status
    debug: msg={{ ansible_selinux.status }}

  - name: Install Apache Server
    yum: name=httpd state=present
    when: ansible_selinux.status == "disabled"

ansible when
这个示例中可以看到192.168.50.71这台机器selinux状态是enabled。然后when语句判断了selinux状态,跳过了这台机器。

with_items

with_items是一个循环语句,使用方法类似于facts变量。在with_items中我们可以定义多个变量并进行调用。
例子:批量安装软件并创建新用户,赋予用户所属组。

---
  - hosts: test
    remote_user: root

    tasks:
      - name: Install Apache Vsftp Server
        yum: name={{ item }} state=present
        with_items:
          - httpd
          - vsftpd

      - name: User add Create
        user: name={{ item.name }} group={{ item.group }} state=present
        with_items:
          - { name: 'wenjiangun', group: 'root' }
          - { name: 'lionel', group: 'root' }

handlers

handlers的作用是可以控制任务执行完需要触发的动作,比如我修改了/var/www/html中的文件,需要重启Apache显示才能生效。这里我们就可以使用handlers来实现。
例子:开启Apache服务,修改index.html。自动触发handlers重启生效。

---
  - hosts: test
    remote_user: root

    tasks:
    - name: Start Apache Server
      service: name=httpd state=started enabled=yes

    - name: Copy Localhost File
      copy: src=./index.html dest=/var/www/html/index.html
      notify: systemctl restart httpd

    handlers:
      - name: systemctl restart httpd
        service: name=httpd state=restarted

ansible handlers
ansible handlers

tag标签

我们知道playbook默认是顺序执行的。随着playbook中执行任务越来越多,有很多的任务不是每一次都要执行的,但是我们又不想重新写playbook,这时候可以用tag标签,手动执行哪个标签需要运行,他会自动略过没有标签的任务。
示例:只修改Apache配置文件

---
  - hosts: test
    remote_user: root

    tasks:
    - name: Start Apache Server
      service: name=httpd state=started enabled=yes

    - name: Copy Localhost File
      copy: src=./index.html dest=/var/www/html/index.html
      notify: systemctl restart httpd
      tags: Modify Apache File

    handlers:
      - name: systemctl restart httpd
        service: name=httpd state=restarted

ansible tag

ignore_errors

最后一个介绍的是ignore_errors。这个的用法是如果我们某个task执行的任务有问题想跳过的话,我们可以加上这个参数,即使任务执行的有问题,也会继续往下执行,不会退出。这里我把ps命令输错了,然后加上ignore_errors,还是会继续向下执行其他任务。
示例:

---
  - hosts: test
    remote_user: root

    tasks:
    - name: check ps
      shell: pss -ef
      ignore_errors: yes

    - name: Copy Localhost File
      copy: src=./index.html dest=/var/www/html/index.html

ansible ignore_errors

上面这些就我平时在playbook中常用的控制语句,官方还有很多的控制语句(包括但不限于这些)。加以利用,一定是可以简化工作的重复度。

相关链接:ansible任务控制
https://docs.ansible.com/ansible/latest/user_guide/playbooks_conditionals.html
上一篇:(ansible变量使用方法)
https://www.wenjiangun.com/blog/1243/

spacer

Leave a reply

评论审核已启用。您的评论可能需要一段时间后才能被显示。

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据