2

i have ansible playbook and i want to look at specified directory (with ls command). the directory is in the root, i check with the pwd command :

/root/git/ansible/data/example

and the ansible the task looks like this :

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

after i execute the playbook i get this error :

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

while the directory actually does exist. i also tried this :

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

and got the same error. can anyone help?

Chloe
  • 181
  • 2
  • 11
  • 1
    possible duplicate of https://stackoverflow.com/questions/19369931/ansible-how-to-change-active-directory-in-ansible-playbook – Hamid Dec 16 '21 at 07:23
  • It's not a duplicate of [this](https://stackoverflow.com/questions/19369931/ansible-how-to-change-active-directory-in-ansible-playbook). The error is ``'No command given'`` because the command is missing ``command: chdir=/opt/tools/temp``. Here, the problem is ``'No such file or directory'``. – Vladimir Botka Dec 16 '21 at 08:30

1 Answers1

2

Given the tree

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

0 directories, 3 files

all forms of command and 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

work as expected

  result.stdout:
    file1
    file2
    file3
Vladimir Botka
  • 58,131
  • 4
  • 32
  • 63