目录

  • 1.var变量
  • 1.1 playbook中的变量
  • 1.1.1 直接定义在playbook里
  • 1.1.2 在playbook中通过外部文件定义
  • 1.1.3 数组定义变量
  • 1.2 inventory清单文件中的变量
  • 1.2.1 主机变量和组变量
  • 1.2.2 使用目录定义清单变量
  • 1.3 命令行上设置变量
  • 1.4 register
  • 2. ansible vault机密
  • 2.1 创建(create)机密文件
  • 2.2 查看(view)机密文件
  • 2.3 编辑(edit)机密文件
  • 2.4 解密(decrypt)机密文件
  • 2.5 加密(encrypt)机密文件
  • 2.6 更改(rekey)机密文件
  • 3. facts事实
  • 3.1 收集并查看事实
  • 3.2 ansible_facts作为变量注入
  • 3.2.1 新旧版本ansible_facts命名系统
  • 3.3 关闭事实收集
  • 3.4 创建自定义事实(local facts)
  • 3.4.1 静态文件定义local facts
  • 3.4.2 local facts使用
  • 3.5 魔法变量
  • 3.5.1 常用魔法变量

1.var变量

  • 变量的名称必须以字母开头,且只能包含字母、数字、下划线
  • 变量优先级:当前目录下命令行(-e)指定的变量 > playbook剧本里指定的变量 > inventory清单文件指定的变量
  • Ansible支持变量存储值,并可以在Ansible项目的所有文件中重复使用这些值,便于轻松管理

1.1 playbook中的变量

1.1.1 直接定义在playbook里

  • 当变量用于开始一个值的第一个元素时要用""引号
[root@vm2 apache]# vim http.yml 

---
- hosts: webservers
  vars:                         ##变量定义
    ware_name: httpd
  tasks:
    - name: install httpd
      dnf:
        name: "{{ware_name}}"   ##变量使用{{}}
        state: present
...

1.1.2 在playbook中通过外部文件定义

  • 外部文件为yaml格式,内容为变量及值
[root@vm2 apache]# vim http.yml 

---
- hosts: webservers
  vars_files:                   #引用外部文件
    - vars/play.yml                                              
  tasks:
    - name: install httpd
      dnf:
        name: "{{ware_name}}"
        state: present

[root@vm2 apache]# tree ..
..
└── apache
    ├── group_vars
    │   └── webservers.yml
    ├── host_vars
    │   ├── vm1.yml
    │   ├── vm3.yml
    │   └── vm4.yml
    ├── http.yml
    ├── inventory
    └── vars
        └── play.yml    #引用的外部文件变量路径

[root@vm2 apache]# cat vars/play.yml 
ware_name: httpd
...

1.1.3 数组定义变量

[root@vm2 apache]# tree ..
..
└── apache
    ├── 1
    ├── group_vars
    │   └── webservers.yml
    ├── host_vars
    │   ├── vm1.yml
    │   ├── vm3.yml
    │   └── vm4.yml
    ├── http.yml
    ├── inventory
    └── vars
        ├── http.yml
        └── play.yml

[root@vm2 apache]# vim vars/http.yml    ##以数组形式定义变量

users:
  vm1:
    ware_name: httpd
    version: 8.0
- hosts: webservers
  vars_files:        
    - vars/http.yml     ##外部文件
##vars:                 ##或者直接定义在playbook里(优先级高于外部文件)
##  users:
##    vm1:
##      ware_name: httpd
##      version: 7.0
  tasks:
    - name: debug
      debug:
        ## 以.的形式访问数组值
        msg="vm1 install {{users.vm1.ware_name}} version {{users.vm1.version}}"  
        ## 以python字典的形式访问数组值
        msg="vm1 install {{users['vm1']['ware_name']}} version {{users['vm1']['version']}}"  
...

1.2 inventory清单文件中的变量

