ansible之when简单调用

When语句
有时候用户有可能需要某一个主机越过某一个特定的步骤.这个过程就可以简单的像在某一个特定版本的系统上少装了一个包一样或者像在一个满了的文件系统上执行清理操作一样.
这些操作在Ansible上,若使用when语句都异常简单,能在when中使用jinja2的语法

1、自己定义的参数

vim /etc/ansible/hosts

在这里插入图片描述

---
- hosts: tomcat
  vars:
        tomca: 1
  tasks:
      - name: "nod1安装httpd"
        yum: name=httpd state=installed
        when: ansible_hosts == 'nod2'   #当ansible_hosts等于nod2时执行就是10.0.0.43
      - name: "nod2安装mysql"
        yum: name=mariadb,mariadb-server state=installed
        when: ansible_hosts == 'nod1'   #当ansible_hosts等于nod2时执行就是10.0.0.42

效果
在这里插入图片描述
2、setup的选项
setup
setup 模块用于收集远程主机的一些基本信息
选项:
filter参数:用于进行条件过滤。如果设置,仅返回匹配过滤条件的信息。
常用的过滤关键词:
ansible_all_ipv4_addresses:仅显示ipv4的信息
ansible_devices:仅显示磁盘设备信息
ansible_distribution:显示是什么系统,例:centos,suse等
ansible_distribution_major_version:显示是系统主版本
ansible_distribution_version:仅显示系统版本
ansible_machine:显示系统类型,例:32位,还是64位
ansible_eth0:仅显示eth0的信息
ansible_hostname:仅显示主机名

---
- hosts: tomcat
  vars:
        tomca: 1
  tasks:
      - name: "nod1安装httpd"
        yum: name=httpd state=removed
        when: ansible_hostname == 'co1'   #当主机名等于co1时执行,setup的选项
      - name: "nod2安装mysql"
        yum: name=mariadb,mariadb-server state=removed
        when: ansible_hostname == 'co2'   #当主机名等于co2时执行,setup的选项

效果
在这里插入图片描述
3、通过when判断变量示例:

---
---
- hosts: tomcat
  vars:
        tomca: 1
  tasks:
      - name: "nod1安装httpd"
        yum: name=httpd state=installed
        when: tomca == 1    #当变量等于co1时执行 ,不能加单引号,双引号
      - name: "nod2安装mysql"
        yum: name=mariadb,mariadb-server state=removed
        when: tomca == 2   #当变量等于co2时执行

效果
在这里插入图片描述
成功
在这里插入图片描述
4、ansible 使用when判断命令

---
- hosts: tomcat
  vars:
        tomca: 1
  tasks:
    - name: ps
      shell: rpm -qa|grep httpd|wc -l
      register: httpd_num   #命令结果赋值给httpd_num 
    - debug: var=httpd_num    #var=nginx_num这一项,结果执行的时候,总是skipping跳过,说明条件错误后来才使用debug模块调试,var固定
    - name: command
      yum: name=httpd state=removed
      when: httpd_num.stdout == "2"  #httpd_num.stdout,必须加stdout获取httpd_num的值

效果
在这里插入图片描述
成功
在这里插入图片描述

发布了139 篇原创文章 · 获赞 240 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/a13568hki/article/details/103874588