-
chevron_right
Ansible module_defaults and a lookup plugin
pubsub.slavino.sk / jpmens.net · Tuesday, 4 October, 2022 - 22:00 · 1 minute
When calling Ansible modules frequently with similar parameters, module_defaults can save on typing and, almost more importantly, improve on clarity by defining default values for modules I use in a play.
Let’s look at a small example in which I want to clear records for a host from a
dynamic DNS
server and then add it in again. In all invocations of the
nsupdate
module I would need to specify key name, algorithm, server, etc., but through the use of
module_defaults
I can set default values and no longer have to specify these repetitively on individual tasks.
-hosts:allvars_files:dns-params.ymlmodule_defaults:community.general.nsupdate:key_algorithm:"hmac-sha256"key_name:"{{tsig_key_name}}"key_secret:"{{tsig_key_secret}}"server:"{{dns_server}}"protocol:"tcp"ttl:60zone:"example.org"tasks:-name:Clean old records from DNScommunity.general.nsupdate:record:"www.example.org."state:absent-name:Add IPv4 addresses to DNScommunity.general.nsupdate:record:"www.example.org."type:"A"value:"192.0.2.43"state:present
What I wasn’t aware of and learned today via Ton , is that the module defaults can also be provided via a lookup plugin. I whipped up a simple example to illustrate this.
The lookup plugin (
md.py
) returns a dictionary of values. It doesn’t use terms passed to it but easily could, e.g. to have the plugin return classes of values, etc.
fromansible.errorsimportAnsibleError,AnsibleParserErrorfromansible.plugins.lookupimportLookupBaseclassLookupModule(LookupBase):defrun(self,terms,variables=None,**kwargs):data={"content":"Rijsttafel","mode":"0400",}ret=[data]returnret
The playbook shows how this plugin is used to feed
module_defaults
for the
copy
module, and it then invokes
copy
twice:
-hosts:localhostmodule_defaults:copy:"{{lookup('md')}}"tasks:-copy:content="Hello" dest="a" mode=0444-copy:dest="b"
The result: two files with distinct permissions and content:
$ls-l ?
-r--r--r-- 1 jpm staff 5 Oct 5 18:32 a
-r-------- 1 jpm staff 10 Oct 5 18:32 b
$cat a
Hello
$cat b
Rijsttafel
The second file
b
has permissions 0400 and content “Rijsttafel” set from the lookup, and both have these defaults overridden for file
a
.
Značky: #Network