6

I am running ansible to copy and execute the script on remote side if script not found. but I am getting this error.

ERROR! conflicting action statements: copy, command

How can i use multiple action in single task.

---
- name: Check if the bb.sh exists
  stat:
    path: /tmp/bb.sh
  register: stat_result

- name: Copy and execute script
  copy: src=sync/bb.sh dest=/tmp/sync/ mode=0755
  command: sh -c "/bin/sh /tmp/bb.sh"
  when: stat_result.stat.exists == False
Deven
  • 85
  • 1
  • 1
  • 4

3 Answers3

8

The best way to run multiple actions in ansible(2.x) is using block:

---
- name: Check if the bb.sh exists
  stat:
    path: /tmp/bb.sh
  register: stat_result

- block:
    - name: Copy script if it doesnot exist
      copy:
        src: sync/bb.sh 
        dest: /tmp/sync/
        mode: 0755

    - name: "Run script"
      command: sh -c "/bin/sh /tmp/bb.sh"

  when: stat_result.stat.exists == False

Hope that might help you

Arbab Nazar
  • 22,378
  • 10
  • 76
  • 82
5

Another way is to use the script module:

- name: Copy script and execute
  script: sync/bb.sh

It copies the script over and runs it.

If you only want to run the script if it is not there already:

  - name: Copy file over
    copy:
      src: sync/bb.sh
      dest: /tmp/bb.sh
      mode: 0755
    register: copy_result

  - name: Run script if changed
    shell: /tmp/bb.sh
    when: copy_result.changed == true

With this, it will copy the file and run it if the file is not on the remote host, AND if the source file is different from the "copy" on the remote host. So if you change the script, it will copy it over and execute it even if an older version is already on the remote host.

Jack
  • 5,801
  • 1
  • 15
  • 20
4

You should do it like this. You can't use multiple actions in one task. rather distribute them on condition statement. You can also use block with in a task.

Note: Here i am assuming everything is working fine, with all your stuff, Like you paths are accessible and available while copying src to dest

---
- name: Check if the bb.sh exists
  stat:
    path: /tmp/bb.sh
  register: stat_result

- name: Copy script if it doesnot exist
  copy: src=sync/bb.sh dest=/tmp/sync/ mode=0755
  when: stat_result.stat.exists == False

- name: "Run script"
  command: sh -c "/bin/sh /tmp/bb.sh"
  when: stat_result.stat.exists == False
Sahil Gulati
  • 15,028
  • 4
  • 24
  • 42
  • but my condition is to run the script only one time. if script is already present then don't perform any action. if script is not present then perform copy and execution. – Deven May 18 '17 at 10:42
  • 1
    So like in my above post if you change `stat_result.stat.exists == True` to `false` then i hope it will be your expected output. right?, so it will like if script is not present then execute first section and second section – Sahil Gulati May 18 '17 at 10:46