如何将 ansible 变量保存到临时文件中,该文件会在 playbook 执行结束时自动删除?

2023-12-21

为了在本地(而不是在远程计算机上)执行一些操作,我需要将 ansible 变量的内容放入临时文件中。

请注意,我正在寻找一种解决方案,负责将临时文件生成到可以写入的位置(无硬编码名称),并且还负责删除文件,因为我们不想留下任何东西。


您应该能够使用tempfile https://docs.ansible.com/ansible/latest/modules/tempfile_module.html模块,后跟copy https://docs.ansible.com/ansible/latest/modules/copy_module.html or template https://docs.ansible.com/ansible/latest/modules/template_module.html模块。就像这样:

- hosts: localhost
  tasks:

    # Create a file named ansible.{random}.config
    - tempfile:
        state:  file
        suffix: config
      register: temp_config

    # Render template content to it
    - template:
        src:  templates/configfile.j2
        dest: "{{ temp_config.path }}"
      vars:
        username: admin

或者,如果您以角色运行它:

- tempfile:
    state:  file
    suffix: config
  register: temp_config

- copy:
    content: "{{ lookup('template', 'configfile.j2') }}"
    dest:    "{{ temp_config.path }}"
  vars:
    username: admin

然后就可以通过temp_config.path到您需要将文件传递到的任何模块。

这不是一个很好的解决方案,但另一种方法是编写一个自定义模块来一步完成它。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何将 ansible 变量保存到临时文件中,该文件会在 playbook 执行结束时自动删除? 的相关文章

随机推荐