侧边栏壁纸
博主头像
小续的成长时光 博主等级

行动起来,活在当下

  • 累计撰写 21 篇文章
  • 累计创建 14 个标签
  • 累计收到 3 条评论

目 录CONTENT

文章目录

Ansible自动化 2、变量

小续
2024-06-17 / 0 评论 / 0 点赞 / 29 阅读 / 0 字 / 正在检测是否收录...

一、ansible变量优先级

  • extra vars 变量(在命令行中用-e);优先级最高

  • inventory中定义的连接变量(比如ansible_ssh_user);优先级第二

  • 大多数其他变量(命令行转换、play中的变量、role中的变量、include的变量);优先级第三

  • inventory中定义的其他变量;优先级第四

  • 有系统发现的facts变量;优先级第五

  • roledefaults变量;优先级最低

注意: 在inventory清单中定义的变量:单个主机定义的变量优先级高于主机组定义的变量

经过实验,ansible使用inventory定义变量的优先级顺序从高到低为:

host_vars下定义变量 ---> inventory中单个主机定义变量 ---> group_vars下定义变量 ---> inventory中组定义变量

1、YAML陷阱

YAML语法要求如果值以{{ foo }}开头的话,那么就需要将整行用双引号包起来,这是为了确认你不是想声明一个YAML字典。 如下面配置是不行的!!!

---
- hosts: app_servers
  vars:
    app_path: {{ base_path }}/data/web

应该改成下面这样:

---
- hosts: app_servers
  vars:
    app_path: "{{ base_path }}/data/web"

二、Ansible-playbook变量配置方式

1、在inventory中定义变量

可以直接在inventory(具体位置由ansible.cfg定义,配置文件优先级见上篇文章)中定义变量,表示该变量对对应的主机或主机组有效

$ cat ./hosts 
[test]
192.168.2.20 key=20180101
192.168.2.21 key="niubility"
​
$ vim ansi.yml 
---
- hosts: all
  gather_facts: False
  tasks:
    - name: haha
      debug: msg="the {{ inventory_hostname }} value is {{ key }}"
​
# 执行结果(注意 inventory_hostname 代表 inventory 列表列表里被控节点的主机名):
​
$ ansible-playbook ansi.yml 
 
PLAY [all] ********************************************************************************************************
 
TASK [haha] ********************************************************************************************************
ok: [10.4.7.101] => {
    "msg": "the 192.168.2.20 value is 20180101"
}
ok: [10.4.7.102] => {
    "msg": "the 192.168.2.21 value is niubility"
}
 
PLAY RECAP **************************************************************************************************************************************
10.4.7.101                 : ok=1    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
10.4.7.102                 : ok=1    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0 

2、通过host_vars和group_vars定义

可以通过在 ansible.cfg 配置文件的同目录下,新建目录 host_varsgroup_vars 目录,用来存放定义的变量

inventory清单中,单个主机定义的变量优先级高于group_vars定义的变量

➜  Ansible git:(master) ~ # tree                                                                         
.
├── ansible.cfg
├── ansible.cfg.default
├── group_vars
│   └── test
├── hosts
├── host_vars
│   ├── 192.168.2.20
│   └── 192.168.2.21

➜  Ansible git:(master) ~ # cat host_vars/192.168.2.20
---
ansible_ssh_user: root

➜  Ansible git:(master) ~ # cat group_vars/test                     
---
ansible_ssh_user: xkj
test: group_vars

3、通过var_file定义

$ cat vars.yml 
---
key: jiayou

$ cat play.yml 
---
- hosts: all
  gather_facts: False
  vars_files:
      - vars.yml
  tasks:
    - name: debug
      debug: msg="the {{ inventory_hostname }} valus is {{ key }}"

$ ansible-playbook bo.yml
TASK [debug] **********************************************************************************************************************************
ok: [192.168.2.20] => {
    "msg": "the 192.168.2.20 valus is jiayou"
}
ok: [192.168.2.21] => {
    "msg": "the 192.168.2.21 valus is jiayou"
}

4、通过vars_prompt交互式定义

playbook中定义vars_prompt的变量名和交互式提示信息,就可以实现在运行playbook时,通过交互的传入变量值。 private字段:用来定义交互时是否显示输入的值,默认privateyes,即不显示输入的值; default字段:用来定义变量的默认值

$ cat prom.yml 
---
- hosts: test
  remote_user: root
  vars_prompt:
      - name: "var1"
        prompt: "please input you name"
        private: no
      - name: "var2"
        prompt: "please input you age"
        private: yes
        default: 18
  tasks:
      - name: display var1
        debug: msg="your name of var1 is {{ var1 }}"
      - name: display var2
        debug: msg="you age of var2 is {{ var2 }}"

$ ansible-playbook prom.yml 
➜  Ansible git:(master) ✗ ansible-playbook tmp/prom.yml           
[WARNING]: Invalid characters were found in group names but not replaced, use -vvvv to see details
please input you name: test
please input you age [18]: 

TASK [display var1] ***************************************************************************************************************************************************************************************************************************************************************************************
ok: [192.168.2.20] => {
    "msg": "your name of var1 is test"
}
ok: [192.168.2.21] => {
    "msg": "your name of var1 is test"
}

TASK [display var2] ***************************************************************************************************************************************************************************************************************************************************************************************
ok: [192.168.2.20] => {
    "msg": "you age of var2 is 111"
}
ok: [192.168.2.21] => {
    "msg": "you age of var2 is 111"
}

PLAY RECAP ************************************************************************************************************************************************************************************************************************************************************************************************
192.168.2.20               : ok=3    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
192.168.2.21               : ok=3    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0 

5、通过命令行传入

除了vars_promptvars_files,也可以通过ansible-playbook命令行发送变量。如果想要编写一个通用的发布playbook时则特别有用!你可以传递应用的版本以便部署。例如下面命令(注意: --extra-vars 相等于 -e)

➜  Ansible git:(master) # cat tmp/exap.yml 
---
- hosts: '{{hosts}}'
  remote_user: '{{user}}'
  gather_facts: no
  tasks:
    - name: "一个测试"
      debug: msg="your hosts is {{hosts}}, user is {{user}}"

➜  Ansible git:(master) # ansible-playbook -e "hosts=test user=root" tmp/exap.yml
[WARNING]: Invalid characters were found in group names but not replaced, use -vvvv to see details
[WARNING]: Found variable using reserved name: hosts

PLAY [test] ***********************************************************************************************************************************************************************************************************************************************************************************************

TASK [一个测试] *******************************************************************************************************************************************************************************************************************************************************************************************
ok: [192.168.2.20] => {
    "msg": "your hosts is test, user is root"
}
ok: [192.168.2.21] => {
    "msg": "your hosts is test, user is root"
}

PLAY RECAP ************************************************************************************************************************************************************************************************************************************************************************************************
192.168.2.20               : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
192.168.2.21               : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

也可以将参数放在文件里面进行传递(注意命令行里要是用"@文件名"):

# 同样使用上面的例子
$ cat anhui.yml 
---
hosts: test
user: root

$ ansible-playbook exap.yml -e "@anhui.yml"
[WARNING]: Found variable using reserved name: hosts
 
PLAY [test] *************************************************************************************************************************************
 
TASK [Gathering Facts] **************************************************************************************************************************
ok: [10.4.7.101]
 
TASK [一个测试] *************************************************************************************************************************************
ok: [10.4.7.101] => {
    "msg": "your hosts is test, user is root"
}
 
PLAY RECAP **************************************************************************************************************************************
10.4.7.101                 : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0  

6、 在playbook剧本中定义变量

在playbook中定义变量需要用到Ansible的vars模块,可以将所有需要用到的变量统一在vars模块下定义,定义格式需要遵循YAML语言格式:

语法格式:

vars:
  - var1: value1
  - var2: value2
  - var3: value3
  - ....: .....

示例:

$ cat playbook.yml 
---
- hosts: test
  remote_user: root
  vars:
    - dir1: /root/Ansible
    - dir2: /root/Ansible/test1
    - dir3: /root/Ansible/test2
  tasks:
    - name: Create New Folder
      file: name={{ dir1 }} state=directory
    - name: Create New Folder
      file: name={{ dir2 }} state=directory
    - name: Create New Folder
      file: name={{ dir3 }} state=directory
​
$ ansible-playbook playbook.yml 
 
PLAY [test] *************************************************************************************************************************************
 
TASK [Gathering Facts] **************************************************************************************************************************
ok: [10.4.7.101]
 
TASK [Create New Folder] ************************************************************************************************************************
changed: [10.4.7.101]
 
TASK [Create New Folder] ************************************************************************************************************************
changed: [10.4.7.101]
 
TASK [Create New Folder] ************************************************************************************************************************
changed: [10.4.7.101]
 
PLAY RECAP **************************************************************************************************************************************
10.4.7.101                 : ok=4    changed=3    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0 

7、通过roles角色定义变量

Ansibleroles中定义变量,有两种方法

  • 将变量及值的键值对形式写到rolesvars目录下的main.yml文件中,这种方法适用于不想通过外部进行修改的变量

  • 将变量及值的键值对形式写到rolesdefaults目录下的main.yml文件中,这种变量优先级最低,适用于需要覆盖值的变量

main.yml格式如下:

---
var1: value1
var2: value2
var3: value3

注意:通过Roles定义的变量只适用于当前roles。

# roles目录结构
$ tree .
.
├── hosts
├── playbook.yml
└── test
    ├── files
    ├── tasks
    │   └── main.yml
    ├── templates
    └── vars
        └── main.yml
 
5 directories, 4 files
​
$ cat test/tasks/main.yml 
- name: create directory
  file: name={{ dir }} state=directory
- name: Get IP Address
  shell: echo `{{ cmd }}` >> {{ dir }}/{{ file }}
​
$ cat test/vars/main.yml 
cmd: hostname -I
​
$ cat playbook.yml 
---
- hosts: test
  remote_user: root
  roles:
    - test
    
$ cat hosts 
[test]
10.4.7.101 dir=/root/node2
10.4.7.102 dir=/root/node1
 
[node1]
10.4.7.100
 
[test:vars]
file=hostname.txt
​
$ ansible-playbook -i hosts  playbook.yml 
 
PLAY [test] *************************************************************************************************************************************
 
TASK [Gathering Facts] **************************************************************************************************************************
ok: [10.4.7.101]
ok: [10.4.7.102]
 
TASK [test : create directory] ******************************************************************************************************************
ok: [10.4.7.101]
ok: [10.4.7.102]
 
TASK [test : Get IP Address] ********************************************************************************************************************
changed: [10.4.7.102]
changed: [10.4.7.101]
 
PLAY RECAP **************************************************************************************************************************************
10.4.7.101                 : ok=3    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
10.4.7.102                 : ok=3    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

8、使用Facts获取的信息

还有其它地方可以获取变量, 这些变量是自动发现的,而不是用户自己设置的。Facts通过访问远程系统获取相应的信息,一个很好的例子就是远程主机的IP地址或者操作系统是什么

$ ansible test -m setup
# 使用以下命令可以查看哪些信息是可用的(test是上面在/etc/ansible/hosts列表文件中配置的主机群组)

$ ansible test -m setup|grep "ansible_python_version"
        "ansible_python_version": "2.7.5", 
# 在playbook中这样引用上面被控制主机的python版本: {{ ansible_python_version }}

$ ansible test -m setup|grep "ansible_nodename"
        "ansible_nodename": "template", 
# 可以在playbook中这样引用上面被控制主机的主机名: {{ ansible_nodename }}

$ ansible test -m setup | grep "ansible_hostname"
        "ansible_hostname": "template",
# 被控制主机的主机名变量还可以是: {{ ansible_hostname }}

如果关闭Facts,可以大大提高ansible的执行速度 ,关闭方法如下:

$ cat anhui.yml
---
- hosts: test
  gather_facts: no

9、register注册变量

register注册变量的主要用途是在运行命令时,把命令结果存储到一个变量中,不同模块的执行结果是不同的。运行playbook时使用-v选项可以看到可能的结果值,ansible执行任务的结果值可以保存在变量中,以便稍后使用它。

register方式主要用于在task之间传递变量。

$ cat /etc/ansible/hosts
[test]
10.4.7.101
10.4.7.102

$ cat register.yml
---
- hosts: test
  remote_user: root
  tasks:
      - name: register bo_test
        shell: hostname -I
        register: info
      - name: display info
        debug: msg="this host ip is {{ info['stdout'] }}"

$ ansible-playbook register.yml
 
PLAY [test] *************************************************************************************************************
 
TASK [Gathering Facts] **************************************************************************************************
ok: [10.4.7.102]
ok: [10.4.7.101]
 
TASK [register bo_test] *************************************************************************************************
changed: [10.4.7.102]
changed: [10.4.7.101]
 
TASK [display info] *****************************************************************************************************
ok: [10.4.7.101] => {
    "msg": "this host ip is 10.4.7.101 "
}
ok: [10.4.7.102] => {
    "msg": "this host ip is 10.4.7.102 "
}
 
PLAY RECAP **************************************************************************************************************
10.4.7.101                 : ok=3    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
10.4.7.102                 : ok=3    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

9.1、委派任务时使用循环导致的register变量问题

9.1.1、问题现象

今天编写kubernetes安装脚本时遇到个奇怪的问题,话不多说,直接上示例play

- hosts: nodes
  gather_facts: no
  tasks:
    - name: Get join command
      shell: kubeadm token create --print-join-command
      delegate_to: "{{item}}"
      with_items: "{{groups['master']}}"
      register: join_command
      failed_when: join_command.rc != 0
      ignore_errors: yes
    - name: test
      debug:
        msg: "join cmd is {{ join_command['stdout'] }}"
      when: (groups['nodes'] | length > 0) and (join_command is defined)

如上,可以看到我使用 delegate_toGet join command 任务委派到master节点上去执行,并将结果注册为join_command变量,并使用debug模块进行查看,但是执行时报错:

fatal: [192.168.2.26]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: 'dict object' has no attribute 'stdout'. 'dict object' has no attribute 'stdout'\n\nThe error appears to be in '/data/data/git/kubernetes/server/ansible_install/test.yaml': line 17, column 7, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n#      when: join_command is defined\n    - name: test\n      ^ here\n"}

9.1.2、排查过程

使用debug模块的var模块仔细观察对应的变量,playbook如下:

- hosts: nodes
  gather_facts: no
  tasks:
    - name: Get join command
      shell: kubeadm token create --print-join-command
      delegate_to: "{{item}}"
      with_items: "{{groups['master']}}"
      register: join_command
      failed_when: join_command.rc != 0
      ignore_errors: yes
    - name: test
      debug:
        var: join_command
      when: (groups['nodes'] | length > 0) and (join_command is defined)

输出变量如下:

"join_command": {
    "changed": true,
    "msg": "All items completed",
    "results": [
        {
            "ansible_loop_var": "item",
            "changed": true,
            "cmd": "kubeadm token create --print-join-command",
            "delta": "0:00:00.082566",
            "end": "2024-05-28 10:56:16.481004",
            "failed": false,
            "failed_when_result": false,
            "invocation": {
                "module_args": {
                    "_raw_params": "kubeadm token create --print-join-command",
                    "_uses_shell": true,
                    "argv": null,
                    "chdir": null,
                    "creates": null,
                    "executable": null,
                    "expand_argument_vars": true,
                    "removes": null,
                    "stdin": null,
                    "stdin_add_newline": true,
                    "strip_empty_ends": true
                }
            },
            "item": "192.168.2.25",
            "msg": "",
            "rc": 0,
            "start": "2024-05-28 10:56:16.398438",
            "stderr": "",
            "stderr_lines": [],
            "stdout": "kubeadm join 192.168.2.25:6443 --token qrk818.j9hmeeygxc7ynr2l --discovery-token-ca-cert-hash sha256:5ddcb5d0381f32f7b26e284d0489ef44e72337a36e3c8698f4d504f04ba906fa ",
            "stdout_lines": [
                "kubeadm join 192.168.2.25:6443 --token qrk818.j9hmeeygxc7ynr2l --discovery-token-ca-cert-hash sha256:5ddcb5d0381f32f7b26e284d0489ef44e72337a36e3c8698f4d504f04ba906fa "
            ]
        }
    ],
    "skipped": false
}

发现进行委派后的变量不太一样,这里也放一下正常的register变量

"join_command": {
    "changed": true,
    "cmd": "kubeadm token create --print-join-command",
    "delta": "0:00:00.080176",
    "end": "2024-05-28 10:47:56.296514",
    "failed": false,
    "failed_when_result": false,
    "msg": "",
    "rc": 0,
    "start": "2024-05-28 10:47:56.290831",
    "stderr": "",
    "stderr_lines": [],
    "stdout": "kubeadm join 192.168.2.25:6443 --token 4dvn2t.e7l46luxc87ggio2 --discovery-token-ca-cert-hash sha256:5ddcb5d0381f32f7b26e284d0489ef44e72337a36e3c8698f4d504f04ba906fa ",
    "stdout_lines": [
        "kubeadm join 192.168.2.25:6443 --token 4dvn2t.e7l46luxc87ggio2 --discovery-token-ca-cert-hash sha256:5ddcb5d0381f32f7b26e284d0489ef44e72337a36e3c8698f4d504f04ba906fa "
    ]
}

可以看出,进行任务委派后得到的join_command.result中才包含我要的信息,且中间包含item,推测并不是任务委派导致的,而是使用循环导致的register变化,于是修改playbook如下:

- hosts: nodes
  gather_facts: no
  tasks:
    - name: Get join command
      shell: kubeadm token create --print-join-command
      delegate_to: 192.168.2.25
#      with_items: "{{groups['master']}}"
      register: join_command
      failed_when: join_command.rc != 0
      ignore_errors: yes
    - name: test
      debug:
        msg: "{{ join_command }}"
      when: (groups['nodes'] | length > 0) and (join_command is defined)

执行后变量结果:

"join_command": {
    "changed": true,
    "cmd": "kubeadm token create --print-join-command",
    "delta": "0:00:00.080176",
    "end": "2024-05-28 11:27:59.875088",
    "failed": false,
    "failed_when_result": false,
    "msg": "",
    "rc": 0,
    "start": "2024-05-28 11:27:59.794912",
    "stderr": "",
    "stderr_lines": [],
    "stdout": "kubeadm join 192.168.2.25:6443 --token 4dvn2t.e7l46luxc87ggio2 --discovery-token-ca-cert-hash sha256:5ddcb5d0381f32f7b26e284d0489ef44e72337a36e3c8698f4d504f04ba906fa ",
    "stdout_lines": [
        "kubeadm join 192.168.2.25:6443 --token 4dvn2t.e7l46luxc87ggio2 --discovery-token-ca-cert-hash sha256:5ddcb5d0381f32f7b26e284d0489ef44e72337a36e3c8698f4d504f04ba906fa "
    ]
}

综上,基本得出结论,由于使用了with_items导致registry变量问题。接下来就是解决方法。

9.1.3、解决方法

目前能想到的解决方法有两种:

  • 取消使用循环

  • 使用循环,修改变量使用方法

这里采用了第二种,修改变量使用方法,修改后playbook如下:

- hosts: nodes
  gather_facts: no
  tasks:
    - name: Get join command
      shell: kubeadm token create --print-join-command
      delegate_to: 192.168.2.25
      with_items: "{{groups['master']}}"
      register: join_command
      failed_when: join_command.rc != 0
      ignore_errors: yes
    - name: test
      debug:
        msg: "{{ join_command.results[0].stdout }}"
      when: join_command is defined

从上面变量结果看,可以看出join_command.results是一个list类型变量,而非dict,所以在调用时需要用这种形式:join_command.results[0].stdout

test任务执行结果如下:

TASK [test] *********************************************************************************************************************************************************************************************
ok: [192.168.2.26] => {
    "msg": "kubeadm join 192.168.2.25:6443 --token mv7n3p.k0nkbd29nwwbjsx4 --discovery-token-ca-cert-hash sha256:5ddcb5d0381f32f7b26e284d0489ef44e72337a36e3c8698f4d504f04ba906fa "
}

如上,解决了register变量问题。

总结:使用循环时,register变量会发生变化,需要修改对应的变量调用方法。

10、hostvars 变量

该变量用于引用其他主机上收集的facts中的数据,或者引用其他主机的主机变量、主机组变量。即从一台远程主机获取另一台远程主机的变量

$ cat /etc/ansible/hosts
[test]
10.4.7.101 addr=beijing
10.4.7.102 user=shibo age=39
​
$ cat test.yml
---
- hosts: test
  remote_user: root
  gather_facts: False
  tasks:
    - name: this is test1
      debug: msg="She is come from {{ hostvars['10.4.7.101']['addr'] }}"
    - name: this is test2
      debug: msg="I am {{ hostvars['10.4.7.102']['user'] }}, and age is {{ hostvars['10.4.7.102']['age'] }}"
​
$ ansible-playbook test.yml
 
PLAY [test] *************************************************************************************************************
 
TASK [this is test1] ****************************************************************************************************
ok: [10.4.7.101] => {
    "msg": "She is come from beijing"
}
ok: [10.4.7.102] => {
    "msg": "She is come from beijing"
}
 
TASK [this is test2] ****************************************************************************************************
ok: [10.4.7.101] => {
    "msg": "I am shibo, and age is 39"
}
ok: [10.4.7.102] => {
    "msg": "I am shibo, and age is 39"
}
 
PLAY RECAP **************************************************************************************************************
10.4.7.101                 : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
10.4.7.102                 : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

11、列表变量、循环变量、字典变量

11.1、ansible传列表作为变量

$ cat test.yml
---
- hosts: test
  remote_user: root
  gather_facts: False
  vars:
    - list: [1,2,3]
  tasks:
    - name: echo
      debug: msg="{{ list }}"
​
$ ansible-playbook test.yml
 
PLAY [test] *************************************************************************************************************
 
TASK [echo] *************************************************************************************************************
ok: [10.4.7.101] => {
    "msg": [
        1,
        2,
        3
    ]
}
ok: [10.4.7.102] => {
    "msg": [
        1,
        2,
        3
    ]
}
 
PLAY RECAP **************************************************************************************************************
10.4.7.101                 : ok=1    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
10.4.7.102                 : ok=1    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=

11.2、循环列表

结合循环,这个特性就变得很有用;以参数传递列表给playbook,不用在playbook中固定循环的次数与内容。

➜  Ansible git:(master) # cat tmp/exap.yml
---
- hosts: test
  remote_user: root
  gather_facts: no
  vars:
    - list:
        - 1
        - 2
        - 3
  tasks:
      - name: loop
        debug:
          msg: "{{item}}"
        with_items: "{{list}}"

➜  Ansible git:(master) # ansible-playbook -v  tmp/exap.yml
PLAY [test] ***********************************************************************************************************************************************************************************************************************************************************************************************

TASK [loop] ***********************************************************************************************************************************************************************************************************************************************************************************************
ok: [192.168.2.20] => (item=1) => {
    "msg": 1
}
ok: [192.168.2.20] => (item=2) => {
    "msg": 2
}
ok: [192.168.2.20] => (item=3) => {
    "msg": 3
}
ok: [192.168.2.21] => (item=1) => {
    "msg": 1
}
ok: [192.168.2.21] => (item=2) => {
    "msg": 2
}
ok: [192.168.2.21] => (item=3) => {
    "msg": 3
}

PLAY RECAP ************************************************************************************************************************************************************************************************************************************************************************************************
192.168.2.20               : ok=1    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
192.168.2.21               : ok=1    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0 

12、set_facts变量

# 使用set_facts模块可以设置为主机的facts变量
# 实例:

三、特殊变量的值

1、ansible facts变量

