在 Ansible 中评估变量内容

Evaluate variable content in Ansible

我使用文件查找插件加载了一个内容为 Some {{bar}} random text 的文件:

- name: Load foo
  set_fact:
    foo: "{{ lookup('file', 'foo.txt') }}"
- name: Output foo
  debug:
    msg: "{{foo}}"

如果我输出{{foo}},输出就是Some {{bar}} random text。忽略我可以使用模板查找插件的事实:Is it possible to evaluate {{foo}} after the file has been loaded, so the actual value of bar 将被注入 Some {{bar}} random text?

我正在寻找类似的东西:

- name: Evaluate foo
  set_fact:
    evaulated_foo: "{{ lookup('template', foo) }}" #Use the value of foo instead of a file

这是预期的行为。查找 return unsafe text,永远不会被模板化。当您想要 return 模板评估后的文件内容时,请使用 template 查找。

为避免排序问题,请在查找中使用变量而不是 set_factset_fact 将变量设置为静态的、完全计算的值,而普通变量是延迟计算的,因此它们不需要同时定义所有变量。

- hosts: localhost
  gather_facts: false
  vars:
    foo: "{{ lookup('template', 'test.j2') }}"
  tasks:
    # These will work because bar is a current variable
    - debug:
        msg: "{{ foo }}"
      vars:
        bar: lemon

    - debug:
        msg: "{{ foo }}"
      vars:
        bar: orange

    # This will not work, because bar isn't set
    - set_fact:
        foo: "{{ foo }}"
PLAY [localhost] ***************************************************************

TASK [debug] *******************************************************************
ok: [localhost] => {
    "msg": "Some lemon random text\n"
}

TASK [debug] *******************************************************************
ok: [localhost] => {
    "msg": "Some orange random text\n"
}

TASK [set_fact] ****************************************************************
fatal: [localhost]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: {{ lookup('template', 'test.j2') }}: 'bar' is undefined\n\nThe error appears to be in '/home/ec2-user/test.yml': line 18, column 7, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n    # This will not work, because bar isn't set\n    - set_fact:\n      ^ here\n"}