Home > Enterprise >  change directory in ansible playbook
change directory in ansible playbook

Time:12-16

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?

CodePudding user response:

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
  • Related