Copy shell script and execute it using Ansible.

Here we will see one Complete example to copy shell script and execute it, & get its output.

I. Make Ansible Conifguration

# cat ansible.cfg 
[defaults]

inventory = hosts
remote_user=saket
host_key_checking = False
pipelining = True

 

II. Create the script what you want to copy and execute

# cat runtask.sh 
#!/bin/bash
CMD="tail /var/log/messages"
echo "Getting the command $CMD output”
$CMD

 

III. Create Playbook

# cat playbooks/runtask.yml 
---
- hosts: all
  remote_user: saket
  gather_facts: no
  sudo: yes
  strategy: free
  tasks:
  - name: "Copy runtask.sh scipt on the remote hosts"
    copy: src= runtask.sh dest=/root/ mode=0755
  - name: "Execute the script"
    command: sh ~/runtask.sh
    register: version
  - debug:
     var: version.stdout_lines

 

IV. Run the playbook now.

# date; 
# ansible-playbook -b -K playbooks/runtask.yml -i hosts -u saket -f 10 > output.txt ; 
# date
5 1 vote
Article Rating
Subscribe
Notify of
guest

0 Comments
Newest
Oldest Most Voted
Inline Feedbacks
View all comments