How to execute a sequence of ansible commands in a single task using shell or command module? Its quite often needed to run a sequence of commands irrespective of the results. If you would like to automate the VM post-build, we knew that the template doesn’t have specific packages. Some of the configuration files might be missing a few entries. In such cases, you could simply execute the sequence of commands using the shell/command module.
1. Login to ansible server.
2. Here is the sample playbook which executes a sequence of commands using the shell module in localhost.
--- - hosts: localhost tasks: - name: Running sequence of commands using shell module shell: | echo "fire first command" echo "fire second command" echo "fire third command" echo "fire fourth command" echo "fire fifth command" register: SEQOUT - debug: msg={{SEQOUT.stdout_lines}}
Added debug module to see the command execution results.
3. Run the playbook
[root@ansible-server ~]# ansible-playbook sequence_of_commands.yaml
4. Here are the playbook results.
[root@ansible-server ~]# ansible-playbook sequence_of_commands.yaml PLAY [localhost] **************************************************************** TASK [Gathering Facts] ********************************************************** ok: [localhost] TASK [Running sequence of commands using shell module] ********************************************************************************** changed: [localhost] TASK [debug] ********************************************************************* ok: [localhost] => { "msg": [ "fire first command", "fire second command", "fire third command", "fire fourth command", "fire fifth command" ] } PLAY RECAP *********************************************************************** localhost : ok=3 changed=1 unreachable=0 failed=0 [root@ansible-server ~]#
Shlle module has the advantage over the command module to accept the filter and piping. Command module just accepts the plain command. Hope this article is informative to you. Share it! Comment it!! Be sociable!!!
rajani says
Informative blog. Thank you for sharing..