Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ansible: run multiple action

Tags:

ansible

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
like image 785
Deven Avatar asked May 18 '17 10:05

Deven


3 Answers

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

like image 150
Arbab Nazar Avatar answered Sep 28 '22 07:09

Arbab Nazar


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.

like image 28
Jack Avatar answered Sep 28 '22 06:09

Jack


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
like image 27
Sahil Gulati Avatar answered Sep 28 '22 08:09

Sahil Gulati