The Level Up team saw a question recently around how to reverse-engineer an Ansible playbook, in order to try to validate it and then modify it for one’s own purposes.
Upfront, we’d generally recommend a good-better-best approach to unraveling anybody else’s Ansible code (much of this can be applied to your own Ansible code too). If it were us, we’d also consider refactoring a standalone playbook into a role in the process of walking through it, to help with greater modularity and portability, etc. But we feel we must say that pretty much always, there’s simply no getting around the need to run Ansible code on a valid test node at some point, if you want to understand how it actually works.
Tips for “Reverse-Engineering” Ansible Code
1) Know your main CLI program options:
ansible-playbook
has a few nifty flags:
--syntax-check
(will it even probably run?)
--list-tasks
(what tasks are going to run, including showing you if multiple plays on different hosts are involved)
--list-tags
(the presence of tags implies that the author(s) may have anticipated that parts of this playbook– but not others– might be run together in at least certain situations)
--step
(go one task at a time)
ansible-navigator
also gives you a lot of similar features with the run, replay, and lint subcommands, and lets you use execution environment images too.
2) Be ready to lean on helper Ansible CLI programs as needed:
ansible-lint
has a lot of syntactic sugar and best practices from the community.
ansible-doc <MODULE_NAME> -s
shows a snippet of how to work with that particular module’s parameters. If invoked without any flags, this program opens a pager, which you can read to see task examples, which can be handy, as opposed to having to reference external systems, which can often be unreliable and incomplete.
3) Figure out your concrete goals for this new and exotic Ansible code:
One of the first questions to ask yourself: “Would I run this Ansible code in prod right now?” If not, why not? What specifically gives you pause? Those are going to be your first blocks to focus on.
4) Test the Ansible code somewhere safe
Yep. Fundamentally, we’re talking about static vs. dynamic code analysis. And potentially also about unit vs. functional testing. This is true for most modern software development being done today, and it’s basically no different with Ansible. You have to run Ansible code somewhere to know with any confidence what it’s probably going to do anywhere else. Beyond utterly basic task definitions, “reverse-engineering” Ansible code without testing it in the real world probably can’t be done with any kind of guarantees.