Shell – read a file and execute each line as command using ansible

ansibleshell

I want to write a playbook for following scenario:
reads a text file which has linux commands written it,
executes them one by one,
aborts if any command fails to execute,
and
if I correct the command and run the playbook again it should execute from where it was aborted (instead of executing from beginning)

sample file: sample.txt

echo "hello world"  
df -h  
free -m  
mkdir /tmp/`hostname`_bkp  
touch /tmp/`hostname`_bkp/file{1..5}  
mvn -version  
echo "directory and files created"  
echo "Bye.!"  

So for example if mvn -version fails to execute then ansible should abort.

How can achieve scenario through ansible?

Best Answer

Bellow is an example playbook, which executes a number of simple tasks.

---
 - hosts: localhost
   tasks:
    - name: say hi
      shell: echo "Hello, World!"

    - name: do df -h
      shell: df -h
      register: space

    - name: show the output of df -h
      debug: var=space

    - name: do free -m
      shell: free -m
      register: memory
      ignore_errors: yes

    - name: show memory stats
      debug: var=memory

    - name: create /tmp/"hostname"_bkp
      file: dest=/tmp/{{ ansible_nodename }}_bkp state=directory

    - name: create files
      file: dest=/tmp/{{ ansible_nodename }}_bkp/file{{ item }} state=touch
      with_items:
       - 1
       - 2
       - 3
       - 4
       - 5

It creates a directory and files at the desired location. You can also set ownership, permissions, which fit better your requirements.

ansible_nodename is an ansible fact (a variable), which gets collected at the beginning of a play.

You can see more information about the ansible file module here. Please have a look at the other ansible modules - they are plenty, easy to learn and powerful.

Related Question