首页 > 解决方案 > 剧本中的 Ansible 嵌套变量

问题描述

我正在尝试使用 getent 查找用户的主目录,然后将该信息应用于复制作业。我知道我们不能做嵌套变量,但我只是卡住了。我一直在使用 lookup('var's...) 语法和从字典中提取值的各种方法。在这种特殊情况下,我确实知道用户的主目录,但现在更多的是弄清楚这一点。ANSIBLE_USER定义为ansible

我的剧本是:

#lookup ansible user's home directory
#drops the value into a getent_passwd variable
- hosts: all
  become_user: root
  become: true
  tasks:
    - name: get info
      getent:
        key: "{{ ANSIBLE_USER }}"
        database: passwd
    - debug:
        var: getent_passwd.{{ ANSIBLE_USER }}.4
    - set_fact:
        ANSIBLE_HOME: "{{ getent_passwd['ansible'][4] }}"

- hosts: all
  become_user: root
  become: true
  tasks:
    - name: copy iptables files
      copy:
        src: "iptables/{{ IPTABLESCONFSRC }}/iptables.sh"
        dest: "{{ ANSIBLE_HOME }}/temp/iptables.sh"

这是有效的,因为我手动定义了'ansible'该行中的字符串ANSIBLE_HOME。但是,我在功能上想要完成的是:

ANSIBLE_HOME: "{{ getent_passwd['{{ ANSIBLE_HOME }}'][4] }}"

我能得到的最好的结果是一个undefined variable错误,因为我最终会寻找:getent_passwd[ansible][4]或者getent_passwd.ansible.4通过以下方式不存在:

ANSIBLE_HOME: "{{ lookup('vars', 'getent_passwd.' + ANSIBLE_USER + '.4') }}"

或者

ANSIBLE_HOME: "{{ lookup('vars', 'getent_passwd[' + ANSIBLE_USER + '][4]') }}"

调试输出显示:

ok: [HOSTNAME] => {
"getent_passwd.ansible.4": "/home/ansible"
}

这似乎可行,因为调试变量已经被认为是 Jinja,所以它对你来说实际上是双重嵌套。

标签: ansible

解决方案


哦,天哪。猜猜这比我想的要容易。这个:

ANSIBLE_HOME: "{{ getent_passwd[ANSIBLE_USER][4] }}"

工作正常。


推荐阅读