1.2.1 主机变量和组变量

  • 主机变量优先于组变量
  • 主机变量和组变量可以直接定义在清单文件中,但不建议这么做
## ansible_password为主机变量
192.168.137.133 ansible_password=123456

## ansible_password为组变量
[webservers]
vm1 ansible_host=192.168.137.128
vm3 ansible_host=192.168.137.133 
vm4 ansible_host=192.168.137.134 
[webservers:vars]
ansible_password=123456

1.2.2 使用目录定义清单变量

  • 在一个项目file的目录中,指定group_vars目录、host_vars目录、inventory文件
  • inventory文件里的组或主机的变量,可以存放在group_vars目录或hosts_vars目录下,文件名为组名或主机名,文件内容为组或者主机的变量(yaml格式)。其效果等同于在inventory文件中添加组或主机的变量
  • 对于一个组,组员相同的变量存放在group_vars里,不同的变量存放在host_vars里
[root@vm2 apache]# tree ..
..
└── apache
    ├── group_vars
    │   └── webservers  #文件名必须与组名一致,文件内容为yaml格式
    ├── host_vars       
    │   ├── vm1         #文件名必须与主机名一致,文件内容为yaml格式
    │   ├── vm2
    │   └── vm3
    ├── http.yml
    └── inventory

[root@vm2 apache]# cat group_vars/webservers 
ansible_password: 123456
[root@vm2 apache]# cat host_vars/vm1
ansible_host: 192.168.137.128
[root@vm2 apache]# cat host_vars/vm2
ansible_host: 192.168.137.133
[root@vm2 apache]# cat host_vars/vm3
ansible_host: 192.168.137.134

[root@vm2 apache]# cat inventory 
[webservers]
vm1 
vm3
vm4

1.3 命令行上设置变量

  • 在命令行中传递参数(- e)到ansible或ansible-playbook命令可以覆盖清单或者剧本中定义的变量值
[root@vm2 apache]# ansible-playbook -C http.yml -e "ware_name=httpd" -i inventory

1.4 register

  • register语句捕获命令输出,保存在一个临时变量中
  • debug模块用于将这个临时变量的值转储到终端
[root@vm2 apache]# vim http.yml 

---
- hosts: webservers
  vars:
    users:
      vm1:
        ware_name: httpd
        version: 7.0
  tasks:
    - name: install http
      dnf:
        name: "{{users.vm1.ware_name}}"
        state: present
      register: result    
    - debug:
        var=result
...

## 运行的部分结果
TASK [debug] *************************************************************************************
ok: [vm1] => {
    "result": {
        "changed": false,
        "failed": false,
        "msg": "Nothing to do",
        "rc": 0,
        "results": []
    }
}

2. ansible vault机密

  • Ansible Vault可以加密和解密任何由Ansible使用的结构化数据文件,包括清单变量、playbook中含有的变量文件、在执行playbook时作为参数传递的变量文件,或者Ansible角色中定义的变量。
  • 可通过ansible-vault命令创建、编辑、加密、解密和查看加密文件

2.1 创建(create)机密文件

  • ansible-vault create filename
  • 通过手动输入加密密码创建
[root@vm2 apache]# ansible-vault create group_vars/webservers/pass
New Vault password: 123456
Confirm New Vault password: 123456
  • 通过加密文件创建
[root@vm2 apache]# ansible-vault create --vault-password-file=vault-pass group_vars/webservers/web-pass

#加密文件,一般修改权限保证文件机密性
[root@vm2 apache]# pwd
/opt/apache
[root@vm2 apache]# ll vault-pass 
-rw-------. 1 root root 7 Sep  2 17:45 vault-pass

2.2 查看(view)机密文件

  • ansible-vault view filename
[root@vm2 apache]# vim group_vars/webservers/web-pass 

$ANSIBLE_VAULT;1.1;AES256
38333861353966333562653339326339353765663963666232633565333539386364343238353165
3661333037663266373130306634313430303637343338370a393834636164373663636135353233
61653962666433336666353434623530333437343139626331653433326631393863623436616130
6430333736396530630a336262383266343966646363313437373839663335336238383662356333
63613065653766363539336137613530616162616633666235393363633737306466

[root@vm2 apache]# ansible-vault view group_vars/webservers/web-pass 
Vault password: 
ansible_password=123456

2.3 编辑(edit)机密文件

  • ansible-vault edit filename
  • 通过vim向加密文件中添加内容,会直接影响这个文件的功能
[root@vm2 apache]# cd group_vars/webservers/
[root@vm2 webservers]# ls
web-pass
[root@vm2 webservers]# ansible-vault edit web-pass 
Vault password: 

ansible_password: 123456

2.4 解密(decrypt)机密文件

  • ansible-vault decrypt filename
[root@vm2 webservers]# vim web-pass 

$ANSIBLE_VAULT;1.1;AES256
32393833626362333863613333343235646530373130626461633832663235643036346537353331
6333613862343866616430653537303231613738396430370a303131346162663038666638636430
32663135313534306562383235653466646661643361303733623133653236353863366165326665
3130343437366633310a313331633138366231393938313630663466616338663866383130376563
31343435633035336562666638636165366635383636336634363939336539633538

[root@vm2 apache]# ansible-vault decrypt group_vars/webservers/web-pass 
Vault password: 
Decryption successful
[root@vm2 apache]# vim group_vars/webservers/web-pass 

ansible_password: 123456

2.5 加密(encrypt)机密文件

  • ansible-vault encrypt filename [--vault-password-file=filename]
[root@vm2 apache]# ansible-vault encrypt group_vars/webservers/web-pass --vault-password-file=vault-pass 
Encryption successful
[root@vm2 apache]# vim group_vars/webservers/web-pass 

$ANSIBLE_VAULT;1.1;AES256
61323664336231646338386237376531333063656166626636366538316634356535613935646666
3033343263383339313938343432336639626239316436300a386563383535303030336664663631
33633037323261633036636633323530643939353134313332336162333337393231353266656237
3362366132623733390a303665333639623366363635326236333831666530323339383430636137
62613232643132393434643966616632633637646235656162656431643666363964

2.6 更改(rekey)机密文件

  • ansible-vault rekey filename [--new-vault-password-file=filename]
[root@vm2 apache]# ansible-vault rekey group_vars/webservers/web-pass 
Vault password: 
New Vault password: 
Confirm New Vault password: 
Rekey successful

3. facts事实

  • ansible facts是ansible在受管主机上自动检测到的变量,包含有与主机相关的信息,可以为playbook中的常规变量、条件、循环或依赖于从受管主机收集来的值的任何其他语句使用。
  • facts包括:主机名称、内核版本、网络接口、IP地址、操作系统 版本、各种环境变量、CPU数量、提供的或可用的内存、可用的磁盘空间
  • 每个playbook在执行第一个任务之前默认自动运行setup模块来收集事实。若要取消收集事实可在playbook开头加入一行“gather_facts: no”
  • playbook以json格式显示ansible_facts变量信息

3.1 收集并查看事实

  • setup模块显示ansible_facts
  • debug模块用于执行时打印相关信息
[root@vm2 apache]# vim facts.yml 

---
- name: gather and print facts
  hosts: vm1
  tasks:
    - debug:
        var: ansible_facts
...
  • 部分内容如下
[root@vm2 apache]# ansible-playbook facts.yml -i inventory --vault-password-file=vault-pass 

PLAY [gather and print facts] ********************************************************************

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

TASK [debug] *************************************************************************************
ok: [vm1] => {
    "ansible_facts": {
        "all_ipv4_addresses": [
            "192.168.137.128"
        ],
        "all_ipv6_addresses": [
            "fe80::c9ad:671a:4675:11f3"
        ],
        "ansible_local": {},
        "apparmor": {
            "status": "disabled"
        },
        "architecture": "x86_64",
        "bios_date": "07/29/2019",
        "bios_version": "6.00",
        "cmdline": {
            "BOOT_IMAGE": "(hd0,msdos1)/vmlinuz-4.18.0-193.el8.x86_64",
            "biosdevname": "0",
            "net.ifnames": "0",
            "quiet": true,
            "rd.lvm.lv": "rhel/swap",
            "resume": "/dev/mapper/rhel-swap",
            "rhgb": true,
            "ro": true,
            "root": "/dev/mapper/rhel-root"
        },
        "date_time": {
            "date": "2020-09-03",
            "day": "03",
            "epoch": "1599142196",
            "hour": "22",
            "iso8601": "2020-09-03T14:09:56Z",
            "iso8601_basic": "20200903T220956723527",
            "iso8601_basic_short": "20200903T220956",
            "iso8601_micro": "2020-09-03T14:09:56.723888Z",
            "minute": "09",
            "month": "09",
            "second": "56",
            "time": "22:09:56",
            "tz": "CST",
            "tz_offset": "+0800",
            "weekday": "Thursday",
            "weekday_number": "4",
            "weeknumber": "35",
            "year": "2020"
        },
        "default_ipv4": {
            "address": "192.168.137.128",
            "alias": "eth0",
            "broadcast": "192.168.137.255",
            "gateway": "192.168.137.2",
            "interface": "eth0",
            "macaddress": "00:0c:29:8b:61:d5",
            "mtu": 1500,
            "netmask": "255.255.255.0",
            "network": "192.168.137.0",
            "type": "ether"
        },
        "default_ipv6": {},
        "device_links": {
            "ids": {
                "dm-0": [
                    "dm-name-rhel-root",
                    "dm-uuid-LVM-jnFAiCFZ1bCbFb9FtPuwHvlAi9cc83JM6x2ufNWZ6EdjuldsfPz7YD3qfKIB3YBU"
                ],
                "dm-1": [
                    "dm-name-rhel-swap",
                    "dm-uuid-LVM-jnFAiCFZ1bCbFb9FtPuwHvlAi9cc83JMRO66St69FTB0Z9tUDc6Kg9IwNi0J4vOc"
                ],
                "nvme0n1": [
                    "nvme-VMware_Virtual_NVMe_Disk_VMWare_NVME_0000",
                    "nvme-nvme.15ad-564d57617265204e564d455f30303030-564d77617265205669727475616c204e564d65204469736b-00000001"
                ],
                "nvme0n1p1": [
                    "nvme-VMware_Virtual_NVMe_Disk_VMWare_NVME_0000-part1",
                    "nvme-nvme.15ad-564d57617265204e564d455f30303030-564d77617265205669727475616c204e564d65204469736b-00000001-part1",
                    "wwn-nvme.15ad-564d57617265204e564d455f30303030-564d77617265205669727475616c204e564d65204469736b-00000001-part1"
                ],
                "nvme0n1p2": [
                    "lvm-pv-uuid-A9mB7j-6yYY-7HUA-VNIO-j8us-9rf5-CRP0xI",
                    "nvme-VMware_Virtual_NVMe_Disk_VMWare_NVME_0000-part2",
                    "nvme-nvme.15ad-564d57617265204e564d455f30303030-564d77617265205669727475616c204e564d65204469736b-00000001-part2",
                    "wwn-nvme.15ad-564d57617265204e564d455f30303030-564d77617265205669727475616c204e564d65204469736b-00000001-part2"
                ],
                "sr0": [
                    "ata-VMware_Virtual_SATA_CDRW_Drive_00000000000000000001"
                ]
            },
            "labels": {
                "sr0": [
                    "RHEL-8-2-0-BaseOS-x86_64"
                ]
            },
..................................

3.2 ansible_facts作为变量注入

  • 如果变量的值为散列/字典类型,则可使用两种语法来获取其值。
  • 比如:ansible_facts['default_ipv4']['address'],推荐该类型
  • 或者:ansible_facts.default_ipv4.address
  • playbook中,{{}}用于替换变量的值

3.2.1 新旧版本ansible_facts命名系统

  • 在ansible2.5之前,事实以ansible_为前缀的单个变量注入,而不是作为ansible_facts变量的一部分注入。
  • 例如:ansible_hostname,在新版本中为ansible_facts['hostname']
  • 目前ansible可兼容两种模式,也可修改ansible配置文件中[default]下inject_facts_as_vars参数值为false,从而关闭旧命名系统
  • 新版本注入事实变量
[root@vm2 apache]# vim facts.yml 

---
- name: gather and print facts
  hosts: vm1
  tasks:
    - name: print some of ansible_facts
      debug:
        msg: "the ipv4 address of {{ansible_facts['hostname']}} is {{ansible_facts['default_ipv4']['address']}}"
...

## 执行效果
[root@vm2 apache]# ansible-playbook facts.yml -i inventory 

TASK [print some of ansible_facts] ***************************************************************
ok: [vm1] => {
    "msg": "the ipv4 address of vm1 is 192.168.137.128"
}
  • 旧版本注入事实变量
[root@vm2 apache]# vim facts.yml 

---
- name: gather and print facts
  hosts: vm1
  tasks:
    - name: print some of ansible_facts
      debug:
        msg: "the ipv4 address of {{ansible_hostname}} is {{ansible_default_ipv4['address']}}"
...

## 执行效果
[root@vm2 apache]# ansible-playbook facts.yml -i inventory 

TASK [print some of ansible_facts] ***************************************************************
ok: [vm1] => {
    "msg": "the ipv4 address of vm1 is 192.168.137.128"
}
  • 关闭旧版本后,注入变量
[root@vm2 apache]# vim /etc/ansible/ansible.cfg 
[defaults]
inventory = /etc/ansible/inventory
 inject_facts_as_vars = False     ## 默认为true,表示兼容旧版本

##执行效果
[root@vm2 apache]# ansible-playbook facts.yml -i inventory 

TASK [print some of ansible_facts] ***************************************************************
fatal: [vm1]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: 'ansible_hostname' is undefined\n\nThe error appears to be in '/opt/apache/facts.yml': line 5, 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: print some of ansible_facts\n      ^ here\n"}

3.3 关闭事实收集

  • gather_facts: no 关闭事实收集
  • 关闭事实收集的效果:
  1. 加快playbook运行速度
  2. 减小playbook在受管主机上造成的负载
  3. 关闭后,可以在playbook有需要收集事实的任务中使用setup模块手动收集事实
## 注意setup模块需要在任务之前开启使用,与子任务平级
[root@vm2 apache]# vim facts.yml 

---
- name: gather and print facts
  hosts: vm1
  gather_facts: no
  tasks:
    - command: echo "hello world !"
    - setup:
    - name: print some of ansible_facts
      debug:
        msg: "the ipv4 address of {{ansible_hostname}} is {{ansible_default_ipv4['address']}}"
...

3.4 创建自定义事实(local facts)

  • 除了系统捕获的事实外,还可以自定义事实,并且可以整合到setup模运行收集的事实列表ansible_facts['ansible_local']中
  • local facts可以在静态文件中定义,其格式为ini或者json。也可以动态定义
  • 默认情况下,setup模块从受管主机/etc/ansible/facts.d目录下的.fact结尾的文件加载local facts

3.4.1 静态文件定义local facts

  • ini格式(键值对)
[root@vm2 apache]# vim file/mylocal.fact 

[users]
user1=xp
user2=fyj

[general]
asdf=1
XYZ=2
  • json格式(可以存储在静态文本文件中,或者通过可执行脚本输出到标准输出)
[root@vm2 apache]# vim file/mylocal.fact 

{
   "general": {
    "XYZ": "1",
    "asdf": "2"
     }, 
          
   "users": {  
     "user1": "fyj", 
     "user2": "xp"  
     }  
}

3.4.2 local facts使用

  • 在受管主机上创建/etc/ansible/facts.d目录,并在其目录中存储mylocal.fact文件
[root@vm2 apache]# vim local_facts.yml 

---
- hosts: webservers
  gather_facts: no
  tasks:
    - name: create directory for ansible custom facts
      file:
        state: directory
        recurse: yes
        path: /etc/ansible/facts.d
    - name: install mylocal.fact
      copy:
        src: file/mylocal.fact
        dest: /etc/ansible/facts.d
    - name: re-read facts after adding mylocal.fact
      setup:
        filter: ansible_local
    - debug:
        msg: "{{ansible_facts['ansible_local']['mylocal']['users']['user1']}} and {{ansible_facts['ansible_local']['mylocal']['general']['XYZ']}}"
...


## 查看执行效果
[root@vm2 apache]# ansible-playbook local_facts.yml --syntax-check -i inventory 

playbook: local_facts.yml
[root@vm2 apache]# ansible-playbook local_facts.yml -i inventory --vault-password-file=vault-pass  
PLAY [webservers] ********************************************************************************

TASK [create directory for ansible custom facts] *************************************************
ok: [vm4]
ok: [vm1]
ok: [vm3]

TASK [install mylocal.fact] **********************************************************************
ok: [vm4]
ok: [vm1]
ok: [vm3]

TASK [re-read facts after adding mylocal.fact] ***************************************************
ok: [vm3]
ok: [vm1]
ok: [vm4]

TASK [debug] *************************************************************************************
fatal: [vm1]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: 'dict object' has no attribute 'XYZ'\n\nThe error appears to be in '/opt/apache/local_facts.yml': 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        filter: ansible_local\n    - debug:\n      ^ here\n"}
fatal: [vm3]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: 'dict object' has no attribute 'XYZ'\n\nThe error appears to be in '/opt/apache/local_facts.yml': 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        filter: ansible_local\n    - debug:\n      ^ here\n"}
fatal: [vm4]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: 'dict object' has no attribute 'XYZ'\n\nThe error appears to be in '/opt/apache/local_facts.yml': 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        filter: ansible_local\n    - debug:\n      ^ here\n"}
  • 对于ini格式的自定义事实.fact文件中变量名若为大写,获取该变量的值时变量名应转为小写。这是由于python的环境造成的(python默认将大写字母转为小写字母)
  • 修改local_facts.yml中的{{ansible_facts['ansible_local']['mylocal']['general']['XYZ']}为{{ansible_facts['ansible_local']['mylocal']['general']['xyz']}的执行效果
[root@vm2 apache]# ansible-playbook local_facts.yml --syntax-check -i inventory 

playbook: local_facts.yml

[root@vm2 apache]# ansible-playbook local_facts.yml -i inventory 
TASK [debug] *************************************************************************************
ok: [vm3] => {
    "msg": "xp and 2"
}
ok: [vm1] => {
    "msg": "xp and 2"
}
ok: [vm4] => {
    "msg": "xp and 2"
}
  • 对于json格式的自定义事实.facts文件则不存在上述问题
## 自定义事实json格式
[root@vm2 apache]# vim file/my.fact 
{
   "general": {
    "XYZ": "1",
    "asdf": "2"
     }, 
          
   "users": {  
     "user1": "fyj", 
     "user2": "xp"  
     }  
}

## 
[root@vm2 apache]# vim local.facts.yml 

---
- hosts: webservers
  gather_facts: no
  tasks:
    - name: create directory for ansible custom facts
      file:
        state: directory
        recurse: yes
        path: /etc/ansible/facts.d
    - name: install my.fact
      copy:
        src: file/my.fact
        dest: /etc/ansible/facts.d
    - name: re-read facts after adding my.fact
      setup:
        filter: ansible_local
    - debug:
        msg: "{{ansible_facts['ansible_local']['my']['general']['XYZ']}} and {{ansible_facts['ansible_local']['my']['users']['user1']}}"

[root@vm2 apache]# ansible-playbook  local.facts.yml -i inventory --vault-password-file=vault-pass 

TASK [re-read facts after adding my.fact] ********************************************************
[WARNING]: error loading fact - please check content
ok: [vm4]
ok: [vm3]
ok: [vm1]

TASK [debug] *************************************************************************************
ok: [vm1] => {
    "msg": "1 and fyj"
}
ok: [vm3] => {
    "msg": "1 and fyj"
}
ok: [vm4] => {
    "msg": "1 and fyj"
}

3.5 魔法变量

  • 一些变量并非事实或通过setup模块配置,但也由Ansible自动设置。这些魔法变量也可用于获取与特定受管主机相关的信息。

3.5.1 常用魔法变量

  • hostvars

包含受管主机的变量,可以用于获取另一台受管主机的变量的值。
如果还没有为受管主机收集事实,则它不会包含该主机的事实。

[root@vm2 apache]# ansible vm1 -m debug -a "var=hostvars['vm4']" -i inventory --vault-password-file=vault-pass 
vm1 | SUCCESS => {
    "hostvars['vm4']": {
        "ansible_check_mode": false,
        "ansible_diff_mode": false,
        "ansible_facts": {},
        "ansible_forks": 5,
        "ansible_host": "192.168.137.134",
        "ansible_inventory_sources": [
            "/opt/apache/inventory"
        ],
        "ansible_password": 123456,
        "ansible_playbook_python": "/usr/bin/python3.6",
        "ansible_verbosity": 0,
        "ansible_version": {
            "full": "2.9.11",
            "major": 2,
            "minor": 9,
            "revision": 11,
            "string": "2.9.11"
        },
        "group_names": [
            "webservers"
        ],
        "groups": {
            "all": [
                "vm1",
                "vm3",
                "vm4"
            ],
            "ungrouped": [],
            "webservers": [
                "vm1",
                "vm3",
                "vm4"
            ]
        },
        "inventory_dir": "/opt/apache",
        "inventory_file": "/opt/apache/inventory",
        "inventory_hostname": "vm4",
        "inventory_hostname_short": "vm4",
        "omit": "__omit_place_holder__088524c558187e4fd4d415ed62ae61eb0aff4050",
        "playbook_dir": "/opt/apache"
    }
}

[root@vm2 apache]# ansible vm1 -m debug -a "var=hostvars['vm4']['ansible_password']" -i inventory --vault-password-file=vault-pass 
vm1 | SUCCESS => {
    "hostvars['vm4']['ansible_password']": "123456"
}
  • group_names

列出当前受管主机所属的所有组

[root@vm2 apache]# ansible vm1 -m debug -a "var=group_names" -i inventory --vault-password-file=vault-pass 
vm1 | SUCCESS => {
    "group_names": [
        "webservers"
    ]
}
  • groups

列出清单中的所有组和主机

[root@vm2 apache]# ansible vm1 -m debug -a "var=groups" -i inventory --vault-password-file=vault-pass 
vm1 | SUCCESS => {
    "groups": {
        "all": [
            "vm1",
            "vm3",
            "vm4"
        ],
        "ungrouped": [],
        "webservers": [
            "vm1",
            "vm3",
            "vm4"
        ]
    }
}
  • inventory_hostname

包含清单中配置的当前受管主机的主机名称。
因为各种原因有可能与事实报告的主机名称不同

[root@vm2 apache]# ansible vm1 -m debug -a "var=inventory_hostname" -i inventory --vault-password-file=vault-pass 
vm1 | SUCCESS => {
    "inventory_hostname": "vm1"
}