Skip to content

Instantly share code, notes, and snippets.

@arbabnazar
Forked from tgerla/app_defaults.py
Created January 14, 2023 18:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arbabnazar/b0ab41115dc9018ef2c675397cf8a05a to your computer and use it in GitHub Desktop.
Save arbabnazar/b0ab41115dc9018ef2c675397cf8a05a to your computer and use it in GitHub Desktop.
example lookup plugin for ansible
import ansible.utils as utils
#
# Put this file in lookup_plugins/ alongside your playbooks.
#
# Lookup plugins can be called two ways: via with_ as a task loop
# construct, or via lookup('name').
#
# You can find the code for the basic lookup plugins here:
# v1: https://github.com/ansible/ansible/tree/devel/v1/ansible/runner/lookup_plugins
# v2: https://github.com/ansible/ansible/tree/devel/lib/ansible/plugins/lookup
#
class LookupModule(object):
def __init__(self, basedir=None, **kwargs):
self.basedir = basedir
def run(self, terms, inject=None, **kwargs):
# "listify" basically dereferences a variable name passed into the plugin
# ie: with_app_defaults:
# - foo
# - bar
#
# ...where foo and bar are data structures.
#
terms = utils.listify_lookup_plugin_terms(terms, self.basedir, inject)
apps = utils.listify_lookup_plugin_terms(terms[0], self.basedir, inject)
app_defaults = utils.listify_lookup_plugin_terms(terms[1], self.basedir, inject)
# everything below is very specific to the application --you'll need to change
# it to suit your needs. perhaps you could use it to merge the global security
# groups data structure with the region-specific list and return a flattened list.
results = []
# .......
# each item in the *_packages list -- can be either a string, to take the default
# instance from app_defaults, or a dict, in which case we might specify a list of
# instances (ports)
for x in apps:
# if hostvars specifies an instance list, use it. if not, take the first one
# from the defaults.
name = x['name']
if 'instances' in x:
instances = x['instances']
else:
instances = [app_defaults[name]['ports'][0]]
if name not in app_defaults:
print "WARNING: invalid application name:", x
continue
for instance in instances:
y = dict(app_defaults[name])
del y['ports']
y['instance'] = instance
y['app_name'] = name
results.append(y)
return results
# this is just to test the custom lookup plugin
- hosts: all
gather_facts: false
connection: local
vars_files:
- vars/app_defaults.yml
tasks:
- name: shut down services (app)
debug: msg="shutting down {{item.app_name}} on port {{item.instance}}"
with_app_defaults:
- apps_packages
- app_defaults
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment