Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run sh script in command task using ansible

Ok.. Here I go. This is my main.yml content.

- hosts: web-servers
  tasks:
    - name: Run the below script
      command: sh temp/myscript.sh

I have a shell script named "myscript.sh" placed under a directory called 'temp'. My directory hierarchy is:

  • ansible-copy-role (directory)
    • main.yml
    • temp (directory)
      • myscript.sh ( I want to run this Shell script)

I don't want to copy the shell script to my host servers and run from thre. I want to run the shell script which will be available along with the main.yml file.

When I run this playbook, I get an error like: stderr: sh: temp/myscript.sh: No such file or directory

Please help on this.

like image 832
user1493004 Avatar asked Apr 28 '16 01:04

user1493004


2 Answers

If you keep this in mind you will find Ansible much simpler:

Ansible modules run on the target host.

If you do this:

- name: run some command
  command: foo

Then that task will try to run the command foo on the host to which Ansible is connecting, not on the host where you're running Ansible.

If you want to run a task locally, you need to be explicit about that. For example:

- hosts: web-servers
  tasks:
    - name: Run the below script
      delegate_to: localhost
      command: sh temp/myscript.sh

This uses the delegate_to directive to have this task run on localhost rather than on whichever web-servers host this task would normally target.

See the Ansible documentation on delegation for more information.

like image 151
larsks Avatar answered Oct 19 '22 03:10

larsks


Additionally to @larsks fine answer, local_action is a shorthand to delegate_to: localhost. Therefore this could become:

- hosts: web-servers
  tasks:
    - name: Run the below script
      local_action: command sh temp/myscript.sh

Use the same link as reference to this.

like image 45
Wtower Avatar answered Oct 19 '22 03:10

Wtower