如何获取Ansible tempfile模块创建的临时目录名称
Problem Statement
I've written a simple Ansible playbook to create a temporary directory, and I want to save the directory's full path to a variable. Here's my playbook:
- hosts: "{{ lookup('env', 'HOSTNAME') }}" tasks: - name : Create staging directory tempfile: state: directory suffix: staging path: "{{ lookup('env', 'HOME') }}" become: true register: output - name: print stdout debug: msg="{{ output }}"
When I run this, the output variable returns as a dictionary. How do I extract the temporary directory path from this dictionary and save it to a variable?
Solution
Got it, let's break this down! The tempfile module (when used with state: directory) includes a path key in its returned dictionary—this is exactly the full absolute path to the temporary directory you created. You can access this value directly, or store it in a dedicated variable for reuse across tasks.
Updated Playbook
Here's how to modify your playbook to extract and use the directory path effectively:
- hosts: "{{ lookup('env', 'HOSTNAME') }}" tasks: - name: Create staging directory tempfile: state: directory suffix: staging path: "{{ lookup('env', 'HOME') }}" become: true register: output - name: Print the temporary directory path directly debug: msg: "Created staging directory at: {{ output.path }}" - name: Save directory path to a reusable variable set_fact: staging_directory: "{{ output.path }}" - name: Use the reusable variable in another task debug: msg: "Preparing to use staging directory: {{ staging_directory }}"
Key Details
- Direct access: You can reference
output.pathimmediately after registering theoutputvariable—this gives you the exact path to your temporary directory. - Reusable variable: Use the
set_factmodule to create a dedicated variable (likestaging_directory) if you need to reference the path in multiple subsequent tasks. This variable will persist for the rest of the play.
What the Full Output Dictionary Looks Like
When you print the complete output variable, you'll see a structure similar to this (simplified):
{ "changed": true, "path": "/home/your-username/random-string-staging", "state": "directory", "invocation": { ... } }
The path key is always present when creating a directory with tempfile, so it's reliable to use for your use case.
内容的提问来源于stack exchange,提问作者linuxfan

