Skip to content

Instantly share code, notes, and snippets.

@geowa4
Created June 19, 2019 12:32
Show Gist options
  • Save geowa4/bad9b2e985a6b8a8072897708a58a3ba to your computer and use it in GitHub Desktop.
Save geowa4/bad9b2e985a6b8a8072897708a58a3ba to your computer and use it in GitHub Desktop.
Ansible vars plugin to use Sops instead of Vault
import os
import subprocess
from ansible.errors import AnsibleParserError
from ansible.module_utils._text import to_native
from ansible.plugins.vars import BaseVarsPlugin
from ansible.inventory.host import Host
from ansible.inventory.group import Group
from ansible.utils.vars import combine_vars
from ansible.parsing.utils.yaml import from_yaml
class VarsModule(BaseVarsPlugin):
"""
Based on the built-in vars_plugin host_group_vars.py
(https://github.com/ansible/ansible/blob/devel/lib/ansible/plugins/vars/host_group_vars.py)
but loads secrets encrypted via sops and stored in
group_secrets or host_secrets.
"""
def get_vars(self, loader, path, entities):
if not isinstance(entities, list):
entities = [entities]
super().get_vars(loader, path, entities)
data = {}
for entity in entities:
if isinstance(entity, Host):
subdir = 'host_secrets'
elif isinstance(entity, Group):
subdir = 'group_secrets'
else:
raise AnsibleParserError(
"Supplied entity must be Host or Group, got {} instead".
format(type(entity)))
# avoid 'chroot' type inventory hostnames /path/to/chroot
if not entity.name.startswith(os.path.sep):
try:
found_files = []
opath = os.path.realpath(
os.path.join(self._basedir, subdir))
if os.path.exists(opath):
if os.path.isdir(opath):
self._display.debug(
"\tprocessing dir {}".format(opath))
found_files = loader.find_vars_files(
opath, entity.name)
else:
self._display.warning(
("Found {} that is not a directory, "
"skipping: {}").format(subdir, opath))
self._display.warning(found_files)
for found in found_files:
sops_result = subprocess.run(
['sops', '--decrypt', found],
check=True,
stdout=subprocess.PIPE)
new_data = from_yaml(
sops_result.stdout.decode('utf-8'),
file_name=opath)
if new_data:
data = combine_vars(data, new_data)
except Exception as e:
raise AnsibleParserError(to_native(e))
return data
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment