Teng's blog Teng's blog
首页
Java
H5前端
GitHub (opens new window)
首页
Java
H5前端
GitHub (opens new window)
  • 背景介绍
  • 安装
  • 配置说明
  • 基础命令
  • 常用模块
  • Playbook

    • 简单介绍
    • yaml语法
    • hosts
    • task
    • 运行playbook
    • handlers
    • tags
    • variables
    • template
    • when条件判断
      • 应用实例
    • with_items迭代
    • roles
    • 附:jinja2语法
  • Tool-Ansible
  • Playbook
Shetengteng
2022-05-13

when条件判断

如果需要根据变量、facts或此前任务的执行结果来做为某task执行与否的前提时使用when实现 在task中用于条件测试,并支持jinja2的语法格式

语法

  • 在task后添加when子句即可使用条件测试;when语句支持Jinja2表达式语法

简单示例:当系统属于红帽系列,执行

tasks:
  - name: "shutdown RedHat flavored systems"
    command: /sbin/shutdown -h now
    when: ansible_os_family == "RedHat"
1
2
3
4

when语句中还可以使用Jinja2的大多"filter",如要忽略此前某语句的错误并基于其结果(failed或者success)运行后面指定的语句

tasks:
  - command: /bin/false
    register: result
    ignore_errors: True
  - command: /bin/something
    when: result|failed
  - command: /bin/something_else
    when: result|success
  - command: /bin/still/something_else
    when: result|skipped
1
2
3
4
5
6
7
8
9
10

when语句中可以使用facts或playbook中定义的变量

# 应用实例

不同的系统版本使用不同的操作

- hosts: websrvs
  remote_user: root
  tasks:
    - name: add group nginx
      tags: user
      user: name=nginx state=present
    - name: add user nginx
      user: name=nginx state=present group=nginx
    - name: Install Nginx
      yum: name=nginx state=present
    - name: restart Nginx
      service: name=nginx state=restarted
      when: ansible_distribution_major_version == "6"
1
2
3
4
5
6
7
8
9
10
11
12
13

不同的系统版本使用不同的配置文件

tasks:
  - name: install conf file to centos7
    template: src=nginx.conf.c7.j2 dest=/etc/nginx/nginx.conf
    when: ansible_distribution_major_version == "7"
  - name: install conf file to centos6
    template: src=nginx.conf.c6.j2 dest=/etc/nginx/nginx.conf
    when: ansible_distribution_major_version == "6"
1
2
3
4
5
6
7
Last Updated: 2022/05/22, 12:42:00
template
with_items迭代

← template with_items迭代→

Theme by Vdoing | Copyright © 2021-2022 Shetengteng | MIT License
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式