首页 > 解决方案 > 如何使用 ansible.builtin.template 模块在文件中写入变量值?

问题描述

我想在文件中记录变量的内容。我是这样做的,

 - name: write infraID to somefile.log
    copy:
      content: "{{ infraID.stdout }}"
      dest: somefile.log

它奏效了。但是在copy 此处的文档中,我发现他们建议在这种情况下使用template而不是。copy

对于高级格式或如果content包含变量,请使用 ansible.builtin.template 模块。

我在这里查看了模板模块文档中给出的示例。但是我无法弄清楚在我的场景中有效的东西。你能告诉我如何以推荐的方式正确地做到这一点吗?提前致谢 !!干杯!

标签: ansible

解决方案


template模块没有content属性。您必须创建一个包含模板的文件,例如:

模板/infra-id-模板

{{ infraID.stdoud }}

剧本

---
- hosts: localhost

  tasks:
    - name: Get infra ID
      shell: echo "my-infra-id"
      register: infraID

    - name: Template the file
      template:
        src: infra-id-template
        dest: infra-id-file

推荐阅读