Ansible Conditionals quick dive
I feel like , this is too much , too much typing to do something so simple:
Somehow i think this should simplified , i think the assertion at the top is too much to test something so simple , I’d like something like:
If you not gonna reuse passwd_exist anymore what’s the point of another task to get this done.
Now I’m by no means an Ansible expert but i was wondering how complicated would it be to implement something like that , i went to freenode and the confirmed the only way to get this done was by having that “check” task :
And the conversation carried on , anyways i wanted to good opportunity to hack around Ansible , so i thought this would be idea.
Step 1:
Find where the “when:” statement on a task is evaluated:
As Ansible is python , I was pretty sure i could find it in /usr/lib/python*** and I did something similar to:
grep -Ri "when:" *
Which resulted in:
What you gonna see next it’s an idea, a mock if you may but this isn’t “production ready” by no means! , it’s just a hack.
When you open that file you will find indeed a Conditional class that deals with the “when:” tag and many others :
The fact that they’re linking jinja made me feel i was in the right path .
So there’s two main functions that pass your “when:” tag to jinja and those are:
evaluate_conditional:
Which basically iterate through all the conditionals for ex:
when:
- ' 1 == 1'
- ' 20 %2 ==0'
And passes to “_check_conditional”
and _check_conditional runs it through j2 , so i will something to capture my “when:” statement and hook it with something else
- is my “shell:” tag in one of the conditions
- if it is: os.system(the command)
- if response code isn’t zero
- raise some exception
- else pretend evetyhing is fine!
And this sort of works , considering this task
Obviously that will fail because the file “passw” doesn’t exist:
Obviously the file /tmp/example wasn’t created either
But with the right when:shell :
we get:
and the file /tmp/example , was created just fine
One of the good things of Ansible being so lean is that you can actually make changes to it without too much hassle , this is a simple idea and i don’t know wether it’s useful or not , but it’s nice to know where things are with a little exploring.