Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access playbook variables from custom module in Ansible [duplicate]

Tags:

ansible

I'm writing a custom module in Ansible, specific to a Playbook. Is it possible to directly access a playbook variable, without needing to pass it to the task as a parameter?

like image 312
Santiago Palladino Avatar asked Aug 19 '15 18:08

Santiago Palladino


People also ask

How do you pass multiple extra variables in ansible playbook?

To pass a value to nodes, use the --extra-vars or -e option while running the Ansible playbook, as seen below. This ensures you avoid accidental running of the playbook against hardcoded hosts.

How do you pass extra arguments in ansible playbook?

Ansible treats values of the extra variables as strings. To pass values that are not strings, we need to use JSON format. To pass extra vars in JSON format we need to enclose JSON in quotation marks: ansible-playbook extra_var_json.

How do you access variables in ansible?

To define a variable in a playbook, simply use the keyword vars before writing your variables with indentation. To access the value of the variable, place it between the double curly braces enclosed with quotation marks. In the above playbook, the greeting variable is substituted by the value Hello world!


1 Answers

It is not possible, because the module is executed remotely and all the variables are not available unless explicitly passed.

I had the same question a while ago and Pruce P offered an interesting workaround in his answer.

Though I had another idea in the meantime, but this is only theoretical and never tested: Beside normal modules, Ansible has a special kind of module: action plugins. (...not documented) They are used exactly like modules but are executed locally. Since they run locally they do have access to Ansibles runner object which holds all the group/host vars etc.

The cool thing is, you can call a module programmatically from the action plugin. So you could have a small wrapper action plugin which then calls the actual module and passes all (required) vars to it. Since it is undocumented you need to look at the available plugins. For instance here is one which calls a module: assemble.

I have written something here which interacts with vars from the runner object.

like image 71
udondan Avatar answered Sep 22 '22 19:09

udondan