Skip to content

Instantly share code, notes, and snippets.

@halberom
Last active November 22, 2021 10:37
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save halberom/f4515e6b9d977f64294d to your computer and use it in GitHub Desktop.
Save halberom/f4515e6b9d977f64294d to your computer and use it in GitHub Desktop.
ansible - example of custom module to gather info on installed packages
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Note: only works on RedHat family
# This library should be saved to the 'library/' folder relative to your playbooks/inventory
import rpm
def _check_installed(module):
ts = rpm.TransactionSet()
mi = ts.dbMatch()
results = []
for h in mi:
results.append(h['name'])
return { 'ansible_facts': { 'packages_installed': results } }
def main():
module = AnsibleModule(
argument_spec = dict(
),
supports_check_mode = True,
)
data = _check_installed(module)
module.exit_json(**data)
from ansible.module_utils.basic import *
main()
- hosts: foo
tasks:
- gather_installed:
- debug: var=hostvars[inventory_hostname]['packages_installed']
- debug: msg='do something when httpd is installed'
when: "'httpd' in packages_installed"
PLAY [foo] ********************************************************************
GATHERING FACTS ***************************************************************
ok: [localhost]
TASK: [gather_installed ] *****************************************************
ok: [localhost]
TASK: [debug var=hostvars[inventory_hostname]['packages_installed']] **********
ok: [localhost] => {
"hostvars[inventory_hostname]['packages_installed']": [
"perl-version",
"xz-lzma-compat",
"fontpackages-filesystem",
"perl-Digest-SHA",
"openconnect",
"libattr",
...
"python-pycurl",
"dhclient",
"libICE"
]
}
TASK: [debug msg='do something when httpd is installed'] **********************
ok: [localhost] => {
"msg": "do something when httpd is installed"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment