Skip to content

Instantly share code, notes, and snippets.

@whereismyjetpack
Created October 28, 2022 18:01
Show Gist options
  • Save whereismyjetpack/12e5ef552f3226ca8bd3a73a7972a5c1 to your computer and use it in GitHub Desktop.
Save whereismyjetpack/12e5ef552f3226ca8bd3a73a7972a5c1 to your computer and use it in GitHub Desktop.
Ansible solr_password lookup
# Inspired by https://gist.github.com/eribeiro/aaa3f7e62750aa8a5799dde035179010
from __future__ import absolute_import, division, print_function
__metaclass__ = type
DOCUMENTATION = """
name: solr_password
short_description: Set Solr Authentication String for use in security.json
options:
_terms:
description:
- Solr Password as a string
required: True
salt:
description: Salt to use when hashing the password. If a salt is not provided a new one will be used each time
type: raw
required: False
"""
EXAMPLES = """
- name: Basic usage
ansible.builtin.debug:
msg: "{{ lookup('solr_password', 'asdf') }}"
- name: With Salt
ansible.builtin.debug:
msg: "{{ lookup('solr_password', 'asdf', salt="salty") }}"
"""
RETURN = """
_list:
description:
- Values from the environment variables.
type: string
"""
from jinja2.runtime import Undefined
from ansible.errors import AnsibleUndefinedVariable
from ansible.plugins.lookup import LookupBase
from ansible.utils import py3compat
import secrets
import sys
from hashlib import sha256
from base64 import b64encode, b64decode
class LookupModule(LookupBase):
def run(self, terms, variables, **kwargs):
self.set_options(var_options=variables, direct=kwargs)
ret = []
salt = self.get_option("salt")
for term in terms:
if salt is None:
salt = secrets.token_bytes(32)
else:
salt = bytes(salt, "utf-8")
m = sha256()
m.update(salt + term.encode("utf-8"))
digest = m.digest()
m = sha256()
m.update(digest)
digest = m.digest()
cypher = b64encode(digest).decode("utf-8")
salt = b64encode(salt).decode("utf-8")
ret.append(f"{cypher} {salt}")
return ret
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment