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?
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.
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.
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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With