← All insightsIntegration

How to use Bash & Shell Scripting with Ansible

CodeWizard Engineering · 21 April 2025 · 3 min read · Intermediate

Bash & Shell Scripting and Ansible are a common pairing in a modern DevOps stack. Here is how they fit together and a practical way to wire them up.

Where Bash & Shell Scripting fits

Bash is the shell present on virtually every Linux system. With strict mode and a little discipline it is perfect for small, reliable automation, wrappers and glue between tools.

bash
#!/usr/bin/env bash
set -Eeuo pipefail
trap 'echo "error on line $LINENO" >&2' ERR

main() {
  local name="${1:?usage: deploy <name>}"
  echo "deploying ${name}"
}
main "$@"

Where Ansible fits

Ansible configures servers and orchestrates deploys using idempotent 'playbooks' - YAML that describes desired state and runs over SSH with no agent to install on the targets.

yaml
- hosts: web
  become: true
  tasks:
    - name: Install nginx
      ansible.builtin.package:
        name: nginx
        state: present
    - name: Ensure nginx is running and enabled
      ansible.builtin.service:
        name: nginx
        state: started
        enabled: true
    - name: Deploy site config
      ansible.builtin.template:
        src: site.conf.j2
        dest: /etc/nginx/conf.d/site.conf
      notify: reload nginx
  handlers:
    - name: reload nginx
      ansible.builtin.service: { name: nginx, state: reloaded }

Making them work together

  • Start every script with set -Eeuo pipefail and an ERR trap
  • Quote all variable expansions; prefer [[ ]] over [ ]
  • Prefer modules over raw shell; add changed_when/creates to shell tasks
  • Structure logic into roles and use group_vars/host_vars

Want this pairing set up properly, with docs and handover? That is exactly the kind of work CodeWizard's embedded senior engineers do - and both Bash & Shell Scripting and Ansible have active community groups you can join for free.

Like where this is going?

Get hands-on help from the engineers who write these posts.

Book a free consult