首页 > 解决方案 > Ansible:从库存文件中获取变量值

问题描述

我在从库存文件中获取ansible_userunder的值时遇到问题。rhel以下是我尝试获取的几种方法,每次都显示 undefined rhel。关于如何检索它的任何建议?

    - set_fact:
         SSHUSER: "{{  hostvars.[rhel].ansible_user }}"
    - set_fact:
         SSHUSER: "{{  rhel.ansible_user }}"
---
all:
  vars:
    project: test
  hosts:
  children:
    test_vm:
       hosts: 10.10.10.4
    example_vm:
       hosts: 10.10.10.5
    ubuntu:
      children:
        test_vm:
      vars:
        os: ubuntu
        ansible_user: "testuser"
    rhel:
      children:
        example_vm:
      vars:
        os: rhel
        ansible_user: "exampleuser"

标签: ansibleansible-2.xansible-inventoryansible-facts

解决方案


rhel您引用的是一个组而不是一个主机——一个主机可能属于多个组。为了实现“组 rhel 的某些成员的主机变量”,您想要的表达式是 jinja2 表达式:{{ hostvars[groups["rhel"][0]].ansible_user }}

ansible 清单主机名的字符串列表在哪里groups["rhel"],如果有人假设它们都有一个等价物ansible_user,那么抓住第一个应该是安全的,它是groups["rhel"][0]或者更冗长但可能更清晰groups["rhel"]|first

然后,我们想要那个主机hostvars,而不是我们自己的;因为它是由 ansible 库存主机名索引的,我们可以将该值插入到字典中,因为它是每个主机变量,然后返回您请求的事实hostvarsdict[str, dict]hostvarshostvars[groups["rhel"][0]]hostvars[groups["rhel"][0]].ansible_useransible_user


推荐阅读