[英]Ansible Setting fact with dynamic key/value
I am trying to set ansible facts from the stdout of a command task I call from another role.我正在尝试从我从另一个角色调用的命令任务的标准输出中设置 ansible 事实。
Role A:角色A:
- name: example command
command: client get -s {{ service }}
register: vars_string
- name: set vars
set_fact: vars={{ vars_string.stdout.split('\n')}}
when:
- vars_string.stdout | length > 0
- name: set vars as facts
set_fact: "{{ item }}"
with_items: "{{ vars }}"
vars output:变量 output:
"vars": [
"tst=ansible",
"example=values"
]
Role B:角色 B:
- debug:
var: tst
Results from Role B:角色 B 的结果:
Expectation: { "tst": "ansible" }
期望: { "tst": "ansible" }
Reality: { "tst": "VARIABLE IS NOT DEFINED!" }
现实: { "tst": "VARIABLE IS NOT DEFINED!" }
{ "tst": "VARIABLE IS NOT DEFINED!" }
I have tried to spit vars into a dict and use set_fact: "{{ item.key }}": "{{ item.value }}"
as well.我曾尝试将 vars 吐入 dict 并使用set_fact: "{{ item.key }}": "{{ item.value }}"
。 This returned the same results.这返回了相同的结果。
I want to be able to call by the variable name returned from the command in future roles.我希望能够在未来的角色中通过从命令返回的变量名进行调用。 Any ideas?有任何想法吗?
Two points about your code snippet that may interest you:关于您可能感兴趣的代码片段的两点:
vars_string.stdout_lines
您的命令中已经有 output 的换行符版本,它是vars_string.stdout_lines
vars
built-in variable, but either way, don't do that我不知道您是否只是偶然选择了该变量,或者您试图实际分配给vars
内置变量,但无论哪种方式,都不要这样做As best I can tell, there is no supported syntax for assigning arbitrary top-level host facts from within just a task.据我所知,没有支持的语法用于从任务中分配任意顶级主机事实。
You have two choices: write out those variables to a file, then use include_vars:
to read them in -- which will assign them as host facts, or concede to the way set_fact:
wants things and be content with those dynamic variables living underneath a known key in hostfacts您有两个选择:将这些变量写到文件中,然后使用include_vars:
将它们读入 - 这会将它们分配为主机事实,或者让步set_fact:
想要的方式并满足于生活在下面的动态变量hostfacts 中的已知键
We'll show the latter first, because it's shorter:我们将首先展示后者,因为它更短:
- set_fact:
my_facts: >-
{{ "{" + (vars_string.stdout_lines
| map('regex_replace', '^([^=]+)=(.+)', '"\1": "\2"')
| join(",")) + "}"
}}
when:
- vars_string.stdout | length > 0
Of course, be aware that trickery won't work if your keys or values have non-JSON friendly characters in them, but if that simple version doesn't work, ask a follow-up question, because there are a lot more tricks in that same vein当然,请注意,如果您的键或值中包含非 JSON 友好字符,则诡计将不起作用,但如果该简单版本不起作用,请提出后续问题,因为在同一条静脉
The include_vars:
way is: include_vars:
方式是:
- tempfile:
state: file
suffix: .json
register: vars_filename
- copy:
dest: '{{ vars_filename.path }}'
content: >-
{{ "{" + (vars_string.stdout_lines
| map('regex_replace', '^([^=]+)=(.+)', '"\1": "\2"')
| join(",")) + "}"
}}
- include_vars:
file: '{{ vars_filename.path }}'
- file:
path: '{{ vars_filename.path }}'
state: absent
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.