Skip to content

Instantly share code, notes, and snippets.

@filipenf
Last active March 15, 2024 15:19
Show Gist options
  • Save filipenf/f0f5ffe7de4a9e1400ceefc32ee683fe to your computer and use it in GitHub Desktop.
Save filipenf/f0f5ffe7de4a9e1400ceefc32ee683fe to your computer and use it in GitHub Desktop.
Ansible inventory comparison

Usage:

1. Create a virtualenv with deepdiff

requirements:

PyYAML==3.13
deepdiff==3.3.0
jsonpickle==1.0

2. Export the inventories to be compared using the ansible-inventory tool:

ansible-inventory -i ./originalinventory/hosts --playbook-dir . -y --list --export > /tmp/original-inventory.yml
ansible-inventory -i ./newinventory/hosts --playbook-dir . -y --list --export > /tmp/new-inventory.yml

this will export the whole inventory, with groups and group vars in the yaml format

3. run the compare tool

python compare.py /tmp/new-inventory.yml /tmp/original-inventory.yml

it will print what changed in the 2 inventories (groups/variables/hosts added and removed)

#!/usr/bin/env python
## This script loads 2 ansible-exported yaml inventory files (passed as args)
## and uses deepdiff to compare their structures
## it is useful to compare big changes to group variables or inventory structure
import yaml
import sys
from deepdiff import DeepDiff
from pprint import pprint
class VaultTag(yaml.YAMLObject):
yaml_tag = u'!vault'
def __init__(self, value):
self.value = value
def __repr__(self):
return self.value
@classmethod
def from_yaml(cls, loader, node):
return node.value
@classmethod
def to_yaml(cls, dumper, data):
return dumper.represent_scalar(cls.yaml_tag, data.value)
yaml.SafeLoader.add_constructor('!vault', VaultTag.from_yaml)
yaml.SafeDumper.add_multi_representer(VaultTag, VaultTag.to_yaml)
t1 = yaml.safe_load(open(sys.argv[1]))
t2 = yaml.safe_load(open(sys.argv[2]))
diff = DeepDiff(t1, t2, ignore_order=True)
pprint(diff)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment