Ansible学习笔记——facts变量

Ansible学习笔记——facts变量

  • facts变量基础使用
    • 使用adhoc(setup命令)查看facts
    • 使用debug查看facts变量
    • facts变量文件截取
    • 在playbook中读取facts变量
    • 关闭facts变量收集
    • 自定义facts
  • facts变量综合练习
    • 要求
    • 环境
    • yml文件操作

facts变量:查看在被管理主机上的一些参数,例如主机名称、内核版本、网络接口、ip地址、系统版本、磁盘空间等

facts变量基础使用

使用adhoc(setup命令)查看facts

在这里插入代码片

使用debug查看facts变量

[student@workstation wangxc]$ cat facts.yml 
---
- name: facts
  hosts: servera
  tasks:
    - name: test facts
      debug: 
        var: ansible_facts

facts变量文件截取

"ipv4": {
                "address": "127.0.0.1",
                "broadcast": "host",
                "netmask": "255.0.0.0",
                "network": "127.0.0.0"
            },


"fibre_channel_wwn": [],
        "fips": false,
        "form_factor": "Other",
        "fqdn": "servera.lab.example.com",
        "gather_subset": [
            "all"
        ],
        "hostname": "servera",
        "hostnqn": "",
        "interfaces": [
            "enp2s0",
            "enp1s0",
            "lo"
        ],
        "is_chroot": false,
        "iscsi_iqn": "",
        "kernel": "4.18.0-80.el8.x86_64",


在playbook中读取facts变量

通过debug方法,读取主机名和ip地址

tasks:
    - name: test facts
      debug:
        msg: >
          the ipv4 address is {{ ansible_facts.fqdn }} 
          is {{ ansible_facts.default_ipv4.address }}

输出结果:

ok: [servera] => {
    "msg": "the ipv4 address is servera.lab.example.com  is 172.25.250.10\n"
}

关闭facts变量收集

如果确认playbook中没有任何地方使用到facts,可以选择关闭变量收集。这能够有效的提升playbook的运行速度和效率。
在task中加入如下片段

gather_facts: no

再次执行facts.yml会提示找不到变量

[student@workstation wangxc]$ ansible-playbook  facts.yml 

PLAY [facts] *************************************************************************************************************************

TASK [test facts] ********************************************************************************************************************
fatal: [servera]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: 'dict object' has no attribute 'fqdn'\n\nThe error appears to be in '/home/student/wangxc/facts.yml': line 6, column 7, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n  tasks:\n    - name: test facts\n      ^ here\n"}

并且输出结果中已经没有下面这一行了

TASK [Gathering Facts] ***************************************************************************************************************
ok: [servera]

自定义facts

在被管理主机的 /etc/ansible/facts.d文件夹下新建一个以.fact结尾的文件,可以为json或ini格式。可写入自定义facts

[student@servera ~]$ cd /etc/ansible/facts.d/
[student@servera facts.d]$ ll
total 4
-rw-r--r--. 1 root root 44 Mar 16 17:52 servera.fact
[student@servera facts.d]$ cat servera.fact 
{
   "user":{
      "name": "wangxc"
   }
}

执行setup之后,可以从结果中查看到自定义facts

ansible servera -m setup >> 1.json
[student@workstation wangxc]$ vi 1.json 
 
 },
        "ansible_local": {
            "servera": {
                "user": {
                    "name": "wangxc"
                }
            }
        },
        "ansible_lsb": {},
        "ansible_lvm": {
            "lvs": {},

facts变量综合练习

要求

  1. 在workstation机器上,创建custom.fact文件,并传输到webserver主机组中。目的是,在执行主playbook是可以读取webserver组中的自定义facts变量。
  2. 使用主playbook在webserver组中的主机上安装httpd服务,并启动。安装过程中需要使用到自定义facts变量。

环境

[student@workstation data-facts]$ cat ansible.cfg 
[defaults]
inventory   = inventory
remote_user = devops

[privilege_escalation]
become      = true
[student@workstation data-facts]$ cat inventory 
[webserver]
servera.lab.example.com

yml文件操作

1、创建custom.fact变量文件

[student@workstation data-facts]$ cat custom.fact 
[general]
package = httpd
service = httpd
state = started
enabled = true

2、编写setup_facts.yml文件,在目标主机中创建文件夹,并将custom.fact文件拷贝过去

[student@workstation data-facts]$ cat setup_facts.yml 
---
- name: install remote facts
  hosts: webserver
  vars:
    remote_dir: /etc/ansible/facts.d
    facts_file: custom.fact
  tasks:
    - name: create the remote directory
      file:
        state: directory
        recurse: yes
        path: "{{ remote_dir }}"
    - name: install the new facts
      copy:
        src: "{{ facts_file }}"
        dest: "{{ remote_dir }}"

3、使用setup命令,查看facts变量。导出到webserver.json中,查看没有自定义变量。

ansible webserver -m setup >>webserver.json
#自定义变量为空
"ansible_local": {}

4、执行setup_facts.yml文件,将变量文件传输到webserver中
5、查看webserver中的自定义变量

"ansible_local": {
            "custom": {
                "general": {
                    "enabled": "true",
                    "package": "httpd",
                    "service": "httpd",
                    "state": "started"
                }
            }
        },

6、使用adhoc命令检查webserver中的httpd服务不存在

[student@workstation data-facts]$ ansible webserver -a 'systemctl status httpd'
servera.lab.example.com | FAILED | rc=4 >>
Unit httpd.service could not be found.non-zero return code

7、编写主playbook,使用自定义的fact变量安装软件包,并启动服务

[student@workstation data-facts]$ ansible-playbook playbook.yml 

PLAY [install apache and start servers] **********************************************************************************************

TASK [Gathering Facts] ***************************************************************************************************************
ok: [servera.lab.example.com]

TASK [install the package] ***********************************************************************************************************
ok: [servera.lab.example.com]

TASK [start service] *****************************************************************************************************************
changed: [servera.lab.example.com]

PLAY RECAP ***************************************************************************************************************************
servera.lab.example.com    : ok=3    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0  

8、查看webserver的httpd状态,已启动

[student@workstation data-facts]$ ansible webserver -a 'systemctl status httpd'
servera.lab.example.com | CHANGED | rc=0 >>
● httpd.service - The Apache HTTP Server
   Loaded: loaded (/usr/lib/systemd/system/httpd.service; enabled; vendor preset: disabled)
   Active: active (running) since Wed 2021-03-17 17:18:22 CST; 33min ago
     Docs: man:httpd.service(8)
 Main PID: 27884 (httpd)
   Status: "Running, listening on: port 80"
    Tasks: 213 (limit: 4956)
   Memory: 46.1M
   CGroup: /system.slice/httpd.service
           ├─27884 /usr/sbin/httpd -DFOREGROUND
           ├─27885 /usr/sbin/httpd -DFOREGROUND
           ├─27886 /usr/sbin/httpd -DFOREGROUND
           ├─27887 /usr/sbin/httpd -DFOREGROUND
           └─27888 /usr/sbin/httpd -DFOREGROUND

Mar 17 17:18:22 servera.lab.example.com systemd[1]: Starting The Apache HTTP Server...
Mar 17 17:18:22 servera.lab.example.com httpd[27884]: Server configured, listening on: port 80
Mar 17 17:18:22 servera.lab.example.com systemd[1]: Started The Apache HTTP Server.

你可能感兴趣的:(Linux,linux)