首页 > 解决方案 > Ansible:如何评估一个模板并将评估的模板放入另一个模板中?

问题描述

我们有一个场景,我们必须用另一个模板文件填充最终的模板文件。

概念参考信息保存在 CSV 文件中,其中包含联系和升级点的详细信息

#csv
incident_type,support_team,support_email
server_down,linux_group,linux@sample.com
server_crash,vmware_group,vm@sample.com

然后必须填充contacts_details 模板。联系人组的模板类似于

#contacts_details.template.j2
|  Item | Value  |
|---|---|
| incident_type  | {{incident_type}}  |
| support_team  | {{support_team}}  |
| support_email  | {{support_email}}  |

然后这个模板对象必须填充主剧本以便操作调用

#callout.playbook.j2
some stuff already there

{{contacts_details}}

所以最终目标是让 Ansible 填充

我已经使用 Ansible 模板模块轻松填充了模板

- name: filltemplates contacts_details
  template:
    src: contacts_details.template.j2
    dest: contacts_details.template
    
- name: filltemplates callout
  template:
      src: callout.playbook.j2
      dest: callout.playbook

但它在“标注”时失败,因为它无法替换{{contacts_details}}

无论如何,我可以确保第一次模板迭代持续到第二次模板替换?

server_down对于类型警报,预期的最终结果 是:

#My Nice Playbook
some stuff already there

|  Item | Value  |
|---|---|
| incident_type  | server_down  |
| support_team  | linux_group |
| support_email  | linux@sample.com |

标签: templatesansible

解决方案


如下完成

---
- name: Read a template and Put into another template
  hosts: localhost
  gather_facts: no
  tasks:
    - name: "show templating results"
      set_fact:
        contact_details: "{{ lookup('template', './templates/04_contact_details.j2') }}"
      vars:
        name: "bob"
        email: "bob@bob.com"
        phone: "12345"

    - name: "Update final template"
      template:
          src: "./templates/04_main_callout.md.j2"
          dest: "/tmp/main_callout.md"
          mode: preserve

模板在哪里

04_contact_details.j2
|  Key |  Value |
|---|---|
| name  | {{name}}  |
| email  | {{email}}  |
| phone  | {{phone}}  |

主要模板是

04_main_callout.md.j2
# Sample markdown

## aim is to fill up contact details automatically from another template

{{contact_details}}

推荐阅读