indolent
indolent

Reputation: 3391

Ansible: How to change active directory in Ansible Playbook?

- 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.

Upvotes: 98

Views: 180427

Answers (4)

Alper
Alper

Reputation: 3973

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"

Upvotes: 12

Josh Beauregard
Josh Beauregard

Reputation: 2749

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.

Upvotes: 47

Kevin Carmody
Kevin Carmody

Reputation: 2319

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"

Upvotes: 10

Marcin Płonka
Marcin Płonka

Reputation: 2940

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

Upvotes: 127

Related Questions