Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I save an ansible variable into a temporary file that is automatically removed at the end of playbook execution?

In order to perform some operations locally (not on the remote machine), I need to put the content of an ansible variable inside a temporary file.

Please note that I am looking for a solution that takes care of generating the temporary file to a location where it can be written (no hardcoded names) and also that takes care of the removal of the file as we do not want to leave things behind.

like image 584
sorin Avatar asked Apr 15 '16 12:04

sorin


3 Answers

You should be able to use the tempfile module, followed by either the copy or template modules. Like so:

- 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

Or if you're running it in a role:

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

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

Then just pass temp_config.path to whatever module you need to pass the file to.

It's not a great solution, but the alternative is writing a custom module to do it in one step.

like image 133
tzrlk Avatar answered Oct 23 '22 13:10

tzrlk


Rather than do it with a file, why not just use the environment? This wan you can easily work with the variable and it will be alive through the ansible session and you can easily retrieve it in any steps or outside of them.

like image 2
Tymoteusz Paul Avatar answered Oct 23 '22 13:10

Tymoteusz Paul


Although using the shell/application environment is probably, if you specifically want to use a file to store variable data you could do something like this

- hosts: server1
  tasks:
  - shell: cat /etc/file.txt
    register: some_data
  - local_action: copy dest=/tmp/foo.txt content="{{some_data.stdout}}"

- hosts: localhost
  tasks:
  - set_fact: some_data="{{ lookup('file', '/tmp/foo.txt') }}"
  - debug: var=some_data

As for your requirement to give the file a unique name and clean it up at the end of the play. I'll leave that implementation to you

like image 1
Petro026 Avatar answered Oct 23 '22 14:10

Petro026