第十一章 Ansibleplaybook变量注册和Facts缓存

一、变量注册概述

当absible的模块在运行之后,其实都会返回一些result结果,就像是执行脚本,我们有的时候需要脚本给我们一些return返回值,我们才知道,上一步是否可以执行成功,但是...默认情况下,ansible的result并不会显示出来,所以,我们可以把这些返回值'存储'到变量中,这样我们就能通过'调用'对应的变量名,从而获取到这些result,这种将模块的返回值,写入到变量中的方法被称为变量注册。

二、变量注册配置

1.配置

[root@m01 ~]# vim list.yml 
- hosts: web01
  tasks:
    - name: list dir
      shell: ls -l /root
      register: list_dir

2.输出调用的变量

[root@m01 ~]# vim list.yml 
- hosts: web01
  tasks:
    - name: list dir
      shell: ls -l /root
      register: list_dir
      
    - name: get list_dir
      debug:
        msg: "{{ list_dir }}"

3.输出我们想要的部分

[root@m01 ~]# vim list.yml 
- hosts: web01
  tasks:
    - name: list dir
      shell: ls -l /root
      register: list_dir
      
    - name: get list_dir
      debug:
        msg: "{{ list_dir.stdout_lines }}"

三、变量注册使用场景

#一般使用变量注册进行判断
[root@m01 ~]# cat install.yml 
- hosts: nfs
  tasks:
    - name: decide nfs status
      shell: systemctl is-active nfs
      ignore_errors: yes
      register: nfs_status

    - name: Start nfs
      systemd:
        name: nfs
        state: started
      when: nfs_status.rc != 0

    - name: Restart nfs
      systemd:
        name: nfs
        state: restarted 
      when: nfs_status.rc == 0

四、Facts缓存概述

Ansible facts是在被管理主机上通过Ansible自动采集发现的变量。facts包含每台特定的主机信息。比如:被控端的主机名、IP地址、系统版本、CPU数量、内存状态、磁盘状态等等。

setup模块实际上就是facts缓存得到的

五、Facts缓存使用场景

1.通过facts缓存检查CPU,来生成对应的nginx配置文件
2.通过facts缓存检查主机名,生成不同的zabbix配置文件
3.通过facts缓存检索物理机的内存大小来生成不通的mysql配置文件

综上所述的Ansible facts类似于saltstack中的grains对于做自动化的小伙伴是非常有用滴。

六、Facts缓存基本用法

#编辑
[root@m01 ~]# vim facts.yml
- hosts: web_group
  tasks:
    - name: Get Host Info
      debug:
        msg: Hostname "{{ ansible_fqdn }}" and IP "{{ ansible_default_ipv4.address }}"

七、关闭facts缓存

[root@m01 ~]# vim facts.yml
- hosts: web_group
  gather_facts: no #关闭信息采集
  tasks:
原文地址:https://www.cnblogs.com/jhno1/p/15723259.html