zoukankan      html  css  js  c++  java
  • ansible——playbook conditions条件判断

    有些时候,我们需要进行一些条件判断才决定是否执行某个操作,在playbook里面when语句帮我们解决了这个问题。

    比如,如果节点的操作的系统为Debian那么就关机。

    tasks:
      - name: "shut down Debian flavored systems"
        command: /sbin/shutdown -t now
        when: ansible_facts['os_family'] == "Debian"

    当然还可以进行更加复杂的操作,and和or的逻辑判断。
    如果系统是centos6或者是Debian7,那么就关机。

    tasks:
      - name: "shut down CentOS 6 and Debian 7 systems"
        command: /sbin/shutdown -t now
        when: (ansible_facts['distribution'] == "CentOS" and ansible_facts['distribution_major_version'] == "6") or
              (ansible_facts['distribution'] == "Debian" and ansible_facts['distribution_major_version'] == "7")

    如果同时需要多个条件,那么可以这样:

    tasks:
      - name: "shut down CentOS 6 systems"
        command: /sbin/shutdown -t now
        when:
          - ansible_facts['distribution'] == "CentOS"
          - ansible_facts['distribution_major_version'] == "6"

    其实等价于下面:

    tasks:
      - name: "shut down CentOS 6 and Debian 7 systems"
        command: /sbin/shutdown -t now
        when: (ansible_facts['distribution'] == "CentOS" and ansible_facts['distribution_major_version'] == "6")

    有时候你会得到一个变量,它是一个字符串,你可以对其进行数学运算:

    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

    你还可以根据变量值,来判断:
    变量值:

    vars:
      epic: true

    判断:

    tasks:
        - shell: echo "This certainly is epic!"
          when: epic

    还可以循环:

    tasks:
        - command: echo {{ item }}
          loop: [ 0, 2, 4, 6, 8, 10 ]
          when: item > 5

    配合变量寄存器:

    - name: test play
      hosts: all
    
      tasks:
    
          - shell: cat /etc/motd
            register: motd_contents
    
          - shell: echo "motd contains the word hi"
            when: motd_contents.stdout.find('hi') != -1
  • 相关阅读:
    EasyUI 常用图标
    DataGridView滚动条联动
    FTP下载工具
    C# 解析带命名空间的xml
    1.基于3.x版本vue脚手架创建新项目
    js处理异步的几种方式
    JS字符串常用方法
    git(开源的分布式版本控制系统)
    js检查数据类型的方法
    数组的常用方法
  • 原文地址:https://www.cnblogs.com/yangmingxianshen/p/12657225.html
Copyright © 2011-2022 走看看