在ansible中使用jinja2时如何避免使用临时文件

How to avoid temp file when using jinja2 in ansible

我想在 ansible 中做一件非常基本的事情,那就是:

我的问题是: 有没有更好的方法(最短的方法,例如仅一个任务)来按照示例 2 的方式编写剧本而不使用临时文件?

提前致谢。

示例 1:使用临时文件

以下是我多次尝试的示例:

---
- hosts: localhost
  gather_facts: false
  any_errors_fatal: true

  ################################################################
  # Mandatory --extra-vars                                       #
  #     myvar    : My variable                                   #
  # ##############################################################
  vars:
    myvar: "{{ myvar }}"

  tasks:

        - name: Create temporary file
          tempfile:
            state: file
            prefix: ansible
            suffix: mysuffix
          register: my_temp_file

        - name: Generate file from template replacing my_var by its value in dest file
          template:
            src: ./templates/mytemplate.j2
            dest: "{{ my_temp_file.path }}"

        - name: use file generated with jinja2
          shell: |
            cat "{{ my_temp_file.path }}" | ./mycommand -f -

        - name: Use the registered var and the file module to remove the temporary file
          file:
            path: "{{ my_temp_file.path }}"
            state: absent
          when: my_temp_file.path is defined

示例 2:没有临时文件

---
- hosts: localhost
  gather_facts: false
  any_errors_fatal: true

  ################################################################
  # Mandatory --extra-vars                                       #
  #     myvar    : My variable                                   #
  # ##############################################################
  vars:
    myvar: "{{ myvar }}"

  tasks:
    - name: get output of templating engine when applied on template
      set_fact:
        rendered_template: "{{ lookup('template', './templates/mytemplate.j2') }}"

    - name: use file generated with jinja2
      shell: |
        cat <<< "{{ rendered_template }}" | ./mycommand -f -

使用stdin,例如

- name: Use stdin generated by Jinja2
  command:
    cmd: ./mycommand -f -
    stdin: "{{ lookup('template', 'templates/mytemplate.j2') }}"

那你也可以用command instead of shell. Quoting from Notes:

"If you want to execute a command securely and predictably, it may be better to use the ansible.builtin.command module instead."