ok: [192.168.2.21] => {
    "msg": {
        "all_ipv4_addresses": [
            "192.168.2.21",
            "172.17.0.1",
            "10.250.40.128",
            "10.111.99.96",
            "10.96.218.13",
            "10.96.0.10",
            "10.96.0.1"
        ],
        "all_ipv6_addresses": [
            "fe80::b89b:af90:6d04:5fa2",
            "fe80::ecee:eeff:feee:eeee",
            "fe80::ecee:eeff:feee:eeee"
        ],
        "ansible_local": {},
        "apparmor": {
            "status": "disabled"
        },
        "architecture": "x86_64",
        "bios_date": "04/01/2014",
        "bios_vendor": "SeaBIOS",
        "bios_version": "rel-1.16.1-0-g3208b098f51a-prebuilt.qemu.org",
        "board_asset_tag": "NA",
        "board_name": "NA",
        "board_serial": "NA",
        "board_vendor": "NA",
        "board_version": "NA",
        "calia8f9eba266e": {
            "active": true,
            "device": "calia8f9eba266e",
            "features": {
                "busy_poll": "off [fixed]",
                "fcoe_mtu": "off [fixed]",
                "generic_receive_offload": "on",
                "generic_segmentation_offload": "on",
                "highdma": "on",
                "hw_tc_offload": "off [fixed]",
                "l2_fwd_offload": "off [fixed]",
                "large_receive_offload": "off [fixed]",
                "loopback": "off [fixed]",
                "netns_local": "off [fixed]",
                "ntuple_filters": "off [fixed]",
                "receive_hashing": "off [fixed]",
                "rx_all": "off [fixed]",
                "rx_checksumming": "on",
                "rx_fcs": "off [fixed]",
                "rx_gro_hw": "off [fixed]",
                "rx_udp_tunnel_port_offload": "off [fixed]",
                "rx_vlan_filter": "off [fixed]",
                "rx_vlan_offload": "on",
                "rx_vlan_stag_filter": "off [fixed]",
                "rx_vlan_stag_hw_parse": "on",
                "scatter_gather": "on",
                "tcp_segmentation_offload": "on",
                "tx_checksum_fcoe_crc": "off [fixed]",
                "tx_checksum_ip_generic": "on",
                "tx_checksum_ipv4": "off [fixed]",
                "tx_checksum_ipv6": "off [fixed]",
                "tx_checksum_sctp": "on",
                "tx_checksumming": "on",
                "tx_fcoe_segmentation": "off [fixed]",
                "tx_gre_csum_segmentation": "on",
                "tx_gre_segmentation": "on",
                "tx_gso_partial": "off [fixed]",
                "tx_gso_robust": "off [fixed]",
                "tx_ipip_segmentation": "on",
                "tx_lockless": "on [fixed]",
                "tx_nocache_copy": "off",
                "tx_scatter_gather": "on",
                "tx_scatter_gather_fraglist": "on",
                "tx_sctp_segmentation": "on",
                "tx_sit_segmentation": "on",
                "tx_tcp6_segmentation": "on",
                "tx_tcp_ecn_segmentation": "on",
                "tx_tcp_mangleid_segmentation": "on",
                "tx_tcp_segmentation": "on",
                "tx_udp_tnl_csum_segmentation": "on",
                "tx_udp_tnl_segmentation": "on",
                "tx_vlan_offload": "on",
                "tx_vlan_stag_hw_insert": "on",
                "udp_fragmentation_offload": "on",
                "vlan_challenged": "off [fixed]"
            },
            "hw_timestamp_filters": [],
            "ipv6": [
                {
                    "address": "fe80::ecee:eeff:feee:eeee",
                    "prefix": "64",
                    "scope": "link"
                }
            ],
            "macaddress": "ee:ee:ee:ee:ee:ee",
            "mtu": 1480,
            "promisc": false,
            "speed": 10000,
            "timestamping": [
                "rx_software",
                "software"
            ],
            "type": "ether"
        },
        "calibab978770c0": {
            "active": true,
            "device": "calibab978770c0",
            "features": {
                "busy_poll": "off [fixed]",
                "fcoe_mtu": "off [fixed]",
                "generic_receive_offload": "on",
                "generic_segmentation_offload": "on",
                "highdma": "on",
                "hw_tc_offload": "off [fixed]",
                "l2_fwd_offload": "off [fixed]",
                "large_receive_offload": "off [fixed]",
                "loopback": "off [fixed]",
                "netns_local": "off [fixed]",
                "ntuple_filters": "off [fixed]",
                "receive_hashing": "off [fixed]",
                "rx_all": "off [fixed]",
                "rx_checksumming": "on",
                "rx_fcs": "off [fixed]",
                "rx_gro_hw": "off [fixed]",
                "rx_udp_tunnel_port_offload": "off [fixed]",
                "rx_vlan_filter": "off [fixed]",
                "rx_vlan_offload": "on",
                "rx_vlan_stag_filter": "off [fixed]",
                "rx_vlan_stag_hw_parse": "on",
                "scatter_gather": "on",
                "tcp_segmentation_offload": "on",
                "tx_checksum_fcoe_crc": "off [fixed]",
                "tx_checksum_ip_generic": "on",
                "tx_checksum_ipv4": "off [fixed]",
                "tx_checksum_ipv6": "off [fixed]",
                "tx_checksum_sctp": "on",
                "tx_checksumming": "on",
                "tx_fcoe_segmentation": "off [fixed]",
                "tx_gre_csum_segmentation": "on",
                "tx_gre_segmentation": "on",
                "tx_gso_partial": "off [fixed]",
                "tx_gso_robust": "off [fixed]",
                "tx_ipip_segmentation": "on",
                "tx_lockless": "on [fixed]",
                "tx_nocache_copy": "off",
                "tx_scatter_gather": "on",
                "tx_scatter_gather_fraglist": "on",
                "tx_sctp_segmentation": "on",
                "tx_sit_segmentation": "on",
                "tx_tcp6_segmentation": "on",
                "tx_tcp_ecn_segmentation": "on",
                "tx_tcp_mangleid_segmentation": "on",
                "tx_tcp_segmentation": "on",
                "tx_udp_tnl_csum_segmentation": "on",
                "tx_udp_tnl_segmentation": "on",
                "tx_vlan_offload": "on",
                "tx_vlan_stag_hw_insert": "on",
                "udp_fragmentation_offload": "on",
                "vlan_challenged": "off [fixed]"
            },
            "hw_timestamp_filters": [],
            "ipv6": [
                {
                    "address": "fe80::ecee:eeff:feee:eeee",
                    "prefix": "64",
                    "scope": "link"
                }
            ],
            "macaddress": "ee:ee:ee:ee:ee:ee",
            "mtu": 1480,
            "promisc": false,
            "speed": 10000,
            "timestamping": [
                "rx_software",
                "software"
            ],
            "type": "ether"
        },
        "chassis_asset_tag": "NA",
        "chassis_serial": "NA",
        "chassis_vendor": "QEMU",
        "chassis_version": "pc-i440fx-7.2",
        "cmdline": {
            "BOOT_IMAGE": "/vmlinuz-3.10.0-1160.el7.x86_64",
            "LANG": "en_US.UTF-8",
            "quiet": true,
            "rd.lvm.lv": "centos/swap",
            "rhgb": true,
            "ro": true,
            "root": "/dev/mapper/centos-root"
        },
        "date_time": {
            "date": "2024-05-13",
            "day": "13",
            "epoch": "1715586180",
            "epoch_int": "1715586180",
            "hour": "15",
            "iso8601": "2024-05-13T07:43:00Z",
            "iso8601_basic": "20240513T154300910961",
            "iso8601_basic_short": "20240513T154300",
            "iso8601_micro": "2024-05-13T07:43:00.910961Z",
            "minute": "43",
            "month": "05",
            "second": "00",
            "time": "15:43:00",
            "tz": "CST",
            "tz_dst": "CST",
            "tz_offset": "+0800",
            "weekday": "星期一",
            "weekday_number": "1",
            "weeknumber": "20",
            "year": "2024"
        },
        "default_ipv4": {
            "address": "192.168.2.21",
            "alias": "eth0",
            "broadcast": "192.168.2.255",
            "gateway": "192.168.2.1",
            "interface": "eth0",
            "macaddress": "1a:80:cc:42:98:2b",
            "mtu": 1500,
            "netmask": "255.255.255.0",
            "network": "192.168.2.0",
            "prefix": "24",
            "type": "ether"
        },
        "default_ipv6": {},
        "device_links": {
            "ids": {
                "dm-0": [
                    "dm-name-centos-root",
                    "dm-uuid-LVM-qfioeKEdGA5ddvQ2WB6p3qdjFkQdsI1wYAbc0alHgruoB4FGcNbxmkRFXhC9HWYw"
                ],
                "dm-1": [
                    "dm-name-centos-swap",
                    "dm-uuid-LVM-qfioeKEdGA5ddvQ2WB6p3qdjFkQdsI1wcKLmot3sf9F9RuSwDYn4lLAxpF2gCcDZ"
                ],
                "sda": [
                    "ata-QEMU_HARDDISK_QM00005"
                ],
                "sda1": [
                    "ata-QEMU_HARDDISK_QM00005-part1"
                ],
                "sda2": [
                    "ata-QEMU_HARDDISK_QM00005-part2",
                    "lvm-pv-uuid-XwBJvP-uW4l-YaJb-3rDR-YTou-lise-3sUHSy"
                ],
                "sr0": [
                    "ata-QEMU_DVD-ROM_QM00003"
                ]
            },
            "labels": {
                "sr0": [
                    "CentOS\\x207\\x20x86_64"
                ]
            },
            "masters": {
                "sda2": [
                    "dm-0",
                    "dm-1"
                ]
            },
            "uuids": {
                "dm-0": [
                    "e9f954fc-b8a1-428b-8b50-15563c638099"
                ],
                "dm-1": [
                    "d0afdfff-3a07-4544-86fe-d9fb436e9483"
                ],
                "sda1": [
                    "6e152b2b-0ae0-4eec-b55d-65f24544553d"
                ],
                "sr0": [
                    "2020-11-04-11-36-43-00"
                ]
            }
        },
        "devices": {
            "dm-0": {
                "holders": [],
                "host": "",
                "links": {
                    "ids": [
                        "dm-name-centos-root",
                        "dm-uuid-LVM-qfioeKEdGA5ddvQ2WB6p3qdjFkQdsI1wYAbc0alHgruoB4FGcNbxmkRFXhC9HWYw"
                    ],
                    "labels": [],
                    "masters": [],
                    "uuids": [
                        "e9f954fc-b8a1-428b-8b50-15563c638099"
                    ]
                },
                "model": null,
                "partitions": {},
                "removable": "0",
                "rotational": "0",
                "sas_address": null,
                "sas_device_handle": null,
                "scheduler_mode": "",
                "sectors": "398450688",
                "sectorsize": "512",
                "serial": "QM00005",
                "size": "190.00 GB",
                "support_discard": "512",
                "vendor": null,
                "virtual": 1
            },
            "dm-1": {
                "holders": [],
                "host": "",
                "links": {
                    "ids": [
                        "dm-name-centos-swap",
                        "dm-uuid-LVM-qfioeKEdGA5ddvQ2WB6p3qdjFkQdsI1wcKLmot3sf9F9RuSwDYn4lLAxpF2gCcDZ"
                    ],
                    "labels": [],
                    "masters": [],
                    "uuids": [
                        "d0afdfff-3a07-4544-86fe-d9fb436e9483"
                    ]
                },
                "model": null,
                "partitions": {},
                "removable": "0",
                "rotational": "0",
                "sas_address": null,
                "sas_device_handle": null,
                "scheduler_mode": "",
                "sectors": "16777216",
                "sectorsize": "512",
                "serial": "QM00005",
                "size": "8.00 GB",
                "support_discard": "512",
                "vendor": null,
                "virtual": 1
            },
            "sda": {
                "holders": [],
                "host": "",
                "links": {
                    "ids": [
                        "ata-QEMU_HARDDISK_QM00005"
                    ],
                    "labels": [],
                    "masters": [],
                    "uuids": []
                },
                "model": "QEMU HARDDISK",
                "partitions": {
                    "sda1": {
                        "holders": [],
                        "links": {
                            "ids": [
                                "ata-QEMU_HARDDISK_QM00005-part1"
                            ],
                            "labels": [],
                            "masters": [],
                            "uuids": [
                                "6e152b2b-0ae0-4eec-b55d-65f24544553d"
                            ]
                        },
                        "sectors": "4194304",
                        "sectorsize": 512,
                        "size": "2.00 GB",
                        "start": "2048",
                        "uuid": "6e152b2b-0ae0-4eec-b55d-65f24544553d"
                    },
                    "sda2": {
                        "holders": [
                            "centos-root",
                            "centos-swap"
                        ],
                        "links": {
                            "ids": [
                                "ata-QEMU_HARDDISK_QM00005-part2",
                                "lvm-pv-uuid-XwBJvP-uW4l-YaJb-3rDR-YTou-lise-3sUHSy"
                            ],
                            "labels": [],
                            "masters": [
                                "dm-0",
                                "dm-1"
                            ],
                            "uuids": []
                        },
                        "sectors": "415234048",
                        "sectorsize": 512,
                        "size": "198.00 GB",
                        "start": "4196352",
                        "uuid": null
                    }
                },
                "removable": "0",
                "rotational": "0",
                "sas_address": null,
                "sas_device_handle": null,
                "scheduler_mode": "deadline",
                "sectors": "419430400",
                "sectorsize": "512",
                "serial": "QM00005",
                "size": "200.00 GB",
                "support_discard": "512",
                "vendor": "ATA",
                "virtual": 1
            },
            "sr0": {
                "holders": [],
                "host": "",
                "links": {
                    "ids": [
                        "ata-QEMU_DVD-ROM_QM00003"
                    ],
                    "labels": [
                        "CentOS\\x207\\x20x86_64"
                    ],
                    "masters": [],
                    "uuids": [
                        "2020-11-04-11-36-43-00"
                    ]
                },
                "model": "QEMU DVD-ROM",
                "partitions": {},
                "removable": "1",
                "rotational": "1",
                "sas_address": null,
                "sas_device_handle": null,
                "scheduler_mode": "deadline",
                "sectors": "9203712",
                "sectorsize": "2048",
                "size": "4.39 GB",
                "support_discard": "0",
                "vendor": "QEMU",
                "virtual": 1
            }
        },
        "discovered_interpreter_python": "/usr/bin/python",
        "distribution": "CentOS",
        "distribution_file_parsed": true,
        "distribution_file_path": "/etc/redhat-release",
        "distribution_file_variety": "RedHat",
        "distribution_major_version": "7",
        "distribution_release": "Core",
        "distribution_version": "7.9",
        "dns": {
            "nameservers": [
                "192.168.2.7",
                "223.5.5.5"
            ]
        },
        "docker0": {
            "active": false,
            "device": "docker0",
            "features": {
                "busy_poll": "off [fixed]",
                "fcoe_mtu": "off [fixed]",
                "generic_receive_offload": "on",
                "generic_segmentation_offload": "on",
                "highdma": "on",
                "hw_tc_offload": "off [fixed]",
                "l2_fwd_offload": "off [fixed]",
                "large_receive_offload": "off [fixed]",
                "loopback": "off [fixed]",
                "netns_local": "on [fixed]",
                "ntuple_filters": "off [fixed]",
                "receive_hashing": "off [fixed]",
                "rx_all": "off [fixed]",
                "rx_checksumming": "off [fixed]",
                "rx_fcs": "off [fixed]",
                "rx_gro_hw": "off [fixed]",
                "rx_udp_tunnel_port_offload": "off [fixed]",
                "rx_vlan_filter": "off [fixed]",
                "rx_vlan_offload": "off [fixed]",
                "rx_vlan_stag_filter": "off [fixed]",
                "rx_vlan_stag_hw_parse": "off [fixed]",
                "scatter_gather": "on",
                "tcp_segmentation_offload": "on",
                "tx_checksum_fcoe_crc": "off [fixed]",
                "tx_checksum_ip_generic": "on",
                "tx_checksum_ipv4": "off [fixed]",
                "tx_checksum_ipv6": "off [fixed]",
                "tx_checksum_sctp": "off [fixed]",
                "tx_checksumming": "on",
                "tx_fcoe_segmentation": "on",
                "tx_gre_csum_segmentation": "on",
                "tx_gre_segmentation": "on",
                "tx_gso_partial": "on",
                "tx_gso_robust": "on",
                "tx_ipip_segmentation": "on",
                "tx_lockless": "on [fixed]",
                "tx_nocache_copy": "off",
                "tx_scatter_gather": "on",
                "tx_scatter_gather_fraglist": "on",
                "tx_sctp_segmentation": "on",
                "tx_sit_segmentation": "on",
                "tx_tcp6_segmentation": "on",
                "tx_tcp_ecn_segmentation": "on",
                "tx_tcp_mangleid_segmentation": "on",
                "tx_tcp_segmentation": "on",
                "tx_udp_tnl_csum_segmentation": "on",
                "tx_udp_tnl_segmentation": "on",
                "tx_vlan_offload": "on",
                "tx_vlan_stag_hw_insert": "on",
                "udp_fragmentation_offload": "on",
                "vlan_challenged": "off [fixed]"
            },
            "hw_timestamp_filters": [],
            "id": "8000.0242f3a61e53",
            "interfaces": [],
            "ipv4": {
                "address": "172.17.0.1",
                "broadcast": "172.17.255.255",
                "netmask": "255.255.0.0",
                "network": "172.17.0.0",
                "prefix": "16"
            },
            "macaddress": "02:42:f3:a6:1e:53",
            "mtu": 1500,
            "promisc": false,
            "stp": false,
            "timestamping": [
                "rx_software",
                "software"
            ],
            "type": "bridge"
        },
        "domain": "",
        "dummy0": {
            "active": false,
            "device": "dummy0",
            "features": {
                "busy_poll": "off [fixed]",
                "fcoe_mtu": "off [fixed]",
                "generic_receive_offload": "on",
                "generic_segmentation_offload": "on",
                "highdma": "on [fixed]",
                "hw_tc_offload": "off [fixed]",
                "l2_fwd_offload": "off [fixed]",
                "large_receive_offload": "off [fixed]",
                "loopback": "off [fixed]",
                "netns_local": "off [fixed]",
                "ntuple_filters": "off [fixed]",
                "receive_hashing": "off [fixed]",
                "rx_all": "off [fixed]",
                "rx_checksumming": "off [fixed]",
                "rx_fcs": "off [fixed]",
                "rx_gro_hw": "off [fixed]",
                "rx_udp_tunnel_port_offload": "off [fixed]",
                "rx_vlan_filter": "off [fixed]",
                "rx_vlan_offload": "off [fixed]",
                "rx_vlan_stag_filter": "off [fixed]",
                "rx_vlan_stag_hw_parse": "off [fixed]",
                "scatter_gather": "on",
                "tcp_segmentation_offload": "on",
                "tx_checksum_fcoe_crc": "off [fixed]",
                "tx_checksum_ip_generic": "on [fixed]",
                "tx_checksum_ipv4": "off [fixed]",
                "tx_checksum_ipv6": "off [fixed]",
                "tx_checksum_sctp": "off [fixed]",
                "tx_checksumming": "on",
                "tx_fcoe_segmentation": "off [fixed]",
                "tx_gre_csum_segmentation": "off [fixed]",
                "tx_gre_segmentation": "off [fixed]",
                "tx_gso_partial": "off [fixed]",
                "tx_gso_robust": "off [fixed]",
                "tx_ipip_segmentation": "off [fixed]",
                "tx_lockless": "on [fixed]",
                "tx_nocache_copy": "off",
                "tx_scatter_gather": "on [fixed]",
                "tx_scatter_gather_fraglist": "on [fixed]",
                "tx_sctp_segmentation": "off [fixed]",
                "tx_sit_segmentation": "off [fixed]",
                "tx_tcp6_segmentation": "off [fixed]",
                "tx_tcp_ecn_segmentation": "off [fixed]",
                "tx_tcp_mangleid_segmentation": "off [fixed]",
                "tx_tcp_segmentation": "on [fixed]",
                "tx_udp_tnl_csum_segmentation": "off [fixed]",
                "tx_udp_tnl_segmentation": "off [fixed]",
                "tx_vlan_offload": "off [fixed]",
                "tx_vlan_stag_hw_insert": "off [fixed]",
                "udp_fragmentation_offload": "off [fixed]",
                "vlan_challenged": "off [fixed]"
            },
            "hw_timestamp_filters": [],
            "macaddress": "4a:22:9d:27:e9:21",
            "mtu": 1500,
            "promisc": false,
            "timestamping": [
                "rx_software",
                "software"
            ],
            "type": "ether"
        },
        "effective_group_id": 0,
        "effective_user_id": 0,
        "env": {
            "HOME": "/root",
            "LANG": "zh_CN.UTF-8",
            "LC_ADDRESS": "zh_CN.UTF-8",
            "LC_IDENTIFICATION": "zh_CN.UTF-8",
            "LC_MEASUREMENT": "zh_CN.UTF-8",
            "LC_MONETARY": "zh_CN.UTF-8",
            "LC_NAME": "zh_CN.UTF-8",
            "LC_NUMERIC": "zh_CN.UTF-8",
            "LC_PAPER": "zh_CN.UTF-8",
            "LC_TELEPHONE": "zh_CN.UTF-8",
            "LC_TIME": "zh_CN.UTF-8",
            "LOGNAME": "root",
            "LS_COLORS": "rs=0:di=38;5;27:ln=38;5;51:mh=44;38;5;15:pi=40;38;5;11:so=38;5;13:do=38;5;5:bd=48;5;232;38;5;11:cd=48;5;232;38;5;3:or=48;5;232;38;5;9:mi=05;48;5;232;38;5;15:su=48;5;196;38;5;15:sg=48;5;11;38;5;16:ca=48;5;196;38;5;226:tw=48;5;10;38;5;16:ow=48;5;10;38;5;21:st=48;5;21;38;5;15:ex=38;5;34:*.tar=38;5;9:*.tgz=38;5;9:*.arc=38;5;9:*.arj=38;5;9:*.taz=38;5;9:*.lha=38;5;9:*.lz4=38;5;9:*.lzh=38;5;9:*.lzma=38;5;9:*.tlz=38;5;9:*.txz=38;5;9:*.tzo=38;5;9:*.t7z=38;5;9:*.zip=38;5;9:*.z=38;5;9:*.Z=38;5;9:*.dz=38;5;9:*.gz=38;5;9:*.lrz=38;5;9:*.lz=38;5;9:*.lzo=38;5;9:*.xz=38;5;9:*.bz2=38;5;9:*.bz=38;5;9:*.tbz=38;5;9:*.tbz2=38;5;9:*.tz=38;5;9:*.deb=38;5;9:*.rpm=38;5;9:*.jar=38;5;9:*.war=38;5;9:*.ear=38;5;9:*.sar=38;5;9:*.rar=38;5;9:*.alz=38;5;9:*.ace=38;5;9:*.zoo=38;5;9:*.cpio=38;5;9:*.7z=38;5;9:*.rz=38;5;9:*.cab=38;5;9:*.jpg=38;5;13:*.jpeg=38;5;13:*.gif=38;5;13:*.bmp=38;5;13:*.pbm=38;5;13:*.pgm=38;5;13:*.ppm=38;5;13:*.tga=38;5;13:*.xbm=38;5;13:*.xpm=38;5;13:*.tif=38;5;13:*.tiff=38;5;13:*.png=38;5;13:*.svg=38;5;13:*.svgz=38;5;13:*.mng=38;5;13:*.pcx=38;5;13:*.mov=38;5;13:*.mpg=38;5;13:*.mpeg=38;5;13:*.m2v=38;5;13:*.mkv=38;5;13:*.webm=38;5;13:*.ogm=38;5;13:*.mp4=38;5;13:*.m4v=38;5;13:*.mp4v=38;5;13:*.vob=38;5;13:*.qt=38;5;13:*.nuv=38;5;13:*.wmv=38;5;13:*.asf=38;5;13:*.rm=38;5;13:*.rmvb=38;5;13:*.flc=38;5;13:*.avi=38;5;13:*.fli=38;5;13:*.flv=38;5;13:*.gl=38;5;13:*.dl=38;5;13:*.xcf=38;5;13:*.xwd=38;5;13:*.yuv=38;5;13:*.cgm=38;5;13:*.emf=38;5;13:*.axv=38;5;13:*.anx=38;5;13:*.ogv=38;5;13:*.ogx=38;5;13:*.aac=38;5;45:*.au=38;5;45:*.flac=38;5;45:*.mid=38;5;45:*.midi=38;5;45:*.mka=38;5;45:*.mp3=38;5;45:*.mpc=38;5;45:*.ogg=38;5;45:*.ra=38;5;45:*.wav=38;5;45:*.axa=38;5;45:*.oga=38;5;45:*.spx=38;5;45:*.xspf=38;5;45:",
            "MAIL": "/var/mail/root",
            "PATH": "/sbin:/bin:/usr/sbin:/usr/bin",
            "PWD": "/root",
            "SHELL": "/bin/bash",
            "SHLVL": "1",
            "SUDO_COMMAND": "/bin/sh -c echo BECOME-SUCCESS-byprxblftkrylymslnyukgunylbcmtwu ; /usr/bin/python ./tmp/ansible-tmp-1715586178.6455448-22538-175088753379732/AnsiballZ_setup.py",
            "SUDO_GID": "0",
            "SUDO_UID": "0",
            "SUDO_USER": "root",
            "TERM": "xterm-256color",
            "USER": "root",
            "USERNAME": "root",
            "XDG_RUNTIME_DIR": "/run/user/0",
            "XDG_SESSION_ID": "320",
            "_": "/usr/bin/python"
        },
        "eth0": {
            "active": true,
            "device": "eth0",
            "features": {
                "busy_poll": "off [fixed]",
                "fcoe_mtu": "off [fixed]",
                "generic_receive_offload": "on",
                "generic_segmentation_offload": "on",
                "highdma": "on [fixed]",
                "hw_tc_offload": "off [fixed]",
                "l2_fwd_offload": "off [fixed]",
                "large_receive_offload": "off [fixed]",
                "loopback": "off [fixed]",
                "netns_local": "off [fixed]",
                "ntuple_filters": "off [fixed]",
                "receive_hashing": "off [fixed]",
                "rx_all": "off [fixed]",
                "rx_checksumming": "on [fixed]",
                "rx_fcs": "off [fixed]",
                "rx_gro_hw": "off [fixed]",
                "rx_udp_tunnel_port_offload": "off [fixed]",
                "rx_vlan_filter": "on [fixed]",
                "rx_vlan_offload": "off [fixed]",
                "rx_vlan_stag_filter": "off [fixed]",
                "rx_vlan_stag_hw_parse": "off [fixed]",
                "scatter_gather": "on",
                "tcp_segmentation_offload": "on",
                "tx_checksum_fcoe_crc": "off [fixed]",
                "tx_checksum_ip_generic": "on",
                "tx_checksum_ipv4": "off [fixed]",
                "tx_checksum_ipv6": "off [fixed]",
                "tx_checksum_sctp": "off [fixed]",
                "tx_checksumming": "on",
                "tx_fcoe_segmentation": "off [fixed]",
                "tx_gre_csum_segmentation": "off [fixed]",
                "tx_gre_segmentation": "off [fixed]",
                "tx_gso_partial": "off [fixed]",
                "tx_gso_robust": "off [fixed]",
                "tx_ipip_segmentation": "off [fixed]",
                "tx_lockless": "off [fixed]",
                "tx_nocache_copy": "off",
                "tx_scatter_gather": "on",
                "tx_scatter_gather_fraglist": "off [fixed]",
                "tx_sctp_segmentation": "off [fixed]",
                "tx_sit_segmentation": "off [fixed]",
                "tx_tcp6_segmentation": "on",
                "tx_tcp_ecn_segmentation": "on",
                "tx_tcp_mangleid_segmentation": "off",
                "tx_tcp_segmentation": "on",
                "tx_udp_tnl_csum_segmentation": "off [fixed]",
                "tx_udp_tnl_segmentation": "off [fixed]",
                "tx_vlan_offload": "off [fixed]",
                "tx_vlan_stag_hw_insert": "off [fixed]",
                "udp_fragmentation_offload": "on",
                "vlan_challenged": "off [fixed]"
            },
            "hw_timestamp_filters": [],
            "ipv4": {
                "address": "192.168.2.21",
                "broadcast": "192.168.2.255",
                "netmask": "255.255.255.0",
                "network": "192.168.2.0",
                "prefix": "24"
            },
            "ipv6": [
                {
                    "address": "fe80::b89b:af90:6d04:5fa2",
                    "prefix": "64",
                    "scope": "link"
                }
            ],
            "macaddress": "1a:80:cc:42:98:2b",
            "module": "virtio_net",
            "mtu": 1500,
            "pciid": "virtio1",
            "promisc": false,
            "timestamping": [
                "rx_software",
                "software"
            ],
            "type": "ether"
        },
        "fibre_channel_wwn": [],
        "fips": false,
        "form_factor": "Other",
        "fqdn": "128-node1",
        "gather_subset": [
            "all"
        ],
        "hostname": "128-node1",
        "hostnqn": "",
        "interfaces": [
            "docker0",
            "kube-ipvs0",
            "lo",
            "tunl0",
            "calia8f9eba266e",
            "calibab978770c0",
            "dummy0",
            "eth0"
        ],
        "is_chroot": false,
        "iscsi_iqn": "",
        "kernel": "3.10.0-1160.el7.x86_64",
        "kernel_version": "#1 SMP Mon Oct 19 16:18:59 UTC 2020",
        "kube_ipvs0": {
            "active": false,
            "device": "kube-ipvs0",
            "features": {
                "busy_poll": "off [fixed]",
                "fcoe_mtu": "off [fixed]",
                "generic_receive_offload": "on",
                "generic_segmentation_offload": "on",
                "highdma": "on [fixed]",
                "hw_tc_offload": "off [fixed]",
                "l2_fwd_offload": "off [fixed]",
                "large_receive_offload": "off [fixed]",
                "loopback": "off [fixed]",
                "netns_local": "off [fixed]",
                "ntuple_filters": "off [fixed]",
                "receive_hashing": "off [fixed]",
                "rx_all": "off [fixed]",
                "rx_checksumming": "off [fixed]",
                "rx_fcs": "off [fixed]",
                "rx_gro_hw": "off [fixed]",
                "rx_udp_tunnel_port_offload": "off [fixed]",
                "rx_vlan_filter": "off [fixed]",
                "rx_vlan_offload": "off [fixed]",
                "rx_vlan_stag_filter": "off [fixed]",
                "rx_vlan_stag_hw_parse": "off [fixed]",
                "scatter_gather": "on",
                "tcp_segmentation_offload": "on",
                "tx_checksum_fcoe_crc": "off [fixed]",
                "tx_checksum_ip_generic": "on [fixed]",
                "tx_checksum_ipv4": "off [fixed]",
                "tx_checksum_ipv6": "off [fixed]",
                "tx_checksum_sctp": "off [fixed]",
                "tx_checksumming": "on",
                "tx_fcoe_segmentation": "off [fixed]",
                "tx_gre_csum_segmentation": "off [fixed]",
                "tx_gre_segmentation": "off [fixed]",
                "tx_gso_partial": "off [fixed]",
                "tx_gso_robust": "off [fixed]",
                "tx_ipip_segmentation": "off [fixed]",
                "tx_lockless": "on [fixed]",
                "tx_nocache_copy": "off",
                "tx_scatter_gather": "on [fixed]",
                "tx_scatter_gather_fraglist": "on [fixed]",
                "tx_sctp_segmentation": "off [fixed]",
                "tx_sit_segmentation": "off [fixed]",
                "tx_tcp6_segmentation": "off [fixed]",
                "tx_tcp_ecn_segmentation": "off [fixed]",
                "tx_tcp_mangleid_segmentation": "off [fixed]",
                "tx_tcp_segmentation": "on [fixed]",
                "tx_udp_tnl_csum_segmentation": "off [fixed]",
                "tx_udp_tnl_segmentation": "off [fixed]",
                "tx_vlan_offload": "off [fixed]",
                "tx_vlan_stag_hw_insert": "off [fixed]",
                "udp_fragmentation_offload": "off [fixed]",
                "vlan_challenged": "off [fixed]"
            },
            "hw_timestamp_filters": [],
            "ipv4": {
                "address": "10.111.99.96",
                "broadcast": "",
                "netmask": "255.255.255.255",
                "network": "10.111.99.96",
                "prefix": "32"
            },
            "ipv4_secondaries": [
                {
                    "address": "10.96.218.13",
                    "broadcast": "",
                    "netmask": "255.255.255.255",
                    "network": "10.96.218.13",
                    "prefix": "32"
                },
                {
                    "address": "10.96.0.10",
                    "broadcast": "",
                    "netmask": "255.255.255.255",
                    "network": "10.96.0.10",
                    "prefix": "32"
                },
                {
                    "address": "10.96.0.1",
                    "broadcast": "",
                    "netmask": "255.255.255.255",
                    "network": "10.96.0.1",
                    "prefix": "32"
                }
            ],
            "macaddress": "12:c3:24:67:38:cb",
            "mtu": 1500,
            "promisc": false,
            "timestamping": [
                "rx_software",
                "software"
            ],
            "type": "ether"
        },
        "lo": {
            "active": true,
            "device": "lo",
            "features": {
                "busy_poll": "off [fixed]",
                "fcoe_mtu": "off [fixed]",
                "generic_receive_offload": "on",
                "generic_segmentation_offload": "on",
                "highdma": "on [fixed]",
                "hw_tc_offload": "off [fixed]",
                "l2_fwd_offload": "off [fixed]",
                "large_receive_offload": "off [fixed]",
                "loopback": "on [fixed]",
                "netns_local": "on [fixed]",
                "ntuple_filters": "off [fixed]",
                "receive_hashing": "off [fixed]",
                "rx_all": "off [fixed]",
                "rx_checksumming": "on [fixed]",
                "rx_fcs": "off [fixed]",
                "rx_gro_hw": "off [fixed]",
                "rx_udp_tunnel_port_offload": "off [fixed]",
                "rx_vlan_filter": "off [fixed]",
                "rx_vlan_offload": "off [fixed]",
                "rx_vlan_stag_filter": "off [fixed]",
                "rx_vlan_stag_hw_parse": "off [fixed]",
                "scatter_gather": "on",
                "tcp_segmentation_offload": "on",
                "tx_checksum_fcoe_crc": "off [fixed]",
                "tx_checksum_ip_generic": "on [fixed]",
                "tx_checksum_ipv4": "off [fixed]",
                "tx_checksum_ipv6": "off [fixed]",
                "tx_checksum_sctp": "on [fixed]",
                "tx_checksumming": "on",
                "tx_fcoe_segmentation": "off [fixed]",
                "tx_gre_csum_segmentation": "off [fixed]",
                "tx_gre_segmentation": "off [fixed]",
                "tx_gso_partial": "off [fixed]",
                "tx_gso_robust": "off [fixed]",
                "tx_ipip_segmentation": "off [fixed]",
                "tx_lockless": "on [fixed]",
                "tx_nocache_copy": "off [fixed]",
                "tx_scatter_gather": "on [fixed]",
                "tx_scatter_gather_fraglist": "on [fixed]",
                "tx_sctp_segmentation": "on",
                "tx_sit_segmentation": "off [fixed]",
                "tx_tcp6_segmentation": "on",
                "tx_tcp_ecn_segmentation": "on",
                "tx_tcp_mangleid_segmentation": "on",
                "tx_tcp_segmentation": "on",
                "tx_udp_tnl_csum_segmentation": "off [fixed]",
                "tx_udp_tnl_segmentation": "off [fixed]",
                "tx_vlan_offload": "off [fixed]",
                "tx_vlan_stag_hw_insert": "off [fixed]",
                "udp_fragmentation_offload": "on",
                "vlan_challenged": "on [fixed]"
            },
            "hw_timestamp_filters": [],
            "ipv4": {
                "address": "127.0.0.1",
                "broadcast": "",
                "netmask": "255.0.0.0",
                "network": "127.0.0.0",
                "prefix": "8"
            },
            "ipv6": [
                {
                    "address": "::1",
                    "prefix": "128",
                    "scope": "host"
                }
            ],
            "mtu": 65536,
            "promisc": false,
            "timestamping": [
                "rx_software",
                "software"
            ],
            "type": "loopback"
        },
        "loadavg": {
            "15m": 0.05,
            "1m": 0.04,
            "5m": 0.04
        },
        "locally_reachable_ips": {
            "ipv4": [
                "10.96.0.1",
                "10.96.0.10",
                "10.96.218.13",
                "10.111.99.96",
                "10.250.40.128",
                "127.0.0.0/8",
                "127.0.0.1",
                "172.17.0.1",
                "192.168.2.21"
            ],
            "ipv6": [
                "::1",
                "fe80::b89b:af90:6d04:5fa2",
                "fe80::ecee:eeff:feee:eeee"
            ]
        },
        "lsb": {},
        "lvm": {
            "lvs": {
                "root": {
                    "size_g": "190.00",
                    "vg": "centos"
                },
                "swap": {
                    "size_g": "8.00",
                    "vg": "centos"
                }
            },
            "pvs": {
                "/dev/sda2": {
                    "free_g": "0",
                    "size_g": "198.00",
                    "vg": "centos"
                }
            },
            "vgs": {
                "centos": {
                    "free_g": "0",
                    "num_lvs": "2",
                    "num_pvs": "1",
                    "size_g": "198.00"
                }
            }
        },
        "machine": "x86_64",
        "machine_id": "22e414902fb540f38026892f8782c086",
        "memfree_mb": 11658,
        "memory_mb": {
            "nocache": {
                "free": 14759,
                "used": 1286
            },
            "real": {
                "free": 11658,
                "total": 16045,
                "used": 4387
            },
            "swap": {
                "cached": 0,
                "free": 0,
                "total": 0,
                "used": 0
            }
        },
        "memtotal_mb": 16045,
        "module_setup": true,
        "mounts": [
            {
                "block_available": 486588,
                "block_size": 4096,
                "block_total": 521728,
                "block_used": 35140,
                "device": "/dev/sda1",
                "fstype": "xfs",
                "inode_available": 1048250,
                "inode_total": 1048576,
                "inode_used": 326,
                "mount": "/boot",
                "options": "rw,seclabel,relatime,attr2,inode64,noquota",
                "size_available": 1993064448,
                "size_total": 2136997888,
                "uuid": "6e152b2b-0ae0-4eec-b55d-65f24544553d"
            },
            {
                "block_available": 0,
                "block_size": 4096,
                "block_total": 0,
                "block_used": 0,
                "device": "/sys/fs/bpf",
                "fstype": "bpf",
                "inode_available": 0,
                "inode_total": 0,
                "inode_used": 0,
                "mount": "/sys/fs/bpf",
                "options": "rw,relatime",
                "size_available": 0,
                "size_total": 0,
                "uuid": "N/A"
            },
            {
                "block_available": 48415969,
                "block_size": 4096,
                "block_total": 49782017,
                "block_used": 1366048,
                "device": "/dev/mapper/centos-root",
                "fstype": "xfs",
                "inode_available": 99470663,
                "inode_total": 99612672,
                "inode_used": 142009,
                "mount": "/",
                "options": "rw,seclabel,relatime,attr2,inode64,noquota",
                "size_available": 198311809024,
                "size_total": 203907141632,
                "uuid": "e9f954fc-b8a1-428b-8b50-15563c638099"
            }
        ],
        "nodename": "128-node1",
        "os_family": "RedHat",
        "pkg_mgr": "yum",
        "proc_cmdline": {
            "BOOT_IMAGE": "/vmlinuz-3.10.0-1160.el7.x86_64",
            "LANG": "en_US.UTF-8",
            "quiet": true,
            "rd.lvm.lv": [
                "centos/root",
                "centos/swap"
            ],
            "rhgb": true,
            "ro": true,
            "root": "/dev/mapper/centos-root"
        },
        "processor": [
            "0",
            "GenuineIntel",
            "Common KVM processor",
            "1",
            "GenuineIntel",
            "Common KVM processor",
            "2",
            "GenuineIntel",
            "Common KVM processor",
            "3",
            "GenuineIntel",
            "Common KVM processor",
            "4",
            "GenuineIntel",
            "Common KVM processor",
            "5",
            "GenuineIntel",
            "Common KVM processor",
            "6",
            "GenuineIntel",
            "Common KVM processor",
            "7",
            "GenuineIntel",
            "Common KVM processor"
        ],
        "processor_cores": 4,
        "processor_count": 2,
        "processor_nproc": 8,
        "processor_threads_per_core": 1,
        "processor_vcpus": 8,
        "product_name": "Standard PC (i440FX + PIIX, 1996)",
        "product_serial": "NA",
        "product_uuid": "023EA3A8-FA69-44D6-A869-3E3774BC048E",
        "product_version": "pc-i440fx-7.2",
        "python": {
            "executable": "/usr/bin/python",
            "has_sslcontext": true,
            "type": "CPython",
            "version": {
                "major": 2,
                "micro": 5,
                "minor": 7,
                "releaselevel": "final",
                "serial": 0
            },
            "version_info": [
                2,
                7,
                5,
                "final",
                0
            ]
        },
        "python_version": "2.7.5",
        "real_group_id": 0,
        "real_user_id": 0,
        "selinux": {
            "config_mode": "unknown",
            "mode": "permissive",
            "policyvers": 31,
            "status": "enabled",
            "type": "targeted"
        },
        "selinux_python_present": true,
        "service_mgr": "systemd",
        "ssh_host_key_ecdsa_public": "AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBDJRxWeJ/lgl8oY39BqaDUOBZKQEXaveUbx/wXBI3gAqmSzyV8hZi82tYhVzRmaOHTtqI8A3FVgI43X/RA34k5g=",
        "ssh_host_key_ecdsa_public_keytype": "ecdsa-sha2-nistp256",
        "ssh_host_key_ed25519_public": "AAAAC3NzaC1lZDI1NTE5AAAAIDqmOOTL8GS6vFodS1G84QN6WQjHGEmGs16ahiEEf/7h",
        "ssh_host_key_ed25519_public_keytype": "ssh-ed25519",
        "ssh_host_key_rsa_public": "AAAAB3NzaC1yc2EAAAADAQABAAABAQCz32Cgb3bH4T58nodP4InYggG9etIIfbUscu6o4Mb42AIY8OwxHl9Db7wddalnt7XawpUpTlboVQtng6TR6sxrxpZxJHZC+tOHttTTlXoOAdExibGMku4czmWxnaGNPdb/p6s60OhamQ4xDz+Dv9H5vGi7LSgfH1fLOYO1C+htNgJLYI3sMRDTLkE0MZdwTmw1Rqm/inNbFIpjlOzwzSFQ8A5fLOu5mMaM/UPwUdNBFqTLo5uE13saEri0ad1iVDm/BduPA5FqqCYhXr17eZuOsuHTtenhajPbPob9ywsxqZtnrRCWExBgO+G67OQQNU91n6r6RwzbxnpVBsVyY+Oh",
        "ssh_host_key_rsa_public_keytype": "ssh-rsa",
        "swapfree_mb": 0,
        "swaptotal_mb": 0,
        "system": "Linux",
        "system_capabilities": [
            "cap_chown",
            "cap_dac_override",
            "cap_dac_read_search",
            "cap_fowner",
            "cap_fsetid",
            "cap_kill",
            "cap_setgid",
            "cap_setuid",
            "cap_setpcap",
            "cap_linux_immutable",
            "cap_net_bind_service",
            "cap_net_broadcast",
            "cap_net_admin",
            "cap_net_raw",
            "cap_ipc_lock",
            "cap_ipc_owner",
            "cap_sys_module",
            "cap_sys_rawio",
            "cap_sys_chroot",
            "cap_sys_ptrace",
            "cap_sys_pacct",
            "cap_sys_admin",
            "cap_sys_boot",
            "cap_sys_nice",
            "cap_sys_resource",
            "cap_sys_time",
            "cap_sys_tty_config",
            "cap_mknod",
            "cap_lease",
            "cap_audit_write",
            "cap_audit_control",
            "cap_setfcap",
            "cap_mac_override",
            "cap_mac_admin",
            "cap_syslog",
            "35",
            "36+ep"
        ],
        "system_capabilities_enforced": "True",
        "system_vendor": "QEMU",
        "tunl0": {
            "active": true,
            "device": "tunl0",
            "features": {
                "busy_poll": "off [fixed]",
                "fcoe_mtu": "off [fixed]",
                "generic_receive_offload": "on",
                "generic_segmentation_offload": "on",
                "highdma": "on",
                "hw_tc_offload": "off [fixed]",
                "l2_fwd_offload": "off [fixed]",
                "large_receive_offload": "off [fixed]",
                "loopback": "off [fixed]",
                "netns_local": "on [fixed]",
                "ntuple_filters": "off [fixed]",
                "receive_hashing": "off [fixed]",
                "rx_all": "off [fixed]",
                "rx_checksumming": "off [fixed]",
                "rx_fcs": "off [fixed]",
                "rx_gro_hw": "off [fixed]",
                "rx_udp_tunnel_port_offload": "off [fixed]",
                "rx_vlan_filter": "off [fixed]",
                "rx_vlan_offload": "off [fixed]",
                "rx_vlan_stag_filter": "off [fixed]",
                "rx_vlan_stag_hw_parse": "off [fixed]",
                "scatter_gather": "on",
                "tcp_segmentation_offload": "on",
                "tx_checksum_fcoe_crc": "off [fixed]",
                "tx_checksum_ip_generic": "on",
                "tx_checksum_ipv4": "off [fixed]",
                "tx_checksum_ipv6": "off [fixed]",
                "tx_checksum_sctp": "off [fixed]",
                "tx_checksumming": "on",
                "tx_fcoe_segmentation": "off [fixed]",
                "tx_gre_csum_segmentation": "off [fixed]",
                "tx_gre_segmentation": "off [fixed]",
                "tx_gso_partial": "off [fixed]",
                "tx_gso_robust": "off [fixed]",
                "tx_ipip_segmentation": "off [fixed]",
                "tx_lockless": "on [fixed]",
                "tx_nocache_copy": "off",
                "tx_scatter_gather": "on",
                "tx_scatter_gather_fraglist": "on",
                "tx_sctp_segmentation": "on",
                "tx_sit_segmentation": "off [fixed]",
                "tx_tcp6_segmentation": "on",
                "tx_tcp_ecn_segmentation": "on",
                "tx_tcp_mangleid_segmentation": "on",
                "tx_tcp_segmentation": "on",
                "tx_udp_tnl_csum_segmentation": "off [fixed]",
                "tx_udp_tnl_segmentation": "off [fixed]",
                "tx_vlan_offload": "off [fixed]",
                "tx_vlan_stag_hw_insert": "off [fixed]",
                "udp_fragmentation_offload": "on",
                "vlan_challenged": "off [fixed]"
            },
            "hw_timestamp_filters": [],
            "ipv4": {
                "address": "10.250.40.128",
                "broadcast": "",
                "netmask": "255.255.255.255",
                "network": "10.250.40.128",
                "prefix": "32"
            },
            "macaddress": "00:00:00:00",
            "mtu": 1480,
            "promisc": false,
            "timestamping": [
                "rx_software",
                "software"
            ],
            "type": "unknown"
        },
        "uptime_seconds": 19121,
        "user_dir": "/root",
        "user_gecos": "root",
        "user_gid": 0,
        "user_id": "root",
        "user_shell": "/bin/bash",
        "user_uid": 0,
        "userspace_architecture": "x86_64",
        "userspace_bits": "64",
        "virtualization_role": "guest",
        "virtualization_tech_guest": [
            "kvm"
        ],
        "virtualization_tech_host": [
            "kvm"
        ],
        "virtualization_type": "kvm"
    }
}

2、register变量

# 测试yaml如下:
---
- name: test
  hosts: test
  gather_facts: no
  tasks:
    - name: test
      shell: whoami
      register: init_status
    - name: debug
      debug:
        msg: "{{init_status}}"

debug返回信息如下:

ok: [192.168.2.20] => {
    "msg": {
        "ansible_facts": {
            "discovered_interpreter_python": "/usr/bin/python"
        },
        "changed": true,
        "cmd": "whoami",
        "delta": "0:00:00.007385",
        "end": "2024-05-13 12:01:24.173776",
        "failed": false,
        "msg": "",
        "rc": 0,
        "start": "2024-05-13 12:01:24.166391",
        "stderr": "",
        "stderr_lines": [],
        "stdout": "root",
        "stdout_lines": [
            "root"
        ]
    }
}

0

评论区