You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取Ansible tempfile模块创建的临时目录名称

Extracting Temporary Directory Name from Ansible Tempfile Module Output

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

  1. Direct access: You can reference output.path immediately after registering the output variable—this gives you the exact path to your temporary directory.
  2. Reusable variable: Use the set_fact module to create a dedicated variable (like staging_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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 04:15:02