Creating a Temporary Directory to do some ansible work

Sometimes when working with ansible you might need a temporary folder to do some work in. Perhaps it’s going to store some large files or secrets and so should be cleaned up afterwards. Below is a sample playbook that can be used to do just that.

- hosts: localhost
  tasks:
  - name: Create temp directory for doing work in
    command: mktemp -d /tmp/mytempdir-XXXXXX
    register: mktemp

  - set_fact:
      tempdir: "{{ mktemp.stdout }}"

# insert your code using {{ tempdir }} here

  - name: Cleanup temp directory
    file:
      path: "{{ tempdir }}"
      state: absent

You can grab the code directly from our github repo
https://github.com/alistairfay/code-snippets/blob/master/tempdir.yml

3 thoughts on “Creating a Temporary Directory to do some ansible work

Leave a Reply

Your email address will not be published. Required fields are marked *