[英]Ansible nested variable in playbook
I'm trying to use getent to lookup a user's home directory and then apply that information to a copy job.我正在尝试使用 getent 查找用户的主目录,然后将该信息应用于复制作业。 I know we can't do nested variables, but I'm just stuck.我知道我们不能做嵌套变量,但我只是卡住了。 I have been playing with the lookup('var's...) syntax and various ways to pull a value out of a dict.我一直在使用 lookup('var's...) 语法和从字典中提取值的各种方法。 In this particular case I do know the user's home directory, but now it's more an exercise in figuring this out.在这种特殊情况下,我确实知道用户的主目录,但现在更多的是弄清楚这一点。 ANSIBLE_USER
is defined as ansible
ANSIBLE_USER
定义为ansible
My playbook is:我的剧本是:
#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"
This works because I'm manually defining the 'ansible'
string in the ANSIBLE_HOME
line.这是有效的,因为我在ANSIBLE_HOME
行中手动定义了'ansible'
字符串。 However, what I'm functionally trying to accomplish is:但是,我在功能上想要完成的是:
ANSIBLE_HOME: "{{ getent_passwd['{{ ANSIBLE_HOME }}'][4] }}"
The best I can get is a undefined variable
error because I end up looking for: getent_passwd[ansible][4]
or getent_passwd.ansible.4
and that doesn't exist via:我能得到的最好的结果是一个undefined variable
错误,因为我最终会寻找: getent_passwd[ansible][4]
或getent_passwd.ansible.4
并且通过以下方式不存在:
ANSIBLE_HOME: "{{ lookup('vars', 'getent_passwd.' + ANSIBLE_USER + '.4') }}"
or或者
ANSIBLE_HOME: "{{ lookup('vars', 'getent_passwd[' + ANSIBLE_USER + '][4]') }}"
The debug output shows:调试 output 显示:
ok: [HOSTNAME] => {
"getent_passwd.ansible.4": "/home/ansible"
}
This seems to work because the debug var is already considered Jinja, so it's effectively double nesting for you.这似乎有效,因为调试变量已经被认为是 Jinja,所以它对你来说实际上是双重嵌套。
Oh geeze.哦,天哪。 Guess this was easier then what I was thinking.猜猜这比我想的要容易。 This:这个:
ANSIBLE_HOME: "{{ getent_passwd[ANSIBLE_USER][4] }}"
works fine.工作正常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.