92
- name: Go to the folder
  command: chdir=/opt/tools/temp

When I run my playbook, I get:

TASK: [Go to the folder] ***************************** 
failed: [host] => {"failed": true, "rc": 256}
msg: no command given

Any help is much appreciated.

Jay
  • 18,959
  • 11
  • 53
  • 72
indolent
  • 3,053
  • 5
  • 23
  • 21

4 Answers4

121

There's no concept of current directory in Ansible. You can specify current directory for specific task, like you did in your playbook. The only missing part was the actual command to execute. Try this:

- name: Go to the folder and execute command
  command: chdir=/opt/tools/temp ls
Marcin Płonka
  • 2,840
  • 1
  • 17
  • 17
  • Good to have ability to run all playbook within a specific directory – podarok Jan 15 '15 at 08:23
  • 2
    `"There's no concept of current directory in Ansible"` I don't think that's true anymore, LOTS of tasks take relative paths now, such as `npm` `composer` `bower` etc – Jonathan Jun 11 '19 at 14:51
  • The pwd seems to be at the location of the playbook, irregardless of from which path you execute the `ansible-playbook` command? – huggie Nov 11 '22 at 03:47
40

This question was in the results for when I was trying to figure out why 'shell' was not respecting my chdir entries when I had to revert to Ansible 1.9. So I will be posting my solution.

I had

- name: task name
  shell:
    cmd: touch foobar
    creates: foobar
    chdir: /usr/lib/foobar

It worked with Ansible > 2, but for 1.9 I had to change it to.

- name: task name
  shell: touch foobar
  args:
    creates: foobar
    chdir: /usr/lib/foobar

Just wanted to share.

ndmeiri
  • 4,979
  • 12
  • 37
  • 45
Josh Beauregard
  • 2,498
  • 2
  • 20
  • 37
11

If you need a login console (like for bundler), then you have to do the command like this.

command: bash -lc "cd /path/to/folder && bundle install"

Kevin Carmody
  • 2,311
  • 2
  • 23
  • 23
  • This is also the command to use with composer (if the composer module doesn't get you there): `command: bash -lc "cd /var/www/ && /usr/local/bin/composer install"` – deviavir Jun 26 '14 at 08:51
  • 1
    You can now user `working_dir` to specify composer path relative – Jonathan Jun 11 '19 at 14:52
9

You can change into a directory before running a command with ansible with chdir.

Here's an example I just setup:

- name: Run a pipenv install
  environment:
    LANG: "en_GB.UTF-8"
  command: "pipenv install --dev"
  args:
    chdir: "{{ dir }}/proj"
Alper
  • 3,424
  • 4
  • 39
  • 45