来自模板/yaml 文件的 Ansible setfacts

问题描述 投票:0回答:1

我们通常使用 include_vars 将 YAML 代码文件加载到我们的 playbook 中。 现在 yaml 文件中有我们想要使用 jinja2 生成的 yaml 块。 yaml 文件看起来像这样简化:

my_list_from_template:
  {% filter from_yaml %}
  {% for my_os_stage in all_os_stage -%}
  - name: "Template for {{ my_os_stage }}"
  {% endfor %}
  {% endfilter %}

我们的剧本看起来像这样

---
- name: "read tmp/test.yml"
  hosts: localhost
  connection: local
  remote_user: opsadm
  gather_facts: False
  become: yes

  #-----------------------------------------------
  vars:
    all_os_stage:
      - TST
      - DEV
      - INT
      - PRD

  #-----------------------------------------------
  tasks:
    - name: "read tmp/test.yml as template"
      ansible.builtin.set_fact: "{{ lookup('ansible.builtin.template', 'tmp/test.yml') }}"

    - debug:
        msg: "{{ my_list_from_template }}"

但是,调试失败并显示以下错误消息:

TASK [read tmp/test.yml as template] 
task path: test.yml:19
File lookup using tmp/test.yml as file
ok: [localhost] => {
    "ansible_facts": {
        "_raw_params": "my_list_from_template:\n  [{'name': 'Template for TST'}, {'name': 'Template for DEV'}, {'name': 'Template for INT'}, {'name': 'Template for PRD'}]\n"
    },
    "changed": false
}

TASK [debug]
task path: test.yml:22
fatal: [localhost]: FAILED! => {
    "msg": "The task includes an option with an undefined variable. The error was: 'my_list_from_template' is undefined. 'my_list_from_template' is undefined\n\nThe error appears to be in '/home/oizkrwa/ANS_GIT/LINUX_project_controller_2.4.0/test.yml': line 22, column 7, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n    - debug:\n      ^ here\n"
}

我该如何解决这个问题?

ansible
1个回答
0
投票

对于名为

templates/my_list.j2

的 Jinja2 模板
my_list_from_template:
  {% for my_os_stage in all_os_stage -%}
  - name: "Template for {{ my_os_stage }}"
  {% endfor %}

一个最小的示例手册

---
- hosts: localhost
  become: false
  gather_facts: false

  vars:

    all_os_stage:
      - TST
      - DEV
      - INT
      - PR

  tasks:

  - name: "Set from template"
    set_fact:
      my_list_from_template: "{{ lookup('ansible.builtin.template', 'templates/my_list.j2') }}"

  - debug:
      msg: "{{ my_list_from_template | from_yaml }}"

将产生

的输出
TASK [debug] ***************
ok: [localhost] =>
  msg:
    my_list_from_template:
    - name: Template for TST
    - name: Template for DEV
    - name: Template for INT
    - name: Template for PR
© www.soinside.com 2019 - 2024. All rights reserved.