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

Ansible如何为所有任务统一设置工作目录?

Ansible Windows任务统一设置工作目录的解决方案

你遇到的问题根源在于:每个win_shell任务都是独立的CMD进程,cd命令仅对当前进程生效,进程结束后目录切换的效果就会消失,所以后续任务仍会回到默认工作目录。

以下是两种可行的解决方法:

方法1:全局统一设置工作目录

在Play的vars中定义ansible_win_chdir变量,所有win_shell任务会默认使用该目录作为工作路径,无需逐个任务配置:

---
- name: 执行TSM备份与清理任务
  hosts: windows_hosts
  vars:
    ansible_win_chdir: E:\mydirectory
  tasks:
    - name: 执行TSM备份命令
      win_shell: tsm backup [你的备份参数]
      args:
        executable: cmd

    - name: 执行TSM清理命令
      win_shell: tsm cleanup [你的清理参数]
      args:
        executable: cmd

    - name: 列出目录文件
      win_shell: dir
      args:
        executable: cmd
      register: myfiles

方法2:单个任务指定工作目录

如果仅部分任务需要切换到目标目录,可以在win_shell的args中添加chdir参数,单独指定该任务的工作路径:

- name: 列出指定目录文件
  win_shell: dir
  args:
    executable: cmd
    chdir: E:\mydirectory
  register: myfiles

- name: 执行TSM备份命令
  win_shell: tsm backup [你的备份参数]
  args:
    executable: cmd
    chdir: E:\mydirectory

内容的提问来源于stack exchange,提问作者Mary.rd

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 05:57:30