Jinja interpreted values in Play.get_vars() or Task.get_vars()

36 views
Skip to first unread message

Didier BOURRIAUD

unread,
May 11, 2021, 5:05:57 AM5/11/21
to Ansible Development
Hi,

I want to fill a custom dashboard with specifics events raise in a playbook, not all tasks that can be confuse output for functionnal users.

To do that, I first developped a role, and include it everytime I want to push an event. This solution works, but introduce so much task in a playbook. I try to handle exceptions too, so I use block with rescue etc... and Playbook become so complex with this approch.

So, after some research, I think that a Callback plugin can answer my needs. The idea is to inject at the plays and tasks levels, a specific var that the callback plugin can catch and react in function.

Playbook Example ( this is the Ansiboad var ):
---
- name: "Callback module test"
  hosts: "localhost"
  gather_facts: no
  vars:
    Ansiboard:
      project: "{{ Proj }}"
      environment: "{{ Env }}"
  tasks:
  - debug:
    msg: "{{ Proj }} - {{ Env }}"
    vars:
      Ansiboard:
        another_project: "{{ Proj }}"
        another_environment: "{{ Env }}"


This playbook is called with this two Extra :
$> ansible-playbook test.yml -e Proj=myproj -e Env=prod

My callback plugin works fine, I can check the presence of the var Ansiboard and apply actions when needed.

The problem is that Jinja templating isn't apply, for example, when I write this :
def v2_playbook_on_play_start(self, play):
  self.playbook_on_play_start(play.name)

  play_vars = play.get_vars()
  if "Ansiboard" in play_vars:
    ansiconf = play_vars["Ansiboard"]
    project = ansiconf["project"]



The value in the project variable is litteraly : {{ Proj }}

Someone knows how I can retreive the final value after the Jinja Template apply ? How can I launch the Jinja templating engine ? Did I need to get the VariableManager of the Play / Task ? I very confused how to acheive my need.

Best regards,
Didier Bourriaud from Kosmos.

Didier BOURRIAUD

unread,
May 11, 2021, 6:37:25 AM5/11/21
to Ansible Development
Hi again,

I found a way to apply the Jinja template on the string. After some research, Templar object works. I don'y really know by the way of this is the best practice to do this.

So, the modified Code :
from ansible.template import Templar

def v2_playbook_on_play_start(self, play):
  self.playbook_on_play_start(play.name)
  
  templar = Templar(loader=play.get_loader(), variables=play.get_variable_manager().get_vars(play=self.play))

  play_vars = play.get_vars()
  if "Ansiboard" in play_vars:
    ansiconf = play_vars["Ansiboard"]
    project = templar.template(ansiconf["project"])


And now, the content of project var is well : myproj

Don't hesitate to correct or purpose a better way to acheive this.
Reply all
Reply to author
Forward
0 new messages