Bobcares

Ansible Builtin Shell Multiple Commands

by | Apr 18, 2024

Learn more about Ansible builtin Shell multiple commands. Our DevOps Support team is here to help you with your questions and concerns.

Ansible Builtin Shell Multiple Commands

The Ansible shell module is a powerful tool that helps with the seamless execution of commands on remote targets. Almost like directly logged into the shell.

Ansible Builtin Shell Multiple Commands

While running a single command at a time is not an uncommon sight, the Ansible shell module lets us execute multiple commands simultaneously. Let’s take a look at how to use this feature:

  1. First, open a text editor and create a new playbook. Let’s name it `playbook2.yml` and create it in the `~/ansible_shell_module_demo` directory.
  2. Then, copy and paste the following content into `playbook2.yml`. Here, the shell module will not create four separate files by running four different commands in the same playbook.

    tasks:
    - name: Create multiple text files in tmp directory with shell module
    ansible.builtin.shell: |
    echo "This goes in log file" > /tmp/log_file.txt
    echo "This goes in memory file"> /tmp/memory_file.txt
    echo "This goes in disk file" > /tmp/disk_file.txt
    echo "This goes in version file"> /tmp/version_file.txt
    become: true
    args:
    chdir: /var/log

  3. Now, run the playbook on the designated node (in this example, SRV1) with this command:

    ansible-playbook playbook2.yml --inventory SRV1

  4. Next, verify that the files have been created on the remote host.

How to Run Sequential Commands

The shell module also lets us run a sequence of commands to be executed in order.

For example:


- name: Shell module example
hosts: webservers
tasks:
- name: Run multiple commands
shell: |
date > /tmp/date.txt
uptime > /tmp/uptime.txt
echo "Hello World" > /tmp/hello.txt

Here, the commands (date, uptime, echo) are executed in order from the first task to the last.

Here are a few additional tips to keep in mind while running multiple shell commands:

  • When running multiple commands, use the vertical bar (`|`) to indicate a multi-line string within the shell module.
  • Ensure proper error handling within commands for playbook integrity. We can use `exit 0/1` to control Ansible behavior in case of errors.

[Need assistance with a different issue? Our team is available 24/7.]

Conclusion

In brief, our Support Experts demonstrated how to run builtin Shell multiple commands in Ansible.

PREVENT YOUR SERVER FROM CRASHING!

Never again lose customers to poor server speed! Let us help you.

Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.

GET STARTED

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

Never again lose customers to poor
server speed! Let us help you.