在ansible playbook中更改目录

change directory in ansible playbook

我有 ansible 剧本,我想查看指定目录(使用 ls 命令)。该目录在根目录中,我使用 pwd 命令检查:

/root/git/ansible/data/example

ansible 任务看起来像这样:

name:  open directory
become: yes
become_user: root
command: chdir=/data/example ls

执行剧本后出现此错误:

fatal: [localhost]: FAILED! => {"changed": false, "msg": "Unable to change directory before execution: [Errno 2] No such file or directory: '/data/example'"}

而该目录确实存在。我也试过这个:

name:  open directory
become: yes
become_user: root
shell:
  cmd: ls
  chdir: /data/example

并得到同样的错误。有人可以帮忙吗?

给定树

shell> tree /data/example
/data/example
├── file1
├── file2
└── file3

0 directories, 3 files

所有形式的命令shell

- hosts: localhost

  tasks:

    - command:
        chdir: /data/example
        cmd: ls
      register: result
      tags: t1

    - shell:
        chdir: /data/example
        cmd: ls
      register: result
      tags: t2

    - command: chdir=/data/example ls
      register: result
      tags: t3

    - shell: chdir=/data/example ls
      register: result
      tags: t4

    - debug:
        var: result.stdout
      tags: always

按预期工作

  result.stdout:
    file1
    file2
    file3