Home > Blockchain >  Execute bash script via ansible playbook
Execute bash script via ansible playbook

Time:01-07

I'm looking to run the following shell script via ansible playbook.

#!/bin/bash
oci compute instance list --lifecycle-state RUNNING --region ca-toronto-1 --compartment-id < compartment OCID> --all | grep display-name -A 0 > hostnames.txt
for line in `cat hostnames.txt`
  do
   #echo $line
   if [[ $line == *","* ]]; then
    #    hostname=$(echo ${line//"display-name"/} | tr -d '",: ')
        hostname=$(echo "$line" | tr -d '",')
        echo "$hostname"
        ssh -tt "$hostname" "sudo puppet agent -tv && sleep 10"
       # break
   fi
  done

This works just like how i want when i run the shell script but I get a blank output when i run via ansible. Playbook:

---
- name: puppet agent trigger
  gather_facts: false
  become_user: true
  hosts: all
  tasks:
    - name: trigger puppet agent
      shell: |
        oci compute instance list --lifecycle-state RUNNING --region ca-toronto-1 --compartment-id <compartment OCID> --all | grep display-name -A 0 > hostnames.txt
        for line in `cat hostnames.txt`
        do
        if [[ $line == *","* ]]; then
         hostname=$(echo "$line" | tr -d '",')
         echo "$hostname"
         ssh -tt "$hostname" "sudo puppet agent -tv && sleep 10"
        fi
        done
      register: shell_output

    - debug: 
        msg: "{{ shell_output.stdout }}"

Please point me as to what im missing.

CodePudding user response:

According the description of your use case it seems to be recommended to transfer the whole logic of the script into Ansible itself. To do so and in respect to the comment regarding add_host_module, you could use an approach like

- name: Create an instance list
  shell:
    cmd: oc get nodes --no-headers | cut -d " " -f 1 | tr '\n' "," | rev | cut -c 2- | rev 
  register: instance_list
  changed_when: false

To generate the instance_list I've used an OpenShift cluster as example, because I don't have something like oci compute instance list ... accessible.

- name: Add all hosts from instance_list to the script group
  add_host:
    name: '{{ item }}'
    groups: script
  loop: "{{ instance_list }}"

From there you could proceed further to execute your command puppet agent -tv && sleep 10.

  •  Tags:  
  • Related