r/ansible • • Oct 28 '26

playbooks, roles and collections Why not just call a bash script?

One thing I still don't think I've understood with ansible is: Why all this new syntax for installing stuff, why not just write an install script in bash and then call it with ansible? Sorry if this is a stupid question...

42 Upvotes

57 comments sorted by

31

u/Horace-Harkness Oct 28 '26

Abstraction. To install a package with Ansible is like 3 lines of yaml. To do it in shell on RHEL and Debian and Arch with full error handling would be a lot of shell code.

4

u/aprettyparrot Oct 28 '26

Yes. I would say they solve two different problems. But can be combined for best results.

you can have an ansible script, but if you have a long bash op to do, maybe it does some validation, logging, updates some shit, has to do some text transformations and build some stuff blah blah

That’s way too long to just slap into ansible, so have ansible go around and run that bash script for you.

I’d say it comes down to a right tool for the job choice

2

u/_blarg1729 Oct 28 '26

You can do coneveluted things like that in an Ansible role. I have a certbot role that will parse the field of every certificate, if they don't match they get marked for re-request, then they get requested. You can change the domain names, key size, key type, even the CA it belongs to. It will just figure it out, no Python, (it does use OpenSSL to convert the certs fields to json).

vars/main.yml has about 100~ transformations in there, lots of which are nested.

Has to invent a way of doing unit test on those transformationa...

2

u/aprettyparrot Oct 28 '26

That’s cool, I haven’t gone deep into ansible. Mainly I use it for deploy or upgrade type things. Maybe like backup config, backup db, pull repo(s), make build, blah blah

It is quite versatile though

-15

u/oz1sej Oct 28 '26

What error handling do I need that sudo apt install package doesn't provide?

13

u/Horace-Harkness Oct 28 '26

apt doesn't exist on RHEL

What if the package is already installed? What if you don't have Sudo on that host? What if you need to template different versions for different hosts?

5

u/bilingual-german Oct 28 '26

But to be fair, since Debian and RHEL based distros don't share the same package names, you often enough have two versions of the required package list.

1

u/aprettyparrot Oct 28 '26

yum install

5

u/weiyentan Oct 28 '26

Ansible is a framework to organise your automation. Three lines of bash script is fine for a single task. Now try stringing that for error handling , work logic and multiple other tasks oh and do over hundreds of machines. Oh and have different settings for groups of servers. With ansible this makes things easy

3

u/scorp123_CH Oct 28 '26

What error handling do I need

What if the package you're trying to install is in the process of itself being updated in the repositories, but some of the dependencies are not updated yet? Result: You get broken dependencies, so you should leave the package "as is" if an older version is already installed; or maybe install the older version that still has its dependencies intact. Ansible can handle this tip top. With a bash script this can get complicated very fast, especially when executed against a fleet of x-100 hosts.

With Ansible and a properly written playbook I can be sure that no shenanigans happened. And it will tell me exactly if it applied a change to a host or not, and to which one it applied changes and which it ignored. With a bash script ... I'd now need another script to check what the first script has done, if the package I wanted installed is really installed, or did it just remove the old one but then fail to install a new version because of broken dependencies ...? As soon as you have x-100 hosts to manage, Ansible wins this contest sky-high.

2

u/ptvlm Oct 28 '26 edited Oct 28 '26

First, apt doesn't apply to RH based distros so you'd have to run multiple commands or introduce something in the script to detect distro type and use the correct package manager. Then ensure the package is correctly installed and configured and the service starts correctly, with said config maybe being different on each machine. Then there's inventory management, ansible makes it trivial to install on a subset of your estate, restrict to a single machine or exclude certain machines based on name or any other attribute. Then, you can easily manage version numbers, downgrade or upgrade or pin versions depending on machine requirements. Then easily add post install tasks or other handling. I use ansible extensively across dozens of machines and few playbooks are as simple as "deploy this package"

Basically, a bash script is cool if you only have one task to perform across a small number of machines. If your requirements are more complex or your estate is much larger, that script is going to get unwieldy rather quickly

2

u/Live_Surround5198 Oct 28 '26

‘bash: apt: command not found’ on a CentOS or Arch system.

2

u/ketchupnsketti Oct 28 '26

Your question kind of answers the question. What if we manage more than one distro? what if we manage different versions of a distro and the syntax isn't the same?

also, why run apt install package at all if the package is already installed?

You can add all of this to your bash script but it becomes a lot more work than ansible. That's who ansible is geared toward.

If you only need to run "apt install package" one time don't bother with ansible (or a script really, just type it).

1

u/DonaldMerwinElbert Oct 28 '26

It seems like you're asking from the perspective of someone using just their own PC - that's not who Ansible is for.

20

u/anarchyusa Oct 28 '26 edited Oct 29 '26

With pre-built collections, the script is already written. This is what’s known as “imperative” opps, i.e. DO THE THING. Ansible tasks are (or should be because it’s not necessarily automatic) written in a “declarative” fashion, i.e. DO WHATEVER IS NECESSARY TO MAKE THE STATE THUS”. E.g. not “start service X”, rather, “the state of service X should be started”. In the former, you have to write the state detection and state management (on, off, delayed, etc). In the latter, you just say what you want the state to be.

1

u/oz1sej Oct 29 '26

So - I currently have an ansible playbook to install programs, another to run an update, etc. You're saying I only should have one playbook to ensure that those programs are installed and the system is updated?

4

u/captkirkseviltwin Oct 29 '26

I'd also strongly recommend custom roles to do complex frequent tasks, and string them together with playbooks. A role to configure one subsystem, role to configure another subsystem, etc. Then chain them with a playbook to get a tailored result. Almost like the roles are the recipes, but the playbook is the dinner menu.

3

u/anarchyusa Oct 29 '26

One playbook to define the desired state as these app at these versions should be present, perhaps another to say that these apps at these versions should be absent. Stop thinking in terms of actions. “Install” & “upgrade “

5

u/planeturban Oct 28 '26

Sure you can do that. But how should you handle upgrades? Ansibles package/dnf/deb module gives you that automatically. 

-10

u/oz1sej Oct 28 '26

sudo apt update && sudo apt -y upgrade && sudo apt autoremove && sudo reboot

usually works fine...?

16

u/ItchyPlant Oct 28 '26 edited Oct 28 '26

Thanks for the illustrative example! So, in this case:

  • What if this was just one of the 50 servers you manage?
  • What if there was nothing to update? The commands would still succeed, and you'd reboot the machine for absolutely no reason.
  • What if you wanted to reboot only when necessary, and only one server at a time to avoid disrupting services?
  • What if something failed halfway through? How would you reliably track which servers succeeded, which failed, and where?
  • What if you needed to run the same procedure again tomorrow without causing unnecessary changes?
  • And where's post-reboot verification?

And BTW, your apt autoremove might even stop and wait for interactive confirmation. Not exactly ideal for automation, is it?

3

u/planeturban Oct 28 '26

That's also assuming you're just running one distribution in your system. And apt/dnf won't update your settings if you need to do that. There are many reasons.

2

u/anaumann Oct 28 '26

So you're rebooting every time you update zsh?

All you ever do is installing packages, you're not generating configuration files for the software you're installing?

Do you like reading logs into which hosts wrote as they pleased only to find out that three out of a hundred hosts failed and it took you an hour to find that out?

You live in an ideal world where every machine really is identical to the next and you don't need config file format A for some servers and a newer format B for others?

1

u/Live_Surround5198 Oct 28 '26

Only on a very limited and specific subset of Linux operating systems. On many it fails badly.

1

u/FarToe1 Oct 28 '26

usually works fine...?

"Usually" doing a lot of heavy lifting there. Good ansible tried to change "usually" into "always"

Others have already given you very good answers, and here's another reason. calling "apt" from within a script is strongly discouraged by apt itself.

WARNING: apt does not have a stable CLI interface. Use with caution in scripts.

125

u/SagaciousZed Oct 28 '26

It's primarily one of safety and idempotency. Running a ansible playbook should result in no work being done on subsequent runs, such the system state matches what is decided in the playbook. If your shell script does all that you now have extra code to maintain to make sure to always works. Bullet proof shell scripts are also difficult to write. Would you rather just maintaining a yaml file with your list of dependencies or manage multiple complex shellscrips?

37

u/red123nax123 Oct 28 '26

This indeed, the template module isn’t just cat > filename.txt. It’s checking whether the file is already existing on the system, whether permissions are correct, easily applying variables, etc. That’s a hell of a bash script to replace a 5 lines of yaml.

Side note is that this mainly works well if you use the correct modules, not just command and bash. Always avoid those if you can do without.

And be aware that Ansible shines with many servers and roles, not just a single server with a single app.

6

u/captkirkseviltwin Oct 29 '26

It's also easier to understand what's going on. A "here doc" for instance takes someone understanding the concept and it's construction, great if you're a Linux admin, less if you're an auditor or non-linux admin. Conversely I had plenty of non-Linux admins be able to look at a lineinfile: or template: stanza and understand exactly what's going on.

14

u/feinorgh Oct 28 '26

The inventory management and passing variables to many hundreds or thousands of machines from a central code repository is also a feature that bash is eminently unsuitable for.

With Ansible, in addition to what's already mentioned, you get remote connection logic, job dispatching, event-based notifications, error handling, structured return data structures, YAML/JSON serialization.

If you're only going to install a package, then Ansible is not the right solution. If you're going to configure and provision many machines in a predictable and consistent way, Ansible is a far better tool than bash scripts.

5

u/aprettyparrot Oct 28 '26

Can confirm, had to make bulletproof bash scripts for years

1

u/a-dot-in-the-sky 12d ago

yes, idempotent is the reason. Unless the bash script written has an algorithm for idempotent.
Ex: just a simple analogy not sure if it will hit the point.
Bash script that is design to download/install an application and restart a service but only once:
- bash script executed, it downloads/install the app and restarts the service without any issues (technically job is done)
- some junior staff, accidentally run the script, it will download and run and install the scripts, and will restart the service, if it's in in Production then I guess users/clients won't be happy
Whereas, deploying and installing the service and restarting it via Ansible.
Ansible, will check if the system already in the desired state. If it is, then it won't do anything.
However, running same Ansible YML 5x, it will lock your keyboard and mouse and ask you to get some coffee and get some fresh Air. lol ;)

14

u/mehx9 Oct 28 '26

Whatever you do, just don’t write bash in ansible.

Like others have said: abstraction.

If you program in Python also it’s dead easy to write extensions and call them from yaml.

6

u/TrueInferno Oct 28 '26

sweats in ansible.builtin.command and ansible.builtin.shell

Kidding, mostly. There are occasionally things where you want to just use a specific shell command to do something, especially w/ non-changing tasks to just get a specific output from a command to work with, but usually there's an ansible module of some sort to do everything. More than once when I wrote something using those two modules I would go do more research and find a proper dedicated module to do what I needed.

I know enough about Python to be dangerous. I really should experiment with making an extension.

2

u/mehx9 Oct 28 '26

To be honest most of us started with ansible.builtin.command/shell at first and asked the same question OP did.

But writing reusable features in Python is pretty easy and once it clicks there is no turning back.

Took me months to get productive with puppet and literally a week to leave years of puppet experience behind 😂

(Still use Puppet but only for exisiting setup)

1

u/weaver_of_cloth Oct 28 '26

Yep, learn every new language by treating it as a wrapper for bash for a while.

5

u/SnooJokes4504 Oct 28 '26

The two biggest wins for Ansible over a bash script is the ability to split out config on a per host/group basis in a straightforward way, and a centralised inventory. That said, if there was a particularly complicated task (eg anything that uses anything more elaborate than a list/array) then I'd always almost exclusively use python or bash.

5

u/N7Valor Oct 28 '26

How do you make it "idempotent" with Bash? Basically the idea that if nothing needs to be changed on a system, then change nothing. If say you try to download a file, sometimes it might throw an error if it already exists. Typically you would need to write a lot of wrapping "if/then" statements.

When you use Ansible native modules, they are more or less idempotent by default. So you can run hundreds of tasks and, assuming it's written correctly, nothing will change on the system and nothing should throw an error.

Ansible Lockdown is a good example of something that performs hundreds of tasks (to apply STIG hardening to RHEL as an example) and should ideally change nothing.

5

u/Proper-Attempt4337 Oct 28 '26

One thing I've found myself doing in the past year is taking a number of legacy bash scripts in my homelab and converting them or folding them into Ansible Playbooks with dynamic inventory. I maintain both the playbooks and standalone bash variants, but for any task where I have a number of targets Ansible is usually the more efficient and reliable way to operate at scale. Even if the scale is only 2 or 3 machines.

4

u/flodabo Oct 28 '26

Becaue with bash you need lot of things yourself that ansible provides. e.g. Bash is not made to do things in an idempotent way by default.

The high level goals of Ansible are described here https://docs.ansible.com/projects/ansible/latest/getting_started/introduction.html

You can of course run plain shell, raw python, whatever else stuff wrapped in ansible using command, shell or similar modules. However you then have to make sure you write proper error handling, make it idempotent, etc. That are things that calling an ansible module mostly solves for you already.

4

u/amarao_san Oct 28 '26

From a decade of use of Ansible.

The great thing about Ansible is that it articulates side effects. > in bash is casual and without proper error handling. file/content is very well articulated.

Ansible falls short in the decision part, but side effects are articulated with excellence.

3

u/Runnergeek Oct 28 '26

This is exactly what I noticed and made me fall in love. I did tons of automation with bash and python. I noticed that the majority of my scripts would end up being error handling and dealing with lots of edge cases. Being able to simply focus on the outcome and not worry about that was an amazing experience.

4

u/iq-0 Oct 28 '26

That’s not why you use Ansible. Ansible is a procedure tool. A well written Ansible playbook should read like a succinctly written procedure that you could perform by hand (minus the templating, but even that should ideally also be human interpretable)

Yes, you can write loops and complex logic, do all kinds of convoluted meta-programming and such. But for our operations teams we try to limit our main playbooks to just simple (but strict) procedures. The technical complexity is abstracted away in roles and a few custom python modules.

3

u/TheTxoof Oct 28 '26

And then there's the fact that you don't need to deeply care what version/distro is running at the other end. If you ask Ansible to get the IP, and it succeedes, you can be sure that you know the IP.

With bash, you would need to verify all the system details yourself and make sure you call the right tools to get your answers. With Ansible, you have the whole Ansible community verifying that the commands run as expected on your endpoints.

3

u/Ill-Ad5760 Oct 28 '26 edited Oct 28 '26

Ich hab früher ( ansible 1.6 - 2.x) immer ein Shebang vorn in die 1. Zeile geschrieben und damit das playbook ausführbar gemacht. Dann konnte ich es wie ein Shellscript aufrufen.

4

u/TrueInferno Oct 28 '26

It's actually a really, really good question because it gets to the heart of how Ansible works and why it's good. Don't feel bad at all!

The thing is? At it's lowest level- to my knowledge- a module is just a Python script (or on Windows machines PowerShell I think) that does certain things based on the input it gets from you and the facts from the host it's working on. Each task consists of Ansible creating a new SSH connection, running the module script, and returning the result.

In that sense, it's not a replacement for writing scripts and running them on machines, but rather an orchestration to run lots of scripts. However, a lot of the tasks that Ansible was made to do are so standardized, it provides those scripts for you as pre-made modules. Not only that, but they are maintained and updated and checked for errors. Then you have all the community collection modules, the manufacturer provided/maintained ones, not to mention all the roles available on Ansible Galaxy and elsewhere!

That means you can usually take a step back and focus on what you want done rather than how you want done- things are now declarative vs imperative. Some modules take it a step further- for example, rather than calling ansible.builtin.dnf or ansible.builtin.apt, you can call ansible.builtin.package which takes the input you give it and looks at the facts from the host to determine which update module to actually use- if it's running on a RHEL machine it'll use dnf, while on Debian etc. it'd use apt.

Not all modules have something like that- for example, there's no overarching module for managing both podman and docker, because a system can have both- but you can use the when keyword to have specific steps only run when applicable, among many other helpful tools.

Going back to the whole "maintained and updated" thing- take that previous statement about the when keyword. A script or playbook you write can be as simple as checking whether it is in the podman server group, since you know and maintain this environment, but a provided module/role can't count on that being there, so it might actually have a very complex check involving looking at package facts.

All of that helps make it so that with Ansible, your job isn't to tell it how to do it, you just tell it what you want done and when and it gets done, without you worrying about all the details about how.

2

u/Live_Surround5198 Oct 28 '26

Ansible was released 14 years ago. The fact that it seems “new” to you and your multiple responses that are getting downvoted suggests you aren’t really familiar with the concepts of automation, idempotent code, portable code, and repeatable code in the modern context.

One can write an Ansible playbook to install a specific package across 3 different Linux os types with a half dozen simple lines of .yaml. The corresponding Bash to do exactly the same with full idempotence would be hundreds of lines.

1

u/emptyDir Oct 28 '26

I genuinely think the best way to answer this question would be to just try writing the bash script. I don't think it would take you too long to find is limitations, and you'd get to experience first hand some of the problems that ansible was designed to solve.

Don't listen to me, though. I apparently only learn things the hard way.

1

u/Forward_Hawk 29d ago

totally agree. plus with version pinning , in ansible you just update variables rather than digging through procedural bash code

1

u/RewardAgitated5520 Oct 28 '26

On top of that different OS versions have different bash versions. Now imagine a bash4 script trying to do some stuff on a host with bash3 only... In general, idempotency is the most important benefit of configuration management - ensure it works and does only the changes it needs.

1

u/serverhorror Oct 28 '26

Because these scripts are already embedded in Ansible.

You don't have to write all the code to make it idempotent.

1

u/Burgergold Oct 28 '26

Existing module managing idempotency, check mode and native inventory

Its also easy to run remotely on linux and even windows

1

u/ipub Oct 28 '26

Bash: Do these steps. Install Nginx, edit the config, start the service. Ansible: Make sure Nginx is installed, the config is correct, and the service is running. Ansible checks the current state and only makes changes when needed. That's idempotency.

1

u/Forward_Hawk 29d ago

ansible good when you handle multiple server and of course idempotentcy is important

1

u/Zesty_IT 26d ago

little late to the party but my two cents using both quite a bit.

Bash is the fast solution to do something, you can call a script with the shell module but that is a quick fix and not idempotent.

Ansible is the tool of choice because if you write a role/playbook correctly, you are describing how you want a group of machines (or one machine) to look. It won't do any additional work or break anything if you set it up properly.

1

u/IT-Dude-42 20d ago

Even later to the party, I do lots of non standard automations, like servicenow -> new microsoft team (all built by ansible). When I started out I did a lot of shell: | <bash script> stuff. Sometimes when I think that way I just point copilot at it and say "convert this to ansible" then if I reuse it anywhere its a role. If I use it more that 2 times it goes into our master collections
I still have playbooks with bash embedded, and because its wrapped in a playbook its self documenting. Love it