fix(vpn-node-config): resolve ansible-lint violations
OpenVPN Ansible / Deploy VPN Networking and OpenVPN (push) Canceled after 0s
OpenVPN Ansible / Generate SBOM (push) Canceled after 0s
OpenVPN Ansible / Scan SBOM with Trivy (push) Canceled after 0s
OpenVPN Ansible / Ansible Syntax Check (push) Canceled after 38s
OpenVPN Ansible / Ansible Lint (push) Canceled after 40s
OpenVPN Ansible / Deploy VPN Networking and OpenVPN (push) Canceled after 0s
OpenVPN Ansible / Generate SBOM (push) Canceled after 0s
OpenVPN Ansible / Scan SBOM with Trivy (push) Canceled after 0s
OpenVPN Ansible / Ansible Syntax Check (push) Canceled after 38s
OpenVPN Ansible / Ansible Lint (push) Canceled after 40s
This commit is contained in:
+117
@@ -0,0 +1,117 @@
|
||||
#
|
||||
# Copyright (c) 2025, Felix Fontein <felix@fontein.de>
|
||||
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
DOCUMENTATION = r"""
|
||||
name: binary_file
|
||||
author: Felix Fontein (@felixfontein)
|
||||
short_description: Read binary file and return it Base64 encoded
|
||||
version_added: 11.2.0
|
||||
description:
|
||||
- This lookup returns the contents from a file on the Ansible controller's file system.
|
||||
- The file is read as a binary file and its contents are returned Base64 encoded.
|
||||
This is similar to using P(ansible.builtin.file#lookup) combined with P(ansible.builtin.b64encode#filter),
|
||||
except that P(ansible.builtin.file#lookup) does not support binary files as it interprets the contents as UTF-8,
|
||||
which can cause the wrong content being Base64 encoded.
|
||||
options:
|
||||
_terms:
|
||||
description:
|
||||
- Paths of the files to read.
|
||||
- Relative paths will be searched for in different places. See R(Ansible task paths, playbook_task_paths) for more details.
|
||||
required: true
|
||||
type: list
|
||||
elements: str
|
||||
not_exist:
|
||||
description:
|
||||
- Determine how to react if the specified file cannot be found.
|
||||
type: str
|
||||
choices:
|
||||
error: Raise an error.
|
||||
empty: Return an empty string for the file.
|
||||
empty_str:
|
||||
- Return the string C(empty) for the file.
|
||||
- This cannot be confused with Base64 encoding due to the missing padding.
|
||||
default: error
|
||||
notes:
|
||||
- This lookup does not understand 'globbing' - use the P(ansible.builtin.fileglob#lookup) lookup instead.
|
||||
seealso:
|
||||
- plugin: ansible.builtin.b64decode
|
||||
plugin_type: filter
|
||||
description: >-
|
||||
The b64decode filter can be used to decode Base64 encoded data.
|
||||
Note that Ansible cannot handle binary data, the data will be interpreted as UTF-8 text!
|
||||
- plugin: ansible.builtin.file
|
||||
plugin_type: lookup
|
||||
description: You can use this lookup plugin to read text files from the Ansible controller.
|
||||
- module: ansible.builtin.slurp
|
||||
description: >-
|
||||
Also allows to read binary files Base64 encoded, but from remote targets.
|
||||
With C(delegate_to: localhost) can be redirected to run on the controller, but you have to know the path to the file to read.
|
||||
Both this plugin and P(ansible.builtin.file#lookup) use some search path logic to for example also find files in the C(files)
|
||||
directory of a role.
|
||||
- ref: playbook_task_paths
|
||||
description: Search paths used for relative files.
|
||||
- module: community.general.write_binary_file
|
||||
"""
|
||||
|
||||
EXAMPLES = r"""
|
||||
---
|
||||
- name: Output Base64 contents of binary files on screen
|
||||
ansible.builtin.debug:
|
||||
msg: "Content: {{ lookup('community.general.binary_file', item) }}"
|
||||
loop:
|
||||
- some-binary-file.bin
|
||||
"""
|
||||
|
||||
RETURN = r"""
|
||||
_raw:
|
||||
description:
|
||||
- Base64 encoded content of requested files, or an empty string resp. the string C(empty), depending on the O(not_exist) option.
|
||||
- This list contains one string per element of O(_terms) in the same order as O(_terms).
|
||||
type: list
|
||||
elements: str
|
||||
returned: success
|
||||
"""
|
||||
|
||||
import base64
|
||||
|
||||
from ansible.errors import AnsibleLookupError
|
||||
from ansible.plugins.lookup import LookupBase
|
||||
from ansible.utils.display import Display
|
||||
|
||||
from ansible_collections.community.general.plugins.plugin_utils._lookup import check_for_wrong_terms
|
||||
|
||||
display = Display()
|
||||
|
||||
|
||||
class LookupModule(LookupBase):
|
||||
def run(self, terms, variables=None, **kwargs):
|
||||
self.set_options(var_options=variables, direct=kwargs)
|
||||
check_for_wrong_terms(self, direct=kwargs)
|
||||
not_exist = self.get_option("not_exist")
|
||||
|
||||
result = []
|
||||
for term in terms:
|
||||
display.debug(f"Searching for binary file: {term!r}")
|
||||
path = self.find_file_in_search_path(variables, "files", term, ignore_missing=(not_exist != "error"))
|
||||
display.vvvv(f"community.general.binary_file lookup using {path} as file")
|
||||
|
||||
if not path:
|
||||
if not_exist == "empty":
|
||||
result.append("")
|
||||
continue
|
||||
if not_exist == "empty_str":
|
||||
result.append("empty")
|
||||
continue
|
||||
raise AnsibleLookupError(f"Could not locate file in community.general.binary_file lookup: {term}")
|
||||
|
||||
try:
|
||||
with open(path, "rb") as f:
|
||||
result.append(base64.b64encode(f.read()).decode("utf-8"))
|
||||
except Exception as exc:
|
||||
raise AnsibleLookupError(f"Error while reading {path}: {exc}") from exc
|
||||
|
||||
return result
|
||||
+316
@@ -0,0 +1,316 @@
|
||||
# Copyright (c) 2022, Jonathan Lung <lungj@heresjono.com>
|
||||
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
from __future__ import annotations
|
||||
|
||||
DOCUMENTATION = r"""
|
||||
name: bitwarden
|
||||
author:
|
||||
- Jonathan Lung (@lungj) <lungj@heresjono.com>
|
||||
requirements:
|
||||
- bw (command line utility)
|
||||
- be logged into bitwarden
|
||||
- bitwarden vault unlocked
|
||||
- E(BW_SESSION) environment variable set
|
||||
short_description: Retrieve secrets from Bitwarden
|
||||
version_added: 5.4.0
|
||||
description:
|
||||
- Retrieve secrets from Bitwarden.
|
||||
options:
|
||||
_terms:
|
||||
description: Key(s) to fetch values for from login info.
|
||||
required: true
|
||||
type: list
|
||||
elements: str
|
||||
search:
|
||||
description:
|
||||
- Field to retrieve, for example V(name) or V(id).
|
||||
- If set to V(id), only zero or one element can be returned. Use the Jinja C(first) filter to get the only list element.
|
||||
- If set to V(None) or V(''), or if O(_terms) is empty, records are not filtered by fields.
|
||||
type: str
|
||||
default: name
|
||||
version_added: 5.7.0
|
||||
field:
|
||||
description:
|
||||
- Field to fetch. Leave unset to fetch whole response.
|
||||
- If matching records are found but none of them has this field, the lookup fails.
|
||||
Pass C(errors='ignore') to the lookup to get an empty result instead.
|
||||
Please note that this will also ignores other errors, such as invalid credentials, insufficient access rights, and so on.
|
||||
type: str
|
||||
collection_id:
|
||||
description:
|
||||
- Collection ID to filter results by collection. Leave unset to skip filtering.
|
||||
- O(collection_id) and O(collection_name) are mutually exclusive.
|
||||
type: str
|
||||
version_added: 6.3.0
|
||||
collection_name:
|
||||
description:
|
||||
- Collection name to filter results by collection. Leave unset to skip filtering.
|
||||
- O(collection_id) and O(collection_name) are mutually exclusive.
|
||||
type: str
|
||||
version_added: 10.4.0
|
||||
organization_id:
|
||||
description: Organization ID to filter results by organization. Leave unset to skip filtering.
|
||||
type: str
|
||||
version_added: 8.5.0
|
||||
bw_session:
|
||||
description: Pass session key instead of reading from env.
|
||||
type: str
|
||||
version_added: 8.4.0
|
||||
secret: true
|
||||
result_count:
|
||||
description:
|
||||
- Number of results expected for the lookup query. Task fails if O(result_count) is set but does not match the number
|
||||
of query results. Leave empty to skip this check.
|
||||
type: int
|
||||
version_added: 10.4.0
|
||||
sync:
|
||||
description: Set to C(true) to sync items from the Bitwarden vault in the beginning.
|
||||
type: bool
|
||||
default: false
|
||||
version_added: 13.2.0
|
||||
"""
|
||||
|
||||
EXAMPLES = r"""
|
||||
- name: "Get 'password' from all Bitwarden records named 'a_test'"
|
||||
ansible.builtin.debug:
|
||||
msg: >-
|
||||
{{ lookup('community.general.bitwarden', 'a_test', field='password') }}
|
||||
|
||||
- name: "Get 'password' from Bitwarden record with ID 'bafba515-af11-47e6-abe3-af1200cd18b2'"
|
||||
ansible.builtin.debug:
|
||||
msg: >-
|
||||
{{ lookup('community.general.bitwarden', 'bafba515-af11-47e6-abe3-af1200cd18b2', search='id', field='password') | first }}
|
||||
|
||||
- name: "Get 'password' from all Bitwarden records named 'a_test' from collection"
|
||||
ansible.builtin.debug:
|
||||
msg: >-
|
||||
{{ lookup('community.general.bitwarden', 'a_test', field='password', collection_id='bafba515-af11-47e6-abe3-af1200cd18b2') }}
|
||||
|
||||
- name: "Get list of all full Bitwarden records named 'a_test'"
|
||||
ansible.builtin.debug:
|
||||
msg: >-
|
||||
{{ lookup('community.general.bitwarden', 'a_test') }}
|
||||
|
||||
- name: "Get custom field 'api_key' from all Bitwarden records named 'a_test'"
|
||||
ansible.builtin.debug:
|
||||
msg: >-
|
||||
{{ lookup('community.general.bitwarden', 'a_test', field='api_key') }}
|
||||
|
||||
- name: "Get 'password' from all Bitwarden records named 'a_test', using given session key"
|
||||
ansible.builtin.debug:
|
||||
msg: >-
|
||||
{{ lookup('community.general.bitwarden', 'a_test', field='password', bw_session='bXZ9B5TXi6...') }}
|
||||
|
||||
- name: "Get all Bitwarden records from collection"
|
||||
ansible.builtin.debug:
|
||||
msg: >-
|
||||
{{ lookup('community.general.bitwarden', None, collection_id='bafba515-af11-47e6-abe3-af1200cd18b2') }}
|
||||
|
||||
- name: "Get all Bitwarden records from collection"
|
||||
ansible.builtin.debug:
|
||||
msg: >-
|
||||
{{ lookup('community.general.bitwarden', None, collection_name='my_collections/test_collection') }}
|
||||
|
||||
- name: "Get Bitwarden record named 'a_test', ensure there is exactly one match"
|
||||
ansible.builtin.debug:
|
||||
msg: >-
|
||||
{{ lookup('community.general.bitwarden', 'a_test', result_count=1) }}
|
||||
"""
|
||||
|
||||
RETURN = r"""
|
||||
_raw:
|
||||
description:
|
||||
- A one-element list that contains a list of requested fields or JSON objects of matches.
|
||||
- If you use C(query), you get a list of lists. If you use C(lookup) without C(wantlist=true), this always gets reduced
|
||||
to a list of field values or JSON objects.
|
||||
type: list
|
||||
elements: list
|
||||
"""
|
||||
|
||||
from subprocess import PIPE, Popen
|
||||
|
||||
from ansible.errors import AnsibleError, AnsibleOptionsError
|
||||
from ansible.module_utils.common.text.converters import to_bytes, to_text
|
||||
from ansible.parsing.ajson import AnsibleJSONDecoder
|
||||
from ansible.plugins.lookup import LookupBase
|
||||
|
||||
from ansible_collections.community.general.plugins.plugin_utils._lookup import check_for_wrong_terms
|
||||
|
||||
|
||||
class BitwardenException(AnsibleError):
|
||||
pass
|
||||
|
||||
|
||||
class Bitwarden:
|
||||
def __init__(self, path="bw"):
|
||||
self._cli_path = path
|
||||
self._session = None
|
||||
|
||||
@property
|
||||
def cli_path(self):
|
||||
return self._cli_path
|
||||
|
||||
@property
|
||||
def session(self):
|
||||
return self._session
|
||||
|
||||
@session.setter
|
||||
def session(self, value):
|
||||
self._session = value
|
||||
|
||||
@property
|
||||
def unlocked(self):
|
||||
out, err = self._run(["status"], stdin="")
|
||||
decoded = AnsibleJSONDecoder().raw_decode(out)[0]
|
||||
return decoded["status"] == "unlocked"
|
||||
|
||||
def sync(self):
|
||||
out, err = self._run(["sync"], stdin="")
|
||||
return out
|
||||
|
||||
def _run(self, args, stdin=None, expected_rc=0):
|
||||
if self.session:
|
||||
args += ["--session", self.session]
|
||||
|
||||
p = Popen([self.cli_path] + args, stdout=PIPE, stderr=PIPE, stdin=PIPE)
|
||||
out, err = p.communicate(to_bytes(stdin))
|
||||
rc = p.wait()
|
||||
if rc != expected_rc:
|
||||
if len(args) > 2 and args[0] == "get" and args[1] == "item" and b"Not found." in err:
|
||||
return "null", ""
|
||||
raise BitwardenException(err)
|
||||
return to_text(out, errors="surrogate_or_strict"), to_text(err, errors="surrogate_or_strict")
|
||||
|
||||
def _get_matches(self, search_value, search_field, collection_id=None, organization_id=None):
|
||||
"""Return matching records whose search_field is equal to key."""
|
||||
|
||||
# Prepare set of params for Bitwarden CLI
|
||||
if search_field == "id":
|
||||
params = ["get", "item", search_value]
|
||||
else:
|
||||
params = ["list", "items"]
|
||||
if search_value:
|
||||
params.extend(["--search", search_value])
|
||||
|
||||
if collection_id:
|
||||
params.extend(["--collectionid", collection_id])
|
||||
if organization_id:
|
||||
params.extend(["--organizationid", organization_id])
|
||||
|
||||
out, err = self._run(params)
|
||||
|
||||
# This includes things that matched in different fields.
|
||||
initial_matches = AnsibleJSONDecoder().raw_decode(out)[0]
|
||||
|
||||
if search_field == "id":
|
||||
if initial_matches is None:
|
||||
initial_matches = []
|
||||
else:
|
||||
initial_matches = [initial_matches]
|
||||
|
||||
# Filter to only include results from the right field, if a search is requested by value or field
|
||||
return [
|
||||
item
|
||||
for item in initial_matches
|
||||
if not search_value or not search_field or item.get(search_field) == search_value
|
||||
]
|
||||
|
||||
def get_field(self, field, search_value, search_field="name", collection_id=None, organization_id=None):
|
||||
"""Return a list of the specified field for records whose search_field match search_value
|
||||
and filtered by collection if collection has been provided.
|
||||
|
||||
If field is None, return the whole record for each match.
|
||||
"""
|
||||
matches = self._get_matches(search_value, search_field, collection_id, organization_id)
|
||||
if not field:
|
||||
return matches
|
||||
field_matches = []
|
||||
for match in matches:
|
||||
# if there are no custom fields, then `match` has no key 'fields'
|
||||
if "fields" in match:
|
||||
custom_field_found = False
|
||||
for custom_field in match["fields"]:
|
||||
if field == custom_field["name"]:
|
||||
field_matches.append(custom_field["value"])
|
||||
custom_field_found = True
|
||||
break
|
||||
if custom_field_found:
|
||||
continue
|
||||
if "login" in match and field in match["login"]:
|
||||
field_matches.append(match["login"][field])
|
||||
continue
|
||||
if field in match:
|
||||
field_matches.append(match[field])
|
||||
continue
|
||||
|
||||
if matches and not field_matches:
|
||||
raise AnsibleError(f"field {field} does not exist in {search_value}")
|
||||
|
||||
return field_matches
|
||||
|
||||
def get_collection_ids(self, collection_name: str, organization_id=None) -> list[str]:
|
||||
"""Return matching IDs of collections whose name is equal to collection_name."""
|
||||
|
||||
# Prepare set of params for Bitwarden CLI
|
||||
params = ["list", "collections", "--search", collection_name]
|
||||
|
||||
if organization_id:
|
||||
params.extend(["--organizationid", organization_id])
|
||||
|
||||
out, err = self._run(params)
|
||||
|
||||
# This includes things that matched in different fields.
|
||||
initial_matches = AnsibleJSONDecoder().raw_decode(out)[0] # type: ignore[operator]
|
||||
|
||||
# Filter to only return the ID of a collections with exactly matching name
|
||||
return [item["id"] for item in initial_matches if str(item.get("name")).lower() == collection_name.lower()]
|
||||
|
||||
|
||||
class LookupModule(LookupBase):
|
||||
def run(self, terms=None, variables=None, **kwargs):
|
||||
self.set_options(var_options=variables, direct=kwargs)
|
||||
check_for_wrong_terms(self, direct=kwargs)
|
||||
field = self.get_option("field")
|
||||
search_field = self.get_option("search")
|
||||
collection_id = self.get_option("collection_id")
|
||||
collection_name = self.get_option("collection_name")
|
||||
organization_id = self.get_option("organization_id")
|
||||
result_count = self.get_option("result_count")
|
||||
_bitwarden.session = self.get_option("bw_session")
|
||||
sync = self.get_option("sync")
|
||||
|
||||
if not _bitwarden.unlocked:
|
||||
raise AnsibleError("Bitwarden Vault locked. Run 'bw unlock'.")
|
||||
|
||||
if sync:
|
||||
_bitwarden.sync()
|
||||
|
||||
if not terms:
|
||||
terms = [None]
|
||||
|
||||
if collection_name and collection_id:
|
||||
raise AnsibleOptionsError("'collection_name' and 'collection_id' are mutually exclusive!")
|
||||
elif collection_name:
|
||||
collection_ids = _bitwarden.get_collection_ids(collection_name, organization_id)
|
||||
if not collection_ids:
|
||||
raise BitwardenException("No matching collections found!")
|
||||
else:
|
||||
collection_ids = [collection_id]
|
||||
|
||||
results = [
|
||||
_bitwarden.get_field(field, term, search_field, collection_id, organization_id)
|
||||
for collection_id in collection_ids
|
||||
for term in terms
|
||||
]
|
||||
|
||||
for result in results:
|
||||
if result_count is not None and len(result) != result_count:
|
||||
raise BitwardenException(
|
||||
f"Number of results doesn't match result_count! ({len(result)} != {result_count})"
|
||||
)
|
||||
|
||||
return results
|
||||
|
||||
|
||||
_bitwarden = Bitwarden()
|
||||
+158
@@ -0,0 +1,158 @@
|
||||
# Copyright (c) 2023, jantari (https://github.com/jantari)
|
||||
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
from __future__ import annotations
|
||||
|
||||
DOCUMENTATION = r"""
|
||||
name: bitwarden_secrets_manager
|
||||
author:
|
||||
- jantari (@jantari)
|
||||
requirements:
|
||||
- bws (command line utility)
|
||||
short_description: Retrieve secrets from Bitwarden Secrets Manager
|
||||
version_added: 7.2.0
|
||||
description:
|
||||
- Retrieve secrets from Bitwarden Secrets Manager.
|
||||
options:
|
||||
_terms:
|
||||
description: Secret ID(s) to fetch values for.
|
||||
required: true
|
||||
type: list
|
||||
elements: str
|
||||
bws_access_token:
|
||||
description: The BWS access token to use for this lookup.
|
||||
env:
|
||||
- name: BWS_ACCESS_TOKEN
|
||||
required: true
|
||||
type: str
|
||||
secret: true
|
||||
"""
|
||||
|
||||
EXAMPLES = r"""
|
||||
- name: Get a secret relying on the BWS_ACCESS_TOKEN environment variable for authentication
|
||||
ansible.builtin.debug:
|
||||
msg: >-
|
||||
{{ lookup("community.general.bitwarden_secrets_manager", "2bc23e48-4932-40de-a047-5524b7ddc972") }}
|
||||
|
||||
- name: Get a secret passing an explicit access token for authentication
|
||||
ansible.builtin.debug:
|
||||
msg: >-
|
||||
{{
|
||||
lookup(
|
||||
"community.general.bitwarden_secrets_manager",
|
||||
"2bc23e48-4932-40de-a047-5524b7ddc972",
|
||||
bws_access_token="9.4f570d14-4b54-42f5-bc07-60f4450b1db5.YmluYXJ5LXNvbWV0aGluZy0xMjMK:d2h5IGhlbGxvIHRoZXJlCg=="
|
||||
)
|
||||
}}
|
||||
|
||||
- name: Get two different secrets each using a different access token for authentication
|
||||
ansible.builtin.debug:
|
||||
msg:
|
||||
- '{{ lookup("community.general.bitwarden_secrets_manager", "2bc23e48-4932-40de-a047-5524b7ddc972", bws_access_token=token1) }}'
|
||||
- '{{ lookup("community.general.bitwarden_secrets_manager", "9d89af4c-eb5d-41f5-bb0f-4ae81215c768", bws_access_token=token2) }}'
|
||||
vars:
|
||||
token1: "9.4f570d14-4b54-42f5-bc07-60f4450b1db5.YmluYXJ5LXNvbWV0aGluZy0xMjMK:d2h5IGhlbGxvIHRoZXJlCg=="
|
||||
token2: "1.69b72797-6ea9-4687-a11e-848e41a30ae6.YW5zaWJsZSBpcyBncmVhdD8K:YW5zaWJsZSBpcyBncmVhdAo="
|
||||
|
||||
- name: Get just the value of a secret
|
||||
ansible.builtin.debug:
|
||||
msg: >-
|
||||
{{ lookup("community.general.bitwarden_secrets_manager", "2bc23e48-4932-40de-a047-5524b7ddc972").value }}
|
||||
"""
|
||||
|
||||
RETURN = r"""
|
||||
_raw:
|
||||
description: List containing one or more secrets.
|
||||
type: list
|
||||
elements: dict
|
||||
"""
|
||||
|
||||
from subprocess import PIPE, Popen
|
||||
from time import sleep
|
||||
|
||||
from ansible.errors import AnsibleLookupError
|
||||
from ansible.module_utils.common.text.converters import to_text
|
||||
from ansible.parsing.ajson import AnsibleJSONDecoder
|
||||
from ansible.plugins.lookup import LookupBase
|
||||
|
||||
from ansible_collections.community.general.plugins.module_utils._version import LooseVersion
|
||||
from ansible_collections.community.general.plugins.plugin_utils._lookup import check_for_wrong_terms
|
||||
|
||||
|
||||
class BitwardenSecretsManagerException(AnsibleLookupError):
|
||||
pass
|
||||
|
||||
|
||||
class BitwardenSecretsManager:
|
||||
def __init__(self, path="bws"):
|
||||
self._cli_path = path
|
||||
self._max_retries = 3
|
||||
self._retry_delay = 1
|
||||
|
||||
@property
|
||||
def cli_path(self):
|
||||
return self._cli_path
|
||||
|
||||
def _run_with_retry(self, args, stdin=None, retries=0):
|
||||
out, err, rc = self._run(args, stdin)
|
||||
|
||||
if rc != 0:
|
||||
if retries >= self._max_retries:
|
||||
raise BitwardenSecretsManagerException("Max retries exceeded. Unable to retrieve secret.")
|
||||
|
||||
if "Too many requests" in err:
|
||||
delay = self._retry_delay * (2**retries)
|
||||
sleep(delay)
|
||||
return self._run_with_retry(args, stdin, retries + 1)
|
||||
else:
|
||||
raise BitwardenSecretsManagerException(f"Command failed with return code {rc}: {err}")
|
||||
|
||||
return out, err, rc
|
||||
|
||||
def _run(self, args, stdin=None):
|
||||
p = Popen([self.cli_path] + args, stdout=PIPE, stderr=PIPE, stdin=PIPE)
|
||||
out, err = p.communicate(stdin)
|
||||
rc = p.wait()
|
||||
return to_text(out, errors="surrogate_or_strict"), to_text(err, errors="surrogate_or_strict"), rc
|
||||
|
||||
def get_bws_version(self):
|
||||
"""Get the version of the Bitwarden Secrets Manager CLI."""
|
||||
out, err, rc = self._run(["--version"])
|
||||
if rc != 0:
|
||||
raise BitwardenSecretsManagerException(to_text(err))
|
||||
# strip the prefix and grab the last segment, the version number
|
||||
return out.split()[-1]
|
||||
|
||||
def get_secret(self, secret_id, bws_access_token):
|
||||
"""Get and return the secret with the given secret_id."""
|
||||
|
||||
# Prepare set of params for Bitwarden Secrets Manager CLI
|
||||
# Color output was not always disabled correctly with the default 'auto' setting so explicitly disable it.
|
||||
params = ["--color", "no", "--access-token", bws_access_token]
|
||||
|
||||
# bws version 0.3.0 introduced a breaking change in the command line syntax:
|
||||
# pre-0.3.0: verb noun
|
||||
# 0.3.0 and later: noun verb
|
||||
bws_version = self.get_bws_version()
|
||||
if LooseVersion(bws_version) < LooseVersion("0.3.0"):
|
||||
params.extend(["get", "secret", secret_id])
|
||||
else:
|
||||
params.extend(["secret", "get", secret_id])
|
||||
|
||||
out, err, rc = self._run_with_retry(params)
|
||||
if rc != 0:
|
||||
raise BitwardenSecretsManagerException(to_text(err))
|
||||
|
||||
return AnsibleJSONDecoder().raw_decode(out)[0]
|
||||
|
||||
|
||||
class LookupModule(LookupBase):
|
||||
def run(self, terms, variables=None, **kwargs):
|
||||
self.set_options(var_options=variables, direct=kwargs)
|
||||
check_for_wrong_terms(self, direct=kwargs)
|
||||
bws_access_token = self.get_option("bws_access_token")
|
||||
|
||||
return [_bitwarden_secrets_manager.get_secret(term, bws_access_token) for term in terms]
|
||||
|
||||
|
||||
_bitwarden_secrets_manager = BitwardenSecretsManager()
|
||||
+82
@@ -0,0 +1,82 @@
|
||||
# Copyright (c) 2013, Bradley Young <young.bradley@gmail.com>
|
||||
# Copyright (c) 2017 Ansible Project
|
||||
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
from __future__ import annotations
|
||||
|
||||
DOCUMENTATION = r"""
|
||||
author: Unknown (!UNKNOWN)
|
||||
name: cartesian
|
||||
short_description: Returns the cartesian product of lists
|
||||
description:
|
||||
- Takes the input lists and returns a list that represents the product of the input lists.
|
||||
- It is clearer with an example, it turns [1, 2, 3], [a, b] into [1, a], [1, b], [2, a], [2, b], [3, a], [3, b].
|
||||
- You can see the exact syntax in the examples section.
|
||||
options:
|
||||
_terms:
|
||||
description:
|
||||
- A set of lists.
|
||||
type: list
|
||||
elements: list
|
||||
required: true
|
||||
"""
|
||||
|
||||
EXAMPLES = r"""
|
||||
- name: Example of the change in the description
|
||||
ansible.builtin.debug:
|
||||
msg: "{{ lookup('community.general.cartesian', [1,2,3], [a, b])}}"
|
||||
|
||||
- name: loops over the cartesian product of the supplied lists
|
||||
ansible.builtin.debug:
|
||||
msg: "{{item}}"
|
||||
with_community.general.cartesian:
|
||||
- "{{list1}}"
|
||||
- "{{list2}}"
|
||||
- [1, 2, 3, 4, 5, 6]
|
||||
"""
|
||||
|
||||
RETURN = r"""
|
||||
_list:
|
||||
description:
|
||||
- List of lists composed of elements of the input lists.
|
||||
type: list
|
||||
elements: list
|
||||
"""
|
||||
|
||||
from itertools import product
|
||||
|
||||
from ansible.errors import AnsibleError
|
||||
from ansible.plugins.lookup import LookupBase
|
||||
from ansible.utils.listify import listify_lookup_plugin_terms
|
||||
|
||||
from ansible_collections.community.general.plugins.plugin_utils._lookup import check_for_wrong_terms
|
||||
|
||||
|
||||
class LookupModule(LookupBase):
|
||||
"""
|
||||
Create the cartesian product of lists
|
||||
"""
|
||||
|
||||
def _lookup_variables(self, terms):
|
||||
"""
|
||||
Turn this:
|
||||
terms == ["1,2,3", "a,b"]
|
||||
into this:
|
||||
terms == [[1,2,3], [a, b]]
|
||||
"""
|
||||
results = []
|
||||
for x in terms:
|
||||
results.append(listify_lookup_plugin_terms(x, templar=self._templar))
|
||||
return results
|
||||
|
||||
def run(self, terms, variables=None, **kwargs):
|
||||
self.set_options(var_options=variables, direct=kwargs)
|
||||
check_for_wrong_terms(self, direct=kwargs)
|
||||
|
||||
terms = self._lookup_variables(terms)
|
||||
|
||||
my_list = terms[:]
|
||||
if len(my_list) == 0:
|
||||
raise AnsibleError("with_cartesian requires at least one element in each list")
|
||||
|
||||
return [self._flatten(x) for x in product(*my_list)]
|
||||
+104
@@ -0,0 +1,104 @@
|
||||
# Copyright (c) 2016, Josh Bradley <jbradley(at)digitalocean.com>
|
||||
# Copyright (c) 2017 Ansible Project
|
||||
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
from __future__ import annotations
|
||||
|
||||
DOCUMENTATION = r"""
|
||||
author: Unknown (!UNKNOWN)
|
||||
name: chef_databag
|
||||
short_description: Fetches data from a Chef Databag
|
||||
description:
|
||||
- 'This is a lookup plugin to provide access to chef data bags using the pychef package. It interfaces with the chef server
|
||||
API using the same methods to find a knife or chef-client config file to load parameters from, starting from either the
|
||||
given base path or the current working directory. The lookup order mirrors the one from Chef, all folders in the base
|
||||
path are walked back looking for the following configuration file in order: C(.chef/knife.rb), C(~/.chef/knife.rb), C(/etc/chef/client.rb).'
|
||||
requirements:
|
||||
- "pychef (L(Python library, https://pychef.readthedocs.io), C(pip install pychef))"
|
||||
options:
|
||||
name:
|
||||
description:
|
||||
- Name of the databag.
|
||||
type: string
|
||||
required: true
|
||||
item:
|
||||
description:
|
||||
- Item to fetch.
|
||||
type: string
|
||||
required: true
|
||||
"""
|
||||
|
||||
EXAMPLES = r"""
|
||||
- ansible.builtin.debug:
|
||||
msg: "{{ lookup('community.general.chef_databag', 'name=data_bag_name item=data_bag_item') }}"
|
||||
"""
|
||||
|
||||
RETURN = r"""
|
||||
_raw:
|
||||
description:
|
||||
- The value from the databag.
|
||||
type: list
|
||||
elements: dict
|
||||
"""
|
||||
|
||||
from ansible.errors import AnsibleError
|
||||
from ansible.parsing.splitter import parse_kv
|
||||
from ansible.plugins.lookup import LookupBase
|
||||
|
||||
try:
|
||||
import chef
|
||||
|
||||
HAS_CHEF = True
|
||||
except ImportError:
|
||||
HAS_CHEF = False
|
||||
|
||||
|
||||
class LookupModule(LookupBase):
|
||||
"""
|
||||
Chef data bag lookup module
|
||||
"""
|
||||
|
||||
def __init__(self, loader=None, templar=None, **kwargs):
|
||||
super().__init__(loader, templar, **kwargs)
|
||||
|
||||
# setup vars for data bag name and data bag item
|
||||
self.name = None
|
||||
self.item = None
|
||||
|
||||
def parse_kv_args(self, args):
|
||||
"""
|
||||
parse key-value style arguments
|
||||
"""
|
||||
|
||||
for arg in ["name", "item"]:
|
||||
try:
|
||||
arg_raw = args.pop(arg, None)
|
||||
if arg_raw is None:
|
||||
continue
|
||||
parsed = str(arg_raw)
|
||||
setattr(self, arg, parsed)
|
||||
except ValueError as e:
|
||||
raise AnsibleError(f"can't parse arg {arg}={arg_raw} as string") from e
|
||||
if args:
|
||||
raise AnsibleError(f"unrecognized arguments to with_sequence: {list(args.keys())!r}")
|
||||
|
||||
def run(self, terms, variables=None, **kwargs):
|
||||
# Ensure pychef has been loaded
|
||||
if not HAS_CHEF:
|
||||
raise AnsibleError("PyChef needed for lookup plugin, try `pip install pychef`")
|
||||
|
||||
# TODO: use new-style option parsing
|
||||
|
||||
for term in terms:
|
||||
self.parse_kv_args(parse_kv(term))
|
||||
|
||||
api_object = chef.autoconfigure()
|
||||
|
||||
if not isinstance(api_object, chef.api.ChefAPI):
|
||||
raise AnsibleError("Unable to connect to Chef Server API.")
|
||||
|
||||
data_bag_object = chef.DataBag(self.name)
|
||||
|
||||
data_bag_item = data_bag_object[self.item]
|
||||
|
||||
return [dict(data_bag_item)]
|
||||
+130
@@ -0,0 +1,130 @@
|
||||
# Copyright (c) 2021, Felix Fontein <felix@fontein.de>
|
||||
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
DOCUMENTATION = r"""
|
||||
name: collection_version
|
||||
author: Felix Fontein (@felixfontein)
|
||||
version_added: "4.0.0"
|
||||
short_description: Retrieves the version of an installed collection
|
||||
description:
|
||||
- This lookup allows to query the version of an installed collection, and to determine whether a collection is installed
|
||||
at all.
|
||||
- By default it returns V(none) for non-existing collections and V(*) for collections without a version number. The latter
|
||||
should only happen in development environments, or when installing a collection from git which has no version in its C(galaxy.yml).
|
||||
This behavior can be adjusted by providing other values with O(result_not_found) and O(result_no_version).
|
||||
options:
|
||||
_terms:
|
||||
description:
|
||||
- The collections to look for.
|
||||
- For example V(community.general).
|
||||
type: list
|
||||
elements: str
|
||||
required: true
|
||||
result_not_found:
|
||||
description:
|
||||
- The value to return when the collection could not be found.
|
||||
- By default, V(none) is returned.
|
||||
type: string
|
||||
default: ~
|
||||
result_no_version:
|
||||
description:
|
||||
- The value to return when the collection has no version number.
|
||||
- This can happen for collections installed from git which do not have a version number in C(galaxy.yml).
|
||||
- By default, V(*) is returned.
|
||||
type: string
|
||||
default: '*'
|
||||
"""
|
||||
|
||||
EXAMPLES = r"""
|
||||
- name: Check version of community.general
|
||||
ansible.builtin.debug:
|
||||
msg: "community.general version {{ lookup('community.general.collection_version', 'community.general') }}"
|
||||
"""
|
||||
|
||||
RETURN = r"""
|
||||
_raw:
|
||||
description:
|
||||
- The version number of the collections listed as input.
|
||||
- If a collection can not be found, it returns the value provided in O(result_not_found). By default, this is V(none).
|
||||
- If a collection can be found, but the version not identified, it returns the value provided in O(result_no_version).
|
||||
By default, this is V(*). This can happen for collections installed from git which do not have a version number in V(galaxy.yml).
|
||||
type: list
|
||||
elements: str
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
from importlib import import_module
|
||||
|
||||
import yaml
|
||||
from ansible.errors import AnsibleLookupError
|
||||
from ansible.plugins.lookup import LookupBase
|
||||
|
||||
from ansible_collections.community.general.plugins.plugin_utils._lookup import check_for_wrong_terms
|
||||
|
||||
FQCN_RE = re.compile(r"^[A-Za-z0-9_]+\.[A-Za-z0-9_]+$")
|
||||
|
||||
|
||||
def load_collection_meta_manifest(manifest_path):
|
||||
with open(manifest_path, "rb") as f:
|
||||
meta = json.load(f)
|
||||
return {
|
||||
"version": meta["collection_info"]["version"],
|
||||
}
|
||||
|
||||
|
||||
def load_collection_meta_galaxy(galaxy_path, no_version="*"):
|
||||
with open(galaxy_path, "rb") as f:
|
||||
meta = yaml.safe_load(f)
|
||||
return {
|
||||
"version": meta.get("version") or no_version,
|
||||
}
|
||||
|
||||
|
||||
def load_collection_meta(collection_pkg, no_version="*"):
|
||||
path = os.path.dirname(collection_pkg.__file__)
|
||||
|
||||
# Try to load MANIFEST.json
|
||||
manifest_path = os.path.join(path, "MANIFEST.json")
|
||||
if os.path.exists(manifest_path):
|
||||
return load_collection_meta_manifest(manifest_path)
|
||||
|
||||
# Try to load galaxy.yml
|
||||
galaxy_path = os.path.join(path, "galaxy.yml")
|
||||
if os.path.exists(galaxy_path):
|
||||
return load_collection_meta_galaxy(galaxy_path, no_version=no_version)
|
||||
|
||||
return {}
|
||||
|
||||
|
||||
class LookupModule(LookupBase):
|
||||
def run(self, terms, variables=None, **kwargs):
|
||||
result = []
|
||||
self.set_options(var_options=variables, direct=kwargs)
|
||||
check_for_wrong_terms(self, direct=kwargs)
|
||||
not_found = self.get_option("result_not_found")
|
||||
no_version = self.get_option("result_no_version")
|
||||
|
||||
for term in terms:
|
||||
if not FQCN_RE.match(term):
|
||||
raise AnsibleLookupError(f'"{term}" is not a FQCN')
|
||||
|
||||
try:
|
||||
collection_pkg = import_module(f"ansible_collections.{term}")
|
||||
except ImportError:
|
||||
# Collection not found
|
||||
result.append(not_found)
|
||||
continue
|
||||
|
||||
try:
|
||||
data = load_collection_meta(collection_pkg, no_version=no_version)
|
||||
except Exception as exc:
|
||||
raise AnsibleLookupError(f"Error while loading metadata for {term}: {exc}") from exc
|
||||
|
||||
result.append(data.get("version", no_version))
|
||||
|
||||
return result
|
||||
+265
@@ -0,0 +1,265 @@
|
||||
# Copyright (c) 2015, Steve Gargan <steve.gargan@gmail.com>
|
||||
# Copyright (c) 2017 Ansible Project
|
||||
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
from __future__ import annotations
|
||||
|
||||
DOCUMENTATION = r"""
|
||||
author: Unknown (!UNKNOWN)
|
||||
name: consul_kv
|
||||
short_description: Fetch metadata from a Consul key value store
|
||||
description:
|
||||
- Lookup metadata for a playbook from the key value store in a Consul cluster. Values can be easily set in the kv store
|
||||
with simple rest commands.
|
||||
- C(curl -X PUT -d 'some-value' http://localhost:8500/v1/kv/ansible/somedata).
|
||||
options:
|
||||
_terms:
|
||||
description: List of key(s) to retrieve.
|
||||
type: list
|
||||
elements: string
|
||||
recurse:
|
||||
type: boolean
|
||||
description: If V(true), retrieves all the values that have the given key as prefix.
|
||||
default: false
|
||||
index:
|
||||
description:
|
||||
- If the key has a value with the specified index then this is returned allowing access to historical values.
|
||||
type: int
|
||||
datacenter:
|
||||
description:
|
||||
- Retrieve the key from a consul datacenter other than the default for the consul host.
|
||||
type: str
|
||||
token:
|
||||
description: The acl token to allow access to restricted values.
|
||||
type: str
|
||||
secret: true
|
||||
host:
|
||||
default: localhost
|
||||
type: str
|
||||
description:
|
||||
- The target to connect to, must be a resolvable address.
|
||||
- It is determined from E(ANSIBLE_CONSUL_URL) if that is set.
|
||||
ini:
|
||||
- section: lookup_consul
|
||||
key: host
|
||||
port:
|
||||
description:
|
||||
- The port of the target host to connect to.
|
||||
- If you use E(ANSIBLE_CONSUL_URL) this value is used from there.
|
||||
type: int
|
||||
default: 8500
|
||||
scheme:
|
||||
default: http
|
||||
type: str
|
||||
description:
|
||||
- Whether to use http or https.
|
||||
- If you use E(ANSIBLE_CONSUL_URL) this value is used from there.
|
||||
validate_certs:
|
||||
default: true
|
||||
description:
|
||||
- Whether to verify the TLS connection or not.
|
||||
- Instead of setting this to V(false), please consider using O(ca_path) instead.
|
||||
type: bool
|
||||
env:
|
||||
- name: ANSIBLE_CONSUL_VALIDATE_CERTS
|
||||
ini:
|
||||
- section: lookup_consul
|
||||
key: validate_certs
|
||||
ca_path:
|
||||
description: The CA bundle to use for HTTPS connections.
|
||||
type: str
|
||||
version_added: "12.6.0"
|
||||
env:
|
||||
- name: ANSIBLE_CONSUL_CA_PATH
|
||||
ini:
|
||||
- section: lookup_consul
|
||||
key: ca_path
|
||||
client_cert:
|
||||
description: The client cert to verify the TLS connection.
|
||||
type: str
|
||||
env:
|
||||
- name: ANSIBLE_CONSUL_CLIENT_CERT
|
||||
ini:
|
||||
- section: lookup_consul
|
||||
key: client_cert
|
||||
url:
|
||||
description:
|
||||
- The target to connect to.
|
||||
- 'Should look like this: V(https://my.consul.server:8500).'
|
||||
type: str
|
||||
version_added: 1.0.0
|
||||
env:
|
||||
- name: ANSIBLE_CONSUL_URL
|
||||
ini:
|
||||
- section: lookup_consul
|
||||
key: url
|
||||
empty_value:
|
||||
description:
|
||||
- Controls what is returned when a Consul value is null.
|
||||
type: str
|
||||
default: 'textual_none'
|
||||
choices:
|
||||
textual_none: Return the string V(None). This is the legacy behavior.
|
||||
python_none: Return a Python V(null)/V(None) value.
|
||||
empty_string: Return an empty string.
|
||||
version_added: 13.1.0
|
||||
notes:
|
||||
- On a macOS controller this lookup can abort the worker process it runs in, with Ansible reporting C(A worker was found
|
||||
in a dead state). Lookups run in a forked process, and resolving the system proxy configuration there initializes macOS
|
||||
frameworks that are not safe to use after a C(fork()); see U(https://github.com/ansible/ansible/issues/49207). Setting
|
||||
any proxy environment variable, for example E(no_proxy), skips the system proxy lookup and avoids the crash.
|
||||
"""
|
||||
|
||||
EXAMPLES = r"""
|
||||
- ansible.builtin.debug:
|
||||
msg: 'key contains {{item}}'
|
||||
with_community.general.consul_kv:
|
||||
- 'key/to/retrieve'
|
||||
|
||||
- name: Parameters can be provided after the key be more specific about what to retrieve
|
||||
ansible.builtin.debug:
|
||||
msg: 'key contains {{item}}'
|
||||
with_community.general.consul_kv:
|
||||
- 'key/to recurse=true token=E6C060A9-26FB-407A-B83E-12DDAFCB4D98'
|
||||
|
||||
- name: retrieving a KV from a remote cluster on non default port
|
||||
ansible.builtin.debug:
|
||||
msg: "{{ lookup('community.general.consul_kv', 'my/key', host='10.10.10.10', port=2000) }}"
|
||||
"""
|
||||
|
||||
RETURN = r"""
|
||||
_raw:
|
||||
description:
|
||||
- Value(s) stored in consul.
|
||||
type: dict
|
||||
"""
|
||||
|
||||
import base64
|
||||
import json
|
||||
from urllib.error import HTTPError
|
||||
from urllib.parse import quote, urlencode, urlparse
|
||||
|
||||
from ansible.errors import AnsibleAssertionError, AnsibleError
|
||||
from ansible.module_utils.common.text.converters import to_text
|
||||
from ansible.module_utils.urls import open_url
|
||||
from ansible.plugins.lookup import LookupBase
|
||||
|
||||
from ansible_collections.community.general.plugins.plugin_utils._lookup import check_for_wrong_terms
|
||||
|
||||
_EMPTY_VALUE_MAP = {
|
||||
"textual_none": "None",
|
||||
"python_none": None,
|
||||
"empty_string": "",
|
||||
}
|
||||
|
||||
|
||||
class LookupModule(LookupBase):
|
||||
def run(self, terms, variables=None, **kwargs):
|
||||
# get options
|
||||
self.set_options(direct=kwargs)
|
||||
check_for_wrong_terms(self, direct=kwargs)
|
||||
|
||||
scheme = self.get_option("scheme")
|
||||
host = self.get_option("host")
|
||||
port = self.get_option("port")
|
||||
url = self.get_option("url")
|
||||
if url is not None:
|
||||
u = urlparse(url)
|
||||
if u.scheme:
|
||||
scheme = u.scheme
|
||||
host = u.hostname
|
||||
if u.port is not None:
|
||||
port = u.port
|
||||
|
||||
validate_certs = self.get_option("validate_certs")
|
||||
ca_path = self.get_option("ca_path")
|
||||
client_cert = self.get_option("client_cert")
|
||||
|
||||
empty_value = _EMPTY_VALUE_MAP[self.get_option("empty_value")]
|
||||
values = []
|
||||
try:
|
||||
for term in terms:
|
||||
params = self.parse_params(term)
|
||||
entries = self._kv_get(
|
||||
scheme=scheme,
|
||||
host=host,
|
||||
port=port,
|
||||
key=params["key"],
|
||||
token=params["token"],
|
||||
index=params["index"],
|
||||
recurse=params["recurse"],
|
||||
datacenter=params["datacenter"],
|
||||
validate_certs=validate_certs,
|
||||
ca_path=ca_path,
|
||||
client_cert=client_cert,
|
||||
)
|
||||
for entry in entries or []:
|
||||
v = entry["Value"]
|
||||
values.append(to_text(v) if v is not None else empty_value)
|
||||
except Exception as e:
|
||||
raise AnsibleError(f"Error locating '{term}' in kv store. Error was {e}") from e
|
||||
|
||||
return values
|
||||
|
||||
@staticmethod
|
||||
def _kv_get(scheme, host, port, key, token, index, recurse, datacenter, validate_certs, ca_path, client_cert):
|
||||
query = {}
|
||||
if recurse:
|
||||
query["recurse"] = "true"
|
||||
if datacenter:
|
||||
query["dc"] = datacenter
|
||||
if index is not None:
|
||||
query["index"] = index
|
||||
|
||||
url = f"{scheme}://{host}:{port}/v1/kv/{quote(key, safe='/')}"
|
||||
if query:
|
||||
url = f"{url}?{urlencode(query)}"
|
||||
|
||||
headers = {"X-Consul-Token": token} if token else {}
|
||||
|
||||
try:
|
||||
response = open_url(
|
||||
url,
|
||||
headers=headers,
|
||||
validate_certs=validate_certs,
|
||||
ca_path=ca_path,
|
||||
client_cert=client_cert,
|
||||
)
|
||||
except HTTPError as e:
|
||||
if e.code == 404:
|
||||
return None
|
||||
raise
|
||||
|
||||
body = response.read()
|
||||
if not body:
|
||||
return None
|
||||
|
||||
entries = json.loads(body)
|
||||
for entry in entries:
|
||||
if entry.get("Value") is not None:
|
||||
entry["Value"] = base64.b64decode(entry["Value"])
|
||||
return entries
|
||||
|
||||
def parse_params(self, term):
|
||||
params = term.split(" ")
|
||||
|
||||
paramvals = {
|
||||
"key": params[0],
|
||||
"token": self.get_option("token"),
|
||||
"recurse": self.get_option("recurse"),
|
||||
"index": self.get_option("index"),
|
||||
"datacenter": self.get_option("datacenter"),
|
||||
}
|
||||
|
||||
# parameters specified?
|
||||
try:
|
||||
for param in params[1:]:
|
||||
if param and len(param) > 0:
|
||||
name, value = param.split("=")
|
||||
if name not in paramvals:
|
||||
raise AnsibleAssertionError(f"{name} not a valid consul lookup parameter")
|
||||
paramvals[name] = value
|
||||
except (ValueError, AssertionError) as e:
|
||||
raise AnsibleError(e) from e
|
||||
|
||||
return paramvals
|
||||
+158
@@ -0,0 +1,158 @@
|
||||
# Copyright (c) 2015, Ensighten <infra@ensighten.com>
|
||||
# Copyright (c) 2017 Ansible Project
|
||||
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
from __future__ import annotations
|
||||
|
||||
DOCUMENTATION = r"""
|
||||
author: Unknown (!UNKNOWN)
|
||||
name: credstash
|
||||
short_description: Retrieve secrets from Credstash on AWS
|
||||
requirements:
|
||||
- credstash (python library)
|
||||
description:
|
||||
- "Credstash is a small utility for managing secrets using AWS's KMS and DynamoDB: https://github.com/fugue/credstash."
|
||||
options:
|
||||
_terms:
|
||||
description: Term or list of terms to lookup in the credit store.
|
||||
type: list
|
||||
elements: string
|
||||
required: true
|
||||
table:
|
||||
description: Name of the credstash table to query.
|
||||
type: str
|
||||
default: 'credential-store'
|
||||
version:
|
||||
description: Credstash version.
|
||||
type: str
|
||||
default: ''
|
||||
region:
|
||||
description: AWS region.
|
||||
type: str
|
||||
profile_name:
|
||||
description: AWS profile to use for authentication.
|
||||
type: str
|
||||
env:
|
||||
- name: AWS_PROFILE
|
||||
aws_access_key_id:
|
||||
description: AWS access key ID.
|
||||
type: str
|
||||
env:
|
||||
- name: AWS_ACCESS_KEY_ID
|
||||
aws_secret_access_key:
|
||||
description: AWS access key.
|
||||
type: str
|
||||
env:
|
||||
- name: AWS_SECRET_ACCESS_KEY
|
||||
secret: true
|
||||
aws_session_token:
|
||||
description: AWS session token.
|
||||
type: str
|
||||
env:
|
||||
- name: AWS_SESSION_TOKEN
|
||||
secret: true
|
||||
"""
|
||||
|
||||
EXAMPLES = r"""
|
||||
- name: first use credstash to store your secrets
|
||||
ansible.builtin.shell: credstash put my-github-password secure123
|
||||
|
||||
- name: "Test credstash lookup plugin -- get my github password"
|
||||
ansible.builtin.debug:
|
||||
msg: "Credstash lookup! {{ lookup('community.general.credstash', 'my-github-password') }}"
|
||||
|
||||
- name: "Test credstash lookup plugin -- get my other password from us-west-1"
|
||||
ansible.builtin.debug:
|
||||
msg: "Credstash lookup! {{ lookup('community.general.credstash', 'my-other-password', region='us-west-1') }}"
|
||||
|
||||
- name: "Test credstash lookup plugin -- get the company's github password"
|
||||
ansible.builtin.debug:
|
||||
msg: "Credstash lookup! {{ lookup('community.general.credstash', 'company-github-password', table='company-passwords') }}"
|
||||
|
||||
- name: Example play using the 'context' feature
|
||||
hosts: localhost
|
||||
vars:
|
||||
context:
|
||||
app: my_app
|
||||
environment: production
|
||||
tasks:
|
||||
|
||||
- name: "Test credstash lookup plugin -- get the password with a context passed as a variable"
|
||||
ansible.builtin.debug:
|
||||
msg: "{{ lookup('community.general.credstash', 'some-password', **context) }}"
|
||||
|
||||
- name: "Test credstash lookup plugin -- get the password with a context defined here"
|
||||
ansible.builtin.debug:
|
||||
msg: "{{ lookup('community.general.credstash', 'some-password', app='my_app', environment='production') }}"
|
||||
"""
|
||||
|
||||
RETURN = r"""
|
||||
_raw:
|
||||
description:
|
||||
- Value(s) stored in Credstash.
|
||||
type: str
|
||||
"""
|
||||
|
||||
from ansible.errors import AnsibleError
|
||||
from ansible.plugins.lookup import LookupBase
|
||||
|
||||
from ansible_collections.community.general.plugins.plugin_utils._lookup import check_for_wrong_terms
|
||||
|
||||
CREDSTASH_INSTALLED = False
|
||||
|
||||
try:
|
||||
import credstash
|
||||
|
||||
CREDSTASH_INSTALLED = True
|
||||
except ImportError:
|
||||
CREDSTASH_INSTALLED = False
|
||||
|
||||
|
||||
class LookupModule(LookupBase):
|
||||
def run(self, terms, variables=None, **kwargs):
|
||||
if not CREDSTASH_INSTALLED:
|
||||
raise AnsibleError("The credstash lookup plugin requires credstash to be installed.")
|
||||
|
||||
self.set_options(var_options=variables, direct=kwargs)
|
||||
check_for_wrong_terms(self, direct=kwargs)
|
||||
|
||||
version = self.get_option("version")
|
||||
region = self.get_option("region")
|
||||
table = self.get_option("table")
|
||||
profile_name = self.get_option("profile_name")
|
||||
aws_access_key_id = self.get_option("aws_access_key_id")
|
||||
aws_secret_access_key = self.get_option("aws_secret_access_key")
|
||||
aws_session_token = self.get_option("aws_session_token")
|
||||
|
||||
context = {
|
||||
k: v
|
||||
for k, v in kwargs.items()
|
||||
if k
|
||||
not in (
|
||||
"version",
|
||||
"region",
|
||||
"table",
|
||||
"profile_name",
|
||||
"aws_access_key_id",
|
||||
"aws_secret_access_key",
|
||||
"aws_session_token",
|
||||
)
|
||||
}
|
||||
|
||||
kwargs_pass = {
|
||||
"profile_name": profile_name,
|
||||
"aws_access_key_id": aws_access_key_id,
|
||||
"aws_secret_access_key": aws_secret_access_key,
|
||||
"aws_session_token": aws_session_token,
|
||||
}
|
||||
|
||||
ret = []
|
||||
for term in terms:
|
||||
try:
|
||||
ret.append(credstash.getSecret(term, version, region, table, context=context, **kwargs_pass))
|
||||
except credstash.ItemNotFound as e:
|
||||
raise AnsibleError(f"Key {term} not found") from e
|
||||
except Exception as e:
|
||||
raise AnsibleError(f"Encountered exception while fetching {term}: {e}") from e
|
||||
|
||||
return ret
|
||||
+194
@@ -0,0 +1,194 @@
|
||||
# Copyright (c) 2017, Edward Nunez <edward.nunez@cyberark.com>
|
||||
# Copyright (c) 2017 Ansible Project
|
||||
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
from __future__ import annotations
|
||||
|
||||
DOCUMENTATION = r"""
|
||||
author: Unknown (!UNKNOWN)
|
||||
name: cyberarkpassword
|
||||
short_description: Get secrets from CyberArk AIM
|
||||
requirements:
|
||||
- CyberArk AIM tool installed
|
||||
description:
|
||||
- Get secrets from CyberArk AIM.
|
||||
options:
|
||||
_command:
|
||||
description: Cyberark CLI utility.
|
||||
type: string
|
||||
env:
|
||||
- name: AIM_CLIPASSWORDSDK_CMD
|
||||
default: '/opt/CARKaim/sdk/clipasswordsdk'
|
||||
appid:
|
||||
description: Defines the unique ID of the application that is issuing the password request.
|
||||
type: string
|
||||
required: true
|
||||
query:
|
||||
description: Describes the filter criteria for the password retrieval.
|
||||
type: string
|
||||
required: true
|
||||
output:
|
||||
description:
|
||||
- Specifies the desired output fields separated by commas.
|
||||
- 'They could be: Password, PassProps.<property>, PasswordChangeInProcess.'
|
||||
type: string
|
||||
default: 'password'
|
||||
_extra:
|
||||
description: For extra_params values please check parameters for clipasswordsdk in CyberArk's "Credential Provider and
|
||||
ASCP Implementation Guide".
|
||||
notes:
|
||||
- For Ansible on Windows, please change the -parameters (C(-p), C(-d), and C(-o)) to /parameters (C(/p), C(/d), and C(/o))
|
||||
and change the location of C(CLIPasswordSDK.exe).
|
||||
"""
|
||||
|
||||
EXAMPLES = r"""
|
||||
- name: passing options to the lookup
|
||||
ansible.builtin.debug:
|
||||
msg: '{{ lookup("community.general.cyberarkpassword", cyquery) }}'
|
||||
vars:
|
||||
cyquery:
|
||||
appid: "app_ansible"
|
||||
query: "safe=CyberArk_Passwords;folder=root;object=AdminPass"
|
||||
output: "Password,PassProps.UserName,PassProps.Address,PasswordChangeInProcess"
|
||||
|
||||
|
||||
- name: used in a loop
|
||||
ansible.builtin.debug:
|
||||
msg: "{{item}}"
|
||||
with_community.general.cyberarkpassword:
|
||||
appid: 'app_ansible'
|
||||
query: 'safe=CyberArk_Passwords;folder=root;object=AdminPass'
|
||||
output: 'Password,PassProps.UserName,PassProps.Address,PasswordChangeInProcess'
|
||||
"""
|
||||
|
||||
RETURN = r"""
|
||||
_result:
|
||||
description: A list containing one dictionary.
|
||||
type: list
|
||||
elements: dictionary
|
||||
contains:
|
||||
password:
|
||||
description:
|
||||
- The actual value stored.
|
||||
passprops:
|
||||
description: Properties assigned to the entry.
|
||||
type: dictionary
|
||||
passwordchangeinprocess:
|
||||
description: Did the password change?
|
||||
"""
|
||||
|
||||
import os
|
||||
import subprocess
|
||||
from subprocess import PIPE, Popen
|
||||
|
||||
from ansible.errors import AnsibleError
|
||||
from ansible.module_utils.common.text.converters import to_bytes, to_native
|
||||
from ansible.plugins.lookup import LookupBase
|
||||
from ansible.utils.display import Display
|
||||
|
||||
display = Display()
|
||||
|
||||
CLIPASSWORDSDK_CMD = os.getenv("AIM_CLIPASSWORDSDK_CMD", "/opt/CARKaim/sdk/clipasswordsdk")
|
||||
|
||||
|
||||
class CyberarkPassword:
|
||||
def __init__(self, appid=None, query=None, output=None, **kwargs):
|
||||
self.appid = appid
|
||||
self.query = query
|
||||
self.output = output
|
||||
|
||||
# Support for Generic parameters to be able to specify
|
||||
# FailRequestOnPasswordChange, Queryformat, Reason, etc.
|
||||
self.extra_parms = []
|
||||
for key, value in kwargs.items():
|
||||
self.extra_parms.append("-p")
|
||||
self.extra_parms.append(f"{key}={value}")
|
||||
|
||||
if self.appid is None:
|
||||
raise AnsibleError("CyberArk Error: No Application ID specified")
|
||||
if self.query is None:
|
||||
raise AnsibleError("CyberArk Error: No Vault query specified")
|
||||
|
||||
if self.output is None:
|
||||
# If no output is specified, return at least the password
|
||||
self.output = "password"
|
||||
else:
|
||||
# To avoid reference issues/confusion to values, all
|
||||
# output 'keys' will be in lowercase.
|
||||
self.output = self.output.lower()
|
||||
|
||||
self.b_delimiter = b"@#@" # Known delimiter to split output results
|
||||
|
||||
def get(self):
|
||||
result_dict = {}
|
||||
|
||||
try:
|
||||
all_parms = [
|
||||
CLIPASSWORDSDK_CMD,
|
||||
"GetPassword",
|
||||
"-p",
|
||||
f"AppDescs.AppID={self.appid}",
|
||||
"-p",
|
||||
f"Query={self.query}",
|
||||
"-o",
|
||||
self.output,
|
||||
"-d",
|
||||
self.b_delimiter,
|
||||
]
|
||||
all_parms.extend(self.extra_parms)
|
||||
|
||||
b_credential = b""
|
||||
b_all_params = [to_bytes(v) for v in all_parms]
|
||||
tmp_output, tmp_error = Popen(b_all_params, stdout=PIPE, stderr=PIPE, stdin=PIPE).communicate()
|
||||
|
||||
if tmp_output:
|
||||
b_credential = to_bytes(tmp_output)
|
||||
|
||||
if tmp_error:
|
||||
raise AnsibleError(f"ERROR => {tmp_error} ")
|
||||
|
||||
if b_credential and b_credential.endswith(b"\n"):
|
||||
b_credential = b_credential[:-1]
|
||||
|
||||
output_names = self.output.split(",")
|
||||
output_values = b_credential.split(self.b_delimiter)
|
||||
|
||||
for i in range(len(output_names)):
|
||||
if output_names[i].startswith("passprops."):
|
||||
if "passprops" not in result_dict:
|
||||
result_dict["passprops"] = {}
|
||||
output_prop_name = output_names[i][10:]
|
||||
result_dict["passprops"][output_prop_name] = to_native(output_values[i])
|
||||
else:
|
||||
result_dict[output_names[i]] = to_native(output_values[i])
|
||||
|
||||
except subprocess.CalledProcessError as e:
|
||||
raise AnsibleError(e.output) from e
|
||||
except OSError as e:
|
||||
raise AnsibleError(
|
||||
f"ERROR - AIM not installed or clipasswordsdk not in standard location. ERROR=({e.errno}) => {e.strerror} "
|
||||
) from e
|
||||
|
||||
return [result_dict]
|
||||
|
||||
|
||||
class LookupModule(LookupBase):
|
||||
"""
|
||||
USAGE:
|
||||
|
||||
"""
|
||||
|
||||
def run(self, terms, variables=None, **kwargs):
|
||||
# TODO: use new-style option parsing
|
||||
display.vvvv(f"{terms}")
|
||||
if isinstance(terms, list):
|
||||
return_values = []
|
||||
for term in terms:
|
||||
display.vvvv(f"Term: {term}")
|
||||
cyberark_conn = CyberarkPassword(**term)
|
||||
return_values.append(cyberark_conn.get())
|
||||
return return_values
|
||||
else:
|
||||
cyberark_conn = CyberarkPassword(**terms)
|
||||
result = cyberark_conn.get()
|
||||
return result
|
||||
+214
@@ -0,0 +1,214 @@
|
||||
# Copyright (c) 2015-2021, Felix Fontein <felix@fontein.de>
|
||||
# Copyright (c) 2018 Ansible Project
|
||||
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
from __future__ import annotations
|
||||
|
||||
DOCUMENTATION = r"""
|
||||
name: dependent
|
||||
short_description: Composes a list with nested elements of other lists or dicts which can depend on previous loop variables
|
||||
author: Felix Fontein (@felixfontein)
|
||||
version_added: 3.1.0
|
||||
description:
|
||||
- Takes the input lists and returns a list with elements that are lists, dictionaries, or template expressions which evaluate
|
||||
to lists or dicts, composed of the elements of the input evaluated lists and dictionaries.
|
||||
options:
|
||||
_terms:
|
||||
description:
|
||||
- A list where the elements are one-element dictionaries, mapping a name to a string, list, or dictionary. The name
|
||||
is the index that is used in the result object. The value is iterated over as described below.
|
||||
- If the value is a list, it is simply iterated over.
|
||||
- If the value is a dictionary, it is iterated over and returned as if they would be processed by the P(ansible.builtin.dict2items#filter)
|
||||
filter.
|
||||
- If the value is a string, it is evaluated as Jinja2 expressions which can access the previously chosen elements with
|
||||
C(item.<index_name>). The result must be a list or a dictionary.
|
||||
type: list
|
||||
elements: dict
|
||||
required: true
|
||||
"""
|
||||
|
||||
EXAMPLES = r"""
|
||||
- name: Install/remove public keys for active admin users
|
||||
ansible.posix.authorized_key:
|
||||
user: "{{ item.admin.key }}"
|
||||
key: "{{ lookup('file', item.key.public_key) }}"
|
||||
state: "{{ 'present' if item.key.active else 'absent' }}"
|
||||
when: item.admin.value.active
|
||||
with_community.general.dependent:
|
||||
- admin: admin_user_data
|
||||
- key: admin_ssh_keys[item.admin.key]
|
||||
loop_control:
|
||||
# Makes the output readable, so that it doesn't contain the whole subdictionaries and lists
|
||||
label: "{{ [item.admin.key, 'active' if item.key.active else 'inactive', item.key.public_key] }}"
|
||||
vars:
|
||||
admin_user_data:
|
||||
admin1:
|
||||
name: Alice
|
||||
active: true
|
||||
admin2:
|
||||
name: Bob
|
||||
active: true
|
||||
admin_ssh_keys:
|
||||
admin1:
|
||||
- private_key: keys/private_key_admin1.pem
|
||||
public_key: keys/private_key_admin1.pub
|
||||
active: true
|
||||
admin2:
|
||||
- private_key: keys/private_key_admin2.pem
|
||||
public_key: keys/private_key_admin2.pub
|
||||
active: true
|
||||
- private_key: keys/private_key_admin2-old.pem
|
||||
public_key: keys/private_key_admin2-old.pub
|
||||
active: false
|
||||
|
||||
- name: Update DNS records
|
||||
community.aws.route53:
|
||||
zone: "{{ item.zone.key }}"
|
||||
record: "{{ item.prefix.key ~ '.' if item.prefix.key else '' }}{{ item.zone.key }}"
|
||||
type: "{{ item.entry.key }}"
|
||||
ttl: "{{ item.entry.value.ttl | default(3600) }}"
|
||||
value: "{{ item.entry.value.value }}"
|
||||
state: "{{ 'absent' if (item.entry.value.absent | default(False)) else 'present' }}"
|
||||
overwrite: true
|
||||
loop_control:
|
||||
# Makes the output readable, so that it doesn't contain the whole subdictionaries and lists
|
||||
label: |-
|
||||
{{ [item.zone.key, item.prefix.key, item.entry.key,
|
||||
item.entry.value.ttl | default(3600),
|
||||
item.entry.value.absent | default(False), item.entry.value.value] }}
|
||||
with_community.general.dependent:
|
||||
- zone: dns_setup
|
||||
- prefix: item.zone.value
|
||||
- entry: item.prefix.value
|
||||
vars:
|
||||
dns_setup:
|
||||
example.com:
|
||||
'':
|
||||
A:
|
||||
value:
|
||||
- 1.2.3.4
|
||||
AAAA:
|
||||
value:
|
||||
- "2a01:1:2:3::1"
|
||||
'test._domainkey':
|
||||
TXT:
|
||||
ttl: 300
|
||||
value:
|
||||
- '"k=rsa; t=s; p=MIGfMA..."'
|
||||
example.org:
|
||||
'www':
|
||||
A:
|
||||
value:
|
||||
- 1.2.3.4
|
||||
- 5.6.7.8
|
||||
"""
|
||||
|
||||
RETURN = r"""
|
||||
_list:
|
||||
description:
|
||||
- A list composed of dictionaries whose keys are the variable names from the input list.
|
||||
type: list
|
||||
elements: dict
|
||||
sample:
|
||||
- key1: a
|
||||
key2: test
|
||||
- key1: a
|
||||
key2: foo
|
||||
- key1: b
|
||||
key2: bar
|
||||
"""
|
||||
|
||||
from collections.abc import Mapping, Sequence
|
||||
|
||||
from ansible.errors import AnsibleLookupError
|
||||
from ansible.plugins.lookup import LookupBase
|
||||
from ansible.template import trust_as_template as _trust_as_template
|
||||
|
||||
from ansible_collections.community.general.plugins.plugin_utils._lookup import check_for_wrong_terms
|
||||
|
||||
|
||||
def _make_safe(value):
|
||||
if isinstance(value, str):
|
||||
return _trust_as_template(value)
|
||||
return value
|
||||
|
||||
|
||||
class LookupModule(LookupBase):
|
||||
def __evaluate(self, expression, templar, variables):
|
||||
"""Evaluate expression with templar.
|
||||
|
||||
``expression`` is the expression to evaluate.
|
||||
``variables`` are the variables to use.
|
||||
"""
|
||||
templar.available_variables = variables or {}
|
||||
return templar.evaluate_expression(_make_safe(expression))
|
||||
|
||||
def __process(self, result, terms, index, current, templar, variables):
|
||||
"""Fills ``result`` list with evaluated items.
|
||||
|
||||
``result`` is a list where the resulting items are placed.
|
||||
``terms`` is the parsed list of terms
|
||||
``index`` is the current index to be processed in the list.
|
||||
``current`` is a dictionary where the first ``index`` values are filled in.
|
||||
``variables`` are the variables currently available.
|
||||
"""
|
||||
# If we are done, add to result list:
|
||||
if index == len(terms):
|
||||
result.append(current.copy())
|
||||
return
|
||||
|
||||
key, expression, values = terms[index]
|
||||
|
||||
if expression is not None:
|
||||
# Evaluate expression in current context
|
||||
vars = variables.copy()
|
||||
vars["item"] = current.copy()
|
||||
try:
|
||||
values = self.__evaluate(expression, templar, variables=vars)
|
||||
except Exception as e:
|
||||
raise AnsibleLookupError(f'Caught "{e}" while evaluating {key!r} with item == {current!r}') from e
|
||||
|
||||
if isinstance(values, Mapping):
|
||||
for idx, val in sorted(values.items()):
|
||||
current[key] = dict(key=idx, value=val)
|
||||
self.__process(result, terms, index + 1, current, templar, variables)
|
||||
elif isinstance(values, Sequence):
|
||||
for elt in values:
|
||||
current[key] = elt
|
||||
self.__process(result, terms, index + 1, current, templar, variables)
|
||||
else:
|
||||
raise AnsibleLookupError(
|
||||
f"Did not obtain dictionary or list while evaluating {key!r} with item == {current!r}, but {type(values)}"
|
||||
)
|
||||
|
||||
def run(self, terms, variables=None, **kwargs):
|
||||
"""Generate list."""
|
||||
self.set_options(var_options=variables, direct=kwargs)
|
||||
check_for_wrong_terms(self, direct=kwargs)
|
||||
|
||||
result = []
|
||||
if len(terms) > 0:
|
||||
templar = self._templar.copy_with_new_env(available_variables={})
|
||||
data = []
|
||||
vars_so_far = set()
|
||||
for index, term in enumerate(terms):
|
||||
if not isinstance(term, Mapping):
|
||||
raise AnsibleLookupError(f"Parameter {index} must be a dictionary, got {type(term)}")
|
||||
if len(term) != 1:
|
||||
raise AnsibleLookupError(
|
||||
f"Parameter {index} must be a one-element dictionary, got {len(term)} elements"
|
||||
)
|
||||
k, v = list(term.items())[0]
|
||||
if k in vars_so_far:
|
||||
raise AnsibleLookupError(f"The variable {k!r} appears more than once")
|
||||
vars_so_far.add(k)
|
||||
if isinstance(v, str):
|
||||
data.append((k, v, None))
|
||||
elif isinstance(v, (Sequence, Mapping)):
|
||||
data.append((k, None, v))
|
||||
else:
|
||||
raise AnsibleLookupError(
|
||||
f"Parameter {k!r} (index {index}) must have a value of type string, dictionary or list, got type {type(v)}"
|
||||
)
|
||||
self.__process(result, data, 0, {}, templar, variables)
|
||||
return result
|
||||
@@ -0,0 +1,510 @@
|
||||
# Copyright (c) 2015, Jan-Piet Mens <jpmens(at)gmail.com>
|
||||
# Copyright (c) 2017 Ansible Project
|
||||
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
from __future__ import annotations
|
||||
|
||||
DOCUMENTATION = r"""
|
||||
name: dig
|
||||
author: Jan-Piet Mens (@jpmens) <jpmens(at)gmail.com>
|
||||
short_description: Query DNS using the dnspython library
|
||||
requirements:
|
||||
- dnspython (python library, http://www.dnspython.org/)
|
||||
description:
|
||||
- The dig lookup runs queries against DNS servers to retrieve DNS records for a specific name (FQDN - fully qualified domain
|
||||
name). It is possible to lookup any DNS record in this manner.
|
||||
- There is a couple of different syntaxes that can be used to specify what record should be retrieved, and for which name.
|
||||
It is also possible to explicitly specify the DNS server(s) to use for lookups.
|
||||
- In its simplest form, the dig lookup plugin can be used to retrieve an IPv4 address (DNS A record) associated with FQDN.
|
||||
- In addition to (default) A record, it is also possible to specify a different record type that should be queried. This
|
||||
can be done by either passing-in additional parameter of format qtype=TYPE to the dig lookup, or by appending /TYPE to
|
||||
the FQDN being queried.
|
||||
- If multiple values are associated with the requested record, the results are returned as a comma-separated list. In
|
||||
such cases you may want to pass option C(wantlist=true) to the lookup call, or alternatively use C(query) instead of C(lookup),
|
||||
which results in the record values being returned as a list over which you can iterate later on.
|
||||
- By default, the lookup relies on system-wide configured DNS servers for performing the query. It is also possible to
|
||||
explicitly specify DNS servers to query using the @DNS_SERVER_1,DNS_SERVER_2,...,DNS_SERVER_N notation. This needs to
|
||||
be passed-in as an additional parameter to the lookup.
|
||||
options:
|
||||
_terms:
|
||||
description: Domain(s) to query.
|
||||
type: list
|
||||
elements: str
|
||||
qtype:
|
||||
description:
|
||||
- Record type to query.
|
||||
- V(DLV) has been removed in community.general 6.0.0.
|
||||
- V(CAA) has been added in community.general 6.3.0.
|
||||
type: str
|
||||
default: 'A'
|
||||
choices:
|
||||
- A
|
||||
- ALL
|
||||
- AAAA
|
||||
- CAA
|
||||
- CNAME
|
||||
- DNAME
|
||||
- DNSKEY
|
||||
- DS
|
||||
- HINFO
|
||||
- LOC
|
||||
- MX
|
||||
- NAPTR
|
||||
- NS
|
||||
- NSEC3PARAM
|
||||
- PTR
|
||||
- RP
|
||||
- RRSIG
|
||||
- SOA
|
||||
- SPF
|
||||
- SRV
|
||||
- SSHFP
|
||||
- TLSA
|
||||
- TXT
|
||||
flat:
|
||||
description: If 0 each record is returned as a dictionary, otherwise a string.
|
||||
type: int
|
||||
default: 1
|
||||
retry_servfail:
|
||||
description: Retry a nameserver if it returns SERVFAIL.
|
||||
default: false
|
||||
type: bool
|
||||
version_added: 3.6.0
|
||||
fail_on_error:
|
||||
description:
|
||||
- Abort execution on lookup errors.
|
||||
- The default for this option is likely to change to V(true) in the future. The current default, V(false), is used for
|
||||
backwards compatibility, and results in empty strings or the string V(NXDOMAIN) in the result in case of errors.
|
||||
default: false
|
||||
type: bool
|
||||
version_added: 5.4.0
|
||||
real_empty:
|
||||
description:
|
||||
- Return empty result without empty strings, and return empty list instead of V(NXDOMAIN).
|
||||
- The default for this option is likely to change to V(true) in the future.
|
||||
- This option is forced to V(true) if multiple domains to be queried are specified.
|
||||
default: false
|
||||
type: bool
|
||||
version_added: 6.0.0
|
||||
class:
|
||||
description:
|
||||
- Class.
|
||||
type: str
|
||||
default: 'IN'
|
||||
tcp:
|
||||
description: Use TCP to lookup DNS records.
|
||||
default: false
|
||||
type: bool
|
||||
version_added: 7.5.0
|
||||
port:
|
||||
description: Use port as target port when looking up DNS records.
|
||||
default: 53
|
||||
type: int
|
||||
version_added: 9.5.0
|
||||
notes:
|
||||
- V(ALL) is not a record in itself, merely the listed fields are available for any record results you retrieve in the form
|
||||
of a dictionary.
|
||||
- While the plugin supports anything which C(dnspython) supports out of the box, only a subset can be converted into a dictionary.
|
||||
- If you need to obtain the AAAA record (IPv6 address), you must specify the record type explicitly. Syntax for specifying
|
||||
the record type is shown in the examples below.
|
||||
- The trailing dot in most of the examples listed is purely optional, but is specified for completeness/correctness sake.
|
||||
"""
|
||||
|
||||
EXAMPLES = r"""
|
||||
- name: Simple A record (IPV4 address) lookup for example.com
|
||||
ansible.builtin.debug:
|
||||
msg: "{{ lookup('community.general.dig', 'example.com.')}}"
|
||||
|
||||
- name: "The TXT record for example.org."
|
||||
ansible.builtin.debug:
|
||||
msg: "{{ lookup('community.general.dig', 'example.org.', qtype='TXT') }}"
|
||||
|
||||
- name: "The TXT record for example.org, alternative syntax."
|
||||
ansible.builtin.debug:
|
||||
msg: "{{ lookup('community.general.dig', 'example.org./TXT') }}"
|
||||
|
||||
- name: use in a loop
|
||||
ansible.builtin.debug:
|
||||
msg: "MX record for gmail.com {{ item }}"
|
||||
with_items: "{{ lookup('community.general.dig', 'gmail.com./MX', wantlist=true) }}"
|
||||
|
||||
- name: Lookup multiple names at once
|
||||
ansible.builtin.debug:
|
||||
msg: "A record found {{ item }}"
|
||||
loop: "{{ query('community.general.dig', 'example.org.', 'example.com.', 'gmail.com.') }}"
|
||||
|
||||
- name: Lookup multiple names at once (from list variable)
|
||||
ansible.builtin.debug:
|
||||
msg: "A record found {{ item }}"
|
||||
loop: "{{ query('community.general.dig', *hosts) }}"
|
||||
vars:
|
||||
hosts:
|
||||
- example.org.
|
||||
- example.com.
|
||||
- gmail.com.
|
||||
|
||||
- ansible.builtin.debug:
|
||||
msg: "Reverse DNS for 192.0.2.5 is {{ lookup('community.general.dig', '192.0.2.5/PTR') }}"
|
||||
- ansible.builtin.debug:
|
||||
msg: "Reverse DNS for 192.0.2.5 is {{ lookup('community.general.dig', '5.2.0.192.in-addr.arpa./PTR') }}"
|
||||
- ansible.builtin.debug:
|
||||
msg: "Reverse DNS for 192.0.2.5 is {{ lookup('community.general.dig', '5.2.0.192.in-addr.arpa.', qtype='PTR') }}"
|
||||
- ansible.builtin.debug:
|
||||
msg: "Querying 198.51.100.23 for IPv4 address for example.com. produces {{ lookup('dig', 'example.com', '@198.51.100.23') }}"
|
||||
|
||||
- ansible.builtin.debug:
|
||||
msg: "XMPP service for gmail.com. is available at {{ item.target }} on port {{ item.port }}"
|
||||
with_items: "{{ lookup('community.general.dig', '_xmpp-server._tcp.gmail.com./SRV', flat=0, wantlist=true) }}"
|
||||
|
||||
- name: Retry nameservers that return SERVFAIL
|
||||
ansible.builtin.debug:
|
||||
msg: "{{ lookup('community.general.dig', 'example.org./A', retry_servfail=true) }}"
|
||||
"""
|
||||
|
||||
RETURN = r"""
|
||||
_list:
|
||||
description:
|
||||
- List of composed strings or of dictionaries, with fields depending
|
||||
on query type.
|
||||
type: list
|
||||
elements: raw
|
||||
contains:
|
||||
ALL:
|
||||
description:
|
||||
- C(owner), C(ttl), C(type).
|
||||
A:
|
||||
description:
|
||||
- C(address).
|
||||
AAAA:
|
||||
description:
|
||||
- C(address).
|
||||
CAA:
|
||||
description:
|
||||
- C(flags).
|
||||
- C(tag).
|
||||
- C(value).
|
||||
version_added: 6.3.0
|
||||
CNAME:
|
||||
description:
|
||||
- C(target).
|
||||
DNAME:
|
||||
description:
|
||||
- C(target).
|
||||
DNSKEY:
|
||||
description:
|
||||
- C(flags), C(algorithm), C(protocol), C(key).
|
||||
DS:
|
||||
description:
|
||||
- C(algorithm), C(digest_type), C(key_tag), C(digest).
|
||||
HINFO:
|
||||
description:
|
||||
- C(cpu), C(os).
|
||||
LOC:
|
||||
description:
|
||||
- C(latitude), C(longitude), C(altitude), C(size), C(horizontal_precision), C(vertical_precision).
|
||||
MX:
|
||||
description:
|
||||
- C(preference), C(exchange).
|
||||
NAPTR:
|
||||
description:
|
||||
- C(order), C(preference), C(flags), C(service), C(regexp), C(replacement).
|
||||
NS:
|
||||
description:
|
||||
- C(target).
|
||||
NSEC3PARAM:
|
||||
description:
|
||||
- C(algorithm), C(flags), C(iterations), C(salt).
|
||||
PTR:
|
||||
description:
|
||||
- C(target).
|
||||
RP:
|
||||
description:
|
||||
- C(mbox), C(txt).
|
||||
SOA:
|
||||
description:
|
||||
- C(mname), C(rname), C(serial), C(refresh), C(retry), C(expire), C(minimum).
|
||||
SPF:
|
||||
description:
|
||||
- C(strings).
|
||||
SRV:
|
||||
description:
|
||||
- C(priority), C(weight), C(port), C(target).
|
||||
SSHFP:
|
||||
description:
|
||||
- C(algorithm), C(fp_type), C(fingerprint).
|
||||
TLSA:
|
||||
description:
|
||||
- C(usage), C(selector), C(mtype), C(cert).
|
||||
TXT:
|
||||
description:
|
||||
- C(strings).
|
||||
"""
|
||||
|
||||
import socket
|
||||
|
||||
from ansible.errors import AnsibleError
|
||||
from ansible.module_utils.parsing.convert_bool import boolean
|
||||
from ansible.plugins.lookup import LookupBase
|
||||
from ansible.utils.display import Display
|
||||
|
||||
from ansible_collections.community.general.plugins.plugin_utils._lookup import check_for_wrong_terms
|
||||
|
||||
try:
|
||||
import dns.exception
|
||||
import dns.name
|
||||
import dns.rdataclass
|
||||
import dns.resolver
|
||||
import dns.reversename
|
||||
from dns.rdatatype import (
|
||||
AAAA,
|
||||
CAA,
|
||||
CNAME,
|
||||
DNAME,
|
||||
DNSKEY,
|
||||
DS,
|
||||
HINFO,
|
||||
LOC,
|
||||
MX,
|
||||
NAPTR,
|
||||
NS,
|
||||
NSEC3PARAM,
|
||||
PTR,
|
||||
RP,
|
||||
SOA,
|
||||
SPF,
|
||||
SRV,
|
||||
SSHFP,
|
||||
TLSA,
|
||||
TXT,
|
||||
A,
|
||||
)
|
||||
|
||||
HAVE_DNS = True
|
||||
except ImportError:
|
||||
HAVE_DNS = False
|
||||
|
||||
|
||||
display = Display()
|
||||
|
||||
|
||||
def make_rdata_dict(rdata):
|
||||
"""While the 'dig' lookup plugin supports anything which dnspython supports
|
||||
out of the box, the following supported_types list describes which
|
||||
DNS query types we can convert to a dict.
|
||||
|
||||
Note: adding support for RRSIG is hard work. :)
|
||||
"""
|
||||
supported_types = {
|
||||
A: ["address"],
|
||||
AAAA: ["address"],
|
||||
CAA: ["flags", "tag", "value"],
|
||||
CNAME: ["target"],
|
||||
DNAME: ["target"],
|
||||
DNSKEY: ["flags", "algorithm", "protocol", "key"],
|
||||
DS: ["algorithm", "digest_type", "key_tag", "digest"],
|
||||
HINFO: ["cpu", "os"],
|
||||
LOC: ["latitude", "longitude", "altitude", "size", "horizontal_precision", "vertical_precision"],
|
||||
MX: ["preference", "exchange"],
|
||||
NAPTR: ["order", "preference", "flags", "service", "regexp", "replacement"],
|
||||
NS: ["target"],
|
||||
NSEC3PARAM: ["algorithm", "flags", "iterations", "salt"],
|
||||
PTR: ["target"],
|
||||
RP: ["mbox", "txt"],
|
||||
# RRSIG: ['type_covered', 'algorithm', 'labels', 'original_ttl', 'expiration', 'inception', 'key_tag', 'signer', 'signature'],
|
||||
SOA: ["mname", "rname", "serial", "refresh", "retry", "expire", "minimum"],
|
||||
SPF: ["strings"],
|
||||
SRV: ["priority", "weight", "port", "target"],
|
||||
SSHFP: ["algorithm", "fp_type", "fingerprint"],
|
||||
TLSA: ["usage", "selector", "mtype", "cert"],
|
||||
TXT: ["strings"],
|
||||
}
|
||||
|
||||
rd = {}
|
||||
|
||||
if rdata.rdtype in supported_types:
|
||||
fields = supported_types[rdata.rdtype]
|
||||
for f in fields:
|
||||
val = rdata.__getattribute__(f)
|
||||
|
||||
if isinstance(val, dns.name.Name):
|
||||
val = dns.name.Name.to_text(val)
|
||||
|
||||
if rdata.rdtype == DS and f == "digest":
|
||||
val = dns.rdata._hexify(rdata.digest).replace(" ", "")
|
||||
if rdata.rdtype == DNSKEY and f == "algorithm":
|
||||
val = int(val)
|
||||
if rdata.rdtype == DNSKEY and f == "key":
|
||||
val = dns.rdata._base64ify(rdata.key).replace(" ", "")
|
||||
if rdata.rdtype == NSEC3PARAM and f == "salt":
|
||||
val = dns.rdata._hexify(rdata.salt).replace(" ", "")
|
||||
if rdata.rdtype == SSHFP and f == "fingerprint":
|
||||
val = dns.rdata._hexify(rdata.fingerprint).replace(" ", "")
|
||||
if rdata.rdtype == TLSA and f == "cert":
|
||||
val = dns.rdata._hexify(rdata.cert).replace(" ", "")
|
||||
|
||||
rd[f] = val
|
||||
|
||||
return rd
|
||||
|
||||
|
||||
# ==============================================================
|
||||
# dig: Lookup DNS records
|
||||
#
|
||||
# --------------------------------------------------------------
|
||||
|
||||
|
||||
class LookupModule(LookupBase):
|
||||
def run(self, terms, variables=None, **kwargs):
|
||||
"""
|
||||
terms contains a string with things to `dig' for. We support the
|
||||
following formats:
|
||||
example.com # A record
|
||||
example.com qtype=A # same
|
||||
example.com/TXT # specific qtype
|
||||
example.com qtype=txt # same
|
||||
192.0.2.23/PTR # reverse PTR
|
||||
^^ shortcut for 23.2.0.192.in-addr.arpa/PTR
|
||||
example.net/AAAA @nameserver # query specified server
|
||||
^^^ can be comma-sep list of names/addresses
|
||||
|
||||
... flat=0 # returns a dict; default is 1 == string
|
||||
"""
|
||||
if HAVE_DNS is False:
|
||||
raise AnsibleError("The dig lookup requires the python 'dnspython' library and it is not installed")
|
||||
|
||||
self.set_options(var_options=variables, direct=kwargs)
|
||||
check_for_wrong_terms(self, direct=kwargs)
|
||||
|
||||
# Create Resolver object so that we can set NS if necessary
|
||||
myres = dns.resolver.Resolver(configure=True)
|
||||
edns_size = 4096
|
||||
myres.use_edns(0, ednsflags=dns.flags.DO, payload=edns_size)
|
||||
|
||||
domains = []
|
||||
nameservers = []
|
||||
qtype = self.get_option("qtype")
|
||||
flat = self.get_option("flat")
|
||||
fail_on_error = self.get_option("fail_on_error")
|
||||
real_empty = self.get_option("real_empty")
|
||||
tcp = self.get_option("tcp")
|
||||
port = self.get_option("port")
|
||||
try:
|
||||
rdclass = dns.rdataclass.from_text(self.get_option("class"))
|
||||
except Exception as e:
|
||||
raise AnsibleError(f"dns lookup illegal CLASS: {e}") from e
|
||||
myres.retry_servfail = self.get_option("retry_servfail")
|
||||
|
||||
for t in terms:
|
||||
if t.startswith("@"): # e.g. "@10.0.1.2,192.0.2.1" is ok.
|
||||
nsset = t[1:].split(",")
|
||||
for ns in nsset:
|
||||
# Check if we have a valid IP address. If so, use that, otherwise
|
||||
# try to resolve name to address using system's resolver. If that
|
||||
# fails we bail out.
|
||||
try:
|
||||
socket.inet_aton(ns)
|
||||
nameservers.append(ns)
|
||||
except Exception:
|
||||
try:
|
||||
nsaddr = dns.resolver.query(ns)[0].address
|
||||
nameservers.append(nsaddr)
|
||||
except Exception as e:
|
||||
raise AnsibleError(f"dns lookup NS: {e}") from e
|
||||
continue
|
||||
if "=" in t:
|
||||
try:
|
||||
opt, arg = t.split("=", 1)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if opt == "qtype":
|
||||
qtype = arg.upper()
|
||||
elif opt == "flat":
|
||||
flat = int(arg)
|
||||
elif opt == "class":
|
||||
try:
|
||||
rdclass = dns.rdataclass.from_text(arg)
|
||||
except Exception as e:
|
||||
raise AnsibleError(f"dns lookup illegal CLASS: {e}") from e
|
||||
elif opt == "retry_servfail":
|
||||
myres.retry_servfail = boolean(arg)
|
||||
elif opt == "fail_on_error":
|
||||
fail_on_error = boolean(arg)
|
||||
elif opt == "real_empty":
|
||||
real_empty = boolean(arg)
|
||||
elif opt == "tcp":
|
||||
tcp = boolean(arg)
|
||||
|
||||
continue
|
||||
|
||||
if "/" in t:
|
||||
try:
|
||||
domain, qtype = t.split("/")
|
||||
domains.append(domain)
|
||||
except Exception:
|
||||
domains.append(t)
|
||||
else:
|
||||
domains.append(t)
|
||||
|
||||
# print "--- domain = {domain} qtype={qtype} rdclass={rdclass}"
|
||||
|
||||
if port:
|
||||
myres.port = port
|
||||
if len(nameservers) > 0:
|
||||
myres.nameservers = nameservers
|
||||
|
||||
if qtype.upper() == "PTR":
|
||||
reversed_domains = []
|
||||
for domain in domains:
|
||||
try:
|
||||
n = dns.reversename.from_address(domain)
|
||||
reversed_domains.append(n.to_text())
|
||||
except dns.exception.SyntaxError:
|
||||
pass
|
||||
except Exception as e:
|
||||
raise AnsibleError(f"dns.reversename unhandled exception {e}") from e
|
||||
domains = reversed_domains
|
||||
|
||||
if len(domains) > 1:
|
||||
real_empty = True
|
||||
|
||||
ret = []
|
||||
|
||||
for domain in domains:
|
||||
try:
|
||||
answers = myres.query(domain, qtype, rdclass=rdclass, tcp=tcp)
|
||||
for rdata in answers:
|
||||
s = rdata.to_text()
|
||||
if qtype.upper() == "TXT":
|
||||
s = s[1:-1] # Strip outside quotes on TXT rdata
|
||||
|
||||
if flat:
|
||||
ret.append(s)
|
||||
else:
|
||||
try:
|
||||
rd = make_rdata_dict(rdata)
|
||||
rd["owner"] = answers.canonical_name.to_text()
|
||||
rd["type"] = dns.rdatatype.to_text(rdata.rdtype)
|
||||
rd["ttl"] = answers.rrset.ttl
|
||||
rd["class"] = dns.rdataclass.to_text(rdata.rdclass)
|
||||
|
||||
ret.append(rd)
|
||||
except Exception as err:
|
||||
if fail_on_error:
|
||||
raise AnsibleError(f"Lookup failed: {err}") from err
|
||||
ret.append(str(err))
|
||||
|
||||
except dns.resolver.NXDOMAIN as err:
|
||||
if fail_on_error:
|
||||
raise AnsibleError(f"Lookup failed: {err}") from err
|
||||
if not real_empty:
|
||||
ret.append("NXDOMAIN")
|
||||
except (dns.resolver.NoAnswer, dns.resolver.Timeout, dns.resolver.NoNameservers) as err:
|
||||
if fail_on_error:
|
||||
raise AnsibleError(f"Lookup failed: {err}") from err
|
||||
if not real_empty:
|
||||
ret.append("")
|
||||
except dns.exception.DNSException as err:
|
||||
raise AnsibleError(f"dns.resolver unhandled exception {err}") from err
|
||||
|
||||
return ret
|
||||
@@ -0,0 +1,115 @@
|
||||
# Copyright (c) 2012, Jan-Piet Mens <jpmens(at)gmail.com>
|
||||
# Copyright (c) 2017 Ansible Project
|
||||
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
from __future__ import annotations
|
||||
|
||||
DOCUMENTATION = r"""
|
||||
name: dnstxt
|
||||
author: Jan-Piet Mens (@jpmens) <jpmens(at)gmail.com>
|
||||
short_description: Query a domain(s)'s DNS txt fields
|
||||
requirements:
|
||||
- dns/dns.resolver (python library)
|
||||
description:
|
||||
- Uses a python library to return the DNS TXT record for a domain.
|
||||
options:
|
||||
_terms:
|
||||
description: Domain or list of domains to query TXT records from.
|
||||
required: true
|
||||
type: list
|
||||
elements: string
|
||||
real_empty:
|
||||
description:
|
||||
- Return empty result without empty strings, and return empty list instead of V(NXDOMAIN).
|
||||
- The default for this option is likely to change to V(true) in the future.
|
||||
default: false
|
||||
type: bool
|
||||
version_added: 6.0.0
|
||||
"""
|
||||
|
||||
EXAMPLES = r"""
|
||||
- name: show txt entry
|
||||
ansible.builtin.debug:
|
||||
msg: "{{lookup('community.general.dnstxt', ['test.example.com'])}}"
|
||||
|
||||
- name: iterate over txt entries
|
||||
ansible.builtin.debug:
|
||||
msg: "{{item}}"
|
||||
with_community.general.dnstxt:
|
||||
- 'test.example.com'
|
||||
- 'other.example.com'
|
||||
- 'last.example.com'
|
||||
|
||||
- name: iterate of a comma delimited DNS TXT entry
|
||||
ansible.builtin.debug:
|
||||
msg: "{{item}}"
|
||||
with_community.general.dnstxt: "{{lookup('community.general.dnstxt', ['test.example.com']).split(',')}}"
|
||||
"""
|
||||
|
||||
RETURN = r"""
|
||||
_list:
|
||||
description:
|
||||
- Values returned by the DNS TXT record.
|
||||
type: list
|
||||
"""
|
||||
|
||||
HAVE_DNS = False
|
||||
try:
|
||||
import dns.resolver
|
||||
from dns.exception import DNSException
|
||||
|
||||
HAVE_DNS = True
|
||||
except ImportError:
|
||||
pass
|
||||
|
||||
from ansible.errors import AnsibleError
|
||||
from ansible.plugins.lookup import LookupBase
|
||||
|
||||
from ansible_collections.community.general.plugins.plugin_utils._lookup import check_for_wrong_terms
|
||||
|
||||
# ==============================================================
|
||||
# DNSTXT: DNS TXT records
|
||||
#
|
||||
# key=domainname
|
||||
# TODO: configurable resolver IPs
|
||||
# --------------------------------------------------------------
|
||||
|
||||
|
||||
class LookupModule(LookupBase):
|
||||
def run(self, terms, variables=None, **kwargs):
|
||||
self.set_options(var_options=variables, direct=kwargs)
|
||||
check_for_wrong_terms(self, direct=kwargs)
|
||||
|
||||
if HAVE_DNS is False:
|
||||
raise AnsibleError("Can't LOOKUP(dnstxt): module dns.resolver is not installed")
|
||||
|
||||
real_empty = self.get_option("real_empty")
|
||||
|
||||
ret = []
|
||||
for term in terms:
|
||||
domain = term.split()[0]
|
||||
string = []
|
||||
try:
|
||||
answers = dns.resolver.query(domain, "TXT")
|
||||
for rdata in answers:
|
||||
s = rdata.to_text()
|
||||
string.append(s[1:-1]) # Strip outside quotes on TXT rdata
|
||||
|
||||
except dns.resolver.NXDOMAIN:
|
||||
if real_empty:
|
||||
continue
|
||||
string = "NXDOMAIN"
|
||||
except dns.resolver.Timeout:
|
||||
if real_empty:
|
||||
continue
|
||||
string = ""
|
||||
except dns.resolver.NoAnswer:
|
||||
if real_empty:
|
||||
continue
|
||||
string = ""
|
||||
except DNSException as e:
|
||||
raise AnsibleError(f"dns.resolver unhandled exception {e}") from e
|
||||
|
||||
ret.append("".join(string))
|
||||
|
||||
return ret
|
||||
@@ -0,0 +1,146 @@
|
||||
# Copyright (c) 2020, Adam Migus <adam@migus.org>
|
||||
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
from __future__ import annotations
|
||||
|
||||
DOCUMENTATION = r"""
|
||||
name: dsv
|
||||
author: Adam Migus (@amigus) <adam@migus.org>
|
||||
short_description: Get secrets from Thycotic DevOps Secrets Vault
|
||||
version_added: 1.0.0
|
||||
description:
|
||||
- Uses the Thycotic DevOps Secrets Vault Python SDK to get Secrets from a DSV O(tenant) using a O(client_id) and O(client_secret).
|
||||
requirements:
|
||||
- python-dsv-sdk - https://pypi.org/project/python-dsv-sdk/
|
||||
options:
|
||||
_terms:
|
||||
description: The path to the secret, for example V(/staging/servers/web1).
|
||||
required: true
|
||||
tenant:
|
||||
description: The first format parameter in the default O(url_template).
|
||||
type: string
|
||||
env:
|
||||
- name: DSV_TENANT
|
||||
ini:
|
||||
- section: dsv_lookup
|
||||
key: tenant
|
||||
required: true
|
||||
tld:
|
||||
default: com
|
||||
description: The top-level domain of the tenant; the second format parameter in the default O(url_template).
|
||||
type: string
|
||||
env:
|
||||
- name: DSV_TLD
|
||||
ini:
|
||||
- section: dsv_lookup
|
||||
key: tld
|
||||
required: false
|
||||
client_id:
|
||||
description: The client_id with which to request the Access Grant.
|
||||
type: string
|
||||
env:
|
||||
- name: DSV_CLIENT_ID
|
||||
ini:
|
||||
- section: dsv_lookup
|
||||
key: client_id
|
||||
required: true
|
||||
client_secret:
|
||||
description: The client secret associated with the specific O(client_id).
|
||||
type: string
|
||||
env:
|
||||
- name: DSV_CLIENT_SECRET
|
||||
ini:
|
||||
- section: dsv_lookup
|
||||
key: client_secret
|
||||
required: true
|
||||
secret: true
|
||||
url_template:
|
||||
default: https://{}.secretsvaultcloud.{}/v1
|
||||
description: The path to prepend to the base URL to form a valid REST API request.
|
||||
type: string
|
||||
env:
|
||||
- name: DSV_URL_TEMPLATE
|
||||
ini:
|
||||
- section: dsv_lookup
|
||||
key: url_template
|
||||
required: false
|
||||
"""
|
||||
|
||||
RETURN = r"""
|
||||
_list:
|
||||
description:
|
||||
- One or more JSON responses to C(GET /secrets/{path}).
|
||||
- See U(https://dsv.thycotic.com/api/index.html#operation/getSecret).
|
||||
type: list
|
||||
elements: dict
|
||||
"""
|
||||
|
||||
EXAMPLES = r"""
|
||||
- hosts: localhost
|
||||
vars:
|
||||
secret: "{{ lookup('community.general.dsv', '/test/secret') }}"
|
||||
tasks:
|
||||
- ansible.builtin.debug:
|
||||
msg: 'the password is {{ secret["data"]["password"] }}'
|
||||
"""
|
||||
|
||||
from ansible.errors import AnsibleError, AnsibleOptionsError
|
||||
|
||||
from ansible_collections.community.general.plugins.plugin_utils._lookup import check_for_wrong_terms
|
||||
|
||||
sdk_is_missing = False
|
||||
|
||||
try:
|
||||
from thycotic.secrets.vault import (
|
||||
SecretsVault,
|
||||
SecretsVaultError,
|
||||
)
|
||||
except ImportError:
|
||||
sdk_is_missing = True
|
||||
|
||||
from ansible.plugins.lookup import LookupBase
|
||||
from ansible.utils.display import Display
|
||||
|
||||
display = Display()
|
||||
|
||||
|
||||
class LookupModule(LookupBase):
|
||||
@staticmethod
|
||||
def Client(vault_parameters):
|
||||
try:
|
||||
vault = SecretsVault(**vault_parameters)
|
||||
return vault
|
||||
except TypeError as e:
|
||||
raise AnsibleError("python-dsv-sdk==0.0.1 must be installed to use this plugin") from e
|
||||
|
||||
def run(self, terms, variables, **kwargs):
|
||||
if sdk_is_missing:
|
||||
raise AnsibleError("python-dsv-sdk==0.0.1 must be installed to use this plugin")
|
||||
|
||||
self.set_options(var_options=variables, direct=kwargs)
|
||||
check_for_wrong_terms(self, direct=kwargs)
|
||||
|
||||
vault = LookupModule.Client(
|
||||
{
|
||||
"tenant": self.get_option("tenant"),
|
||||
"client_id": self.get_option("client_id"),
|
||||
"client_secret": self.get_option("client_secret"),
|
||||
"tld": self.get_option("tld"),
|
||||
"url_template": self.get_option("url_template"),
|
||||
}
|
||||
)
|
||||
result = []
|
||||
|
||||
for term in terms:
|
||||
display.debug(f"dsv_lookup term: {term}")
|
||||
try:
|
||||
path = term.lstrip("[/:]")
|
||||
|
||||
if path == "":
|
||||
raise AnsibleOptionsError(f"Invalid secret path: {term}")
|
||||
|
||||
display.vvv(f"DevOps Secrets Vault GET /secrets/{path}")
|
||||
result.append(vault.get_secret_json(path))
|
||||
except SecretsVaultError as error:
|
||||
raise AnsibleError(f"DevOps Secrets Vault lookup failure: {error.message}") from error
|
||||
return result
|
||||
@@ -0,0 +1,174 @@
|
||||
# Copyright (c) 2013, Jan-Piet Mens <jpmens(at)gmail.com>
|
||||
# (m) 2016, Mihai Moldovanu <mihaim@tfm.ro>
|
||||
# (m) 2017, Juan Manuel Parrilla <jparrill@redhat.com>
|
||||
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
DOCUMENTATION = r"""
|
||||
author:
|
||||
- Jan-Piet Mens (@jpmens)
|
||||
name: etcd
|
||||
short_description: Get info from an etcd server
|
||||
description:
|
||||
- Retrieves data from an etcd server.
|
||||
options:
|
||||
_terms:
|
||||
description:
|
||||
- The list of keys to lookup on the etcd server.
|
||||
type: list
|
||||
elements: string
|
||||
required: true
|
||||
url:
|
||||
description:
|
||||
- Environment variable with the URL for the etcd server.
|
||||
type: string
|
||||
default: 'http://127.0.0.1:4001'
|
||||
env:
|
||||
- name: ANSIBLE_ETCD_URL
|
||||
version:
|
||||
description:
|
||||
- Environment variable with the etcd protocol version.
|
||||
type: string
|
||||
default: 'v1'
|
||||
env:
|
||||
- name: ANSIBLE_ETCD_VERSION
|
||||
validate_certs:
|
||||
description:
|
||||
- Toggle checking that the ssl certificates are valid, you normally only want to turn this off with self-signed certs.
|
||||
default: true
|
||||
type: boolean
|
||||
seealso:
|
||||
- module: community.general.etcd3
|
||||
- plugin: community.general.etcd3
|
||||
plugin_type: lookup
|
||||
"""
|
||||
|
||||
EXAMPLES = r"""
|
||||
- name: "a value from a locally running etcd"
|
||||
ansible.builtin.debug:
|
||||
msg: "{{ lookup('community.general.etcd', 'foo/bar') }}"
|
||||
|
||||
- name: "values from multiple folders on a locally running etcd"
|
||||
ansible.builtin.debug:
|
||||
msg: "{{ lookup('community.general.etcd', 'foo', 'bar', 'baz') }}"
|
||||
|
||||
- name: "you can set server options inline"
|
||||
ansible.builtin.debug:
|
||||
msg: "{{ lookup('community.general.etcd', 'foo', version='v2', url='http://192.168.0.27:4001') }}"
|
||||
"""
|
||||
|
||||
RETURN = r"""
|
||||
_raw:
|
||||
description:
|
||||
- List of values associated with input keys.
|
||||
type: list
|
||||
elements: string
|
||||
"""
|
||||
|
||||
import json
|
||||
|
||||
from ansible.module_utils.urls import open_url
|
||||
from ansible.plugins.lookup import LookupBase
|
||||
|
||||
from ansible_collections.community.general.plugins.plugin_utils._lookup import check_for_wrong_terms
|
||||
|
||||
# this can be made configurable, not should not use ansible.cfg
|
||||
#
|
||||
# Made module configurable from playbooks:
|
||||
# If etcd v2 running on host 192.168.1.21 on port 2379
|
||||
# we can use the following in a playbook to retrieve /tfm/network/config key
|
||||
#
|
||||
# - ansible.builtin.debug: msg={{lookup('etcd','/tfm/network/config', url='http://192.168.1.21:2379' , version='v2')}}
|
||||
#
|
||||
# Example Output:
|
||||
#
|
||||
# TASK [debug] *******************************************************************
|
||||
# ok: [localhost] => {
|
||||
# "msg": {
|
||||
# "Backend": {
|
||||
# "Type": "vxlan"
|
||||
# },
|
||||
# "Network": "172.30.0.0/16",
|
||||
# "SubnetLen": 24
|
||||
# }
|
||||
# }
|
||||
#
|
||||
#
|
||||
#
|
||||
#
|
||||
|
||||
|
||||
class Etcd:
|
||||
def __init__(self, url, version, validate_certs):
|
||||
self.url = url
|
||||
self.version = version
|
||||
self.baseurl = f"{self.url}/{self.version}/keys"
|
||||
self.validate_certs = validate_certs
|
||||
|
||||
def _parse_node(self, node):
|
||||
# This function will receive all etcd tree,
|
||||
# if the level requested has any node, the recursion starts
|
||||
# create a list in the dir variable and it is passed to the
|
||||
# recursive function, and so on, if we get a variable,
|
||||
# the function will create a key-value at this level and
|
||||
# undoing the loop.
|
||||
path = {}
|
||||
if node.get("dir", False):
|
||||
for n in node.get("nodes", []):
|
||||
path[n["key"].split("/")[-1]] = self._parse_node(n)
|
||||
|
||||
else:
|
||||
path = node["value"]
|
||||
|
||||
return path
|
||||
|
||||
def get(self, key):
|
||||
url = f"{self.baseurl}/{key}?recursive=true"
|
||||
data = None
|
||||
value = {}
|
||||
try:
|
||||
r = open_url(url, validate_certs=self.validate_certs)
|
||||
data = r.read()
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
try:
|
||||
# I will not support Version 1 of etcd for folder parsing
|
||||
item = json.loads(data)
|
||||
if self.version == "v1":
|
||||
# When ETCD are working with just v1
|
||||
if "value" in item:
|
||||
value = item["value"]
|
||||
else:
|
||||
if "node" in item:
|
||||
# When a usual result from ETCD
|
||||
value = self._parse_node(item["node"])
|
||||
|
||||
if "errorCode" in item:
|
||||
# Here return an error when an unknown entry responds
|
||||
value = "ENOENT"
|
||||
except Exception:
|
||||
raise
|
||||
|
||||
return value
|
||||
|
||||
|
||||
class LookupModule(LookupBase):
|
||||
def run(self, terms, variables, **kwargs):
|
||||
self.set_options(var_options=variables, direct=kwargs)
|
||||
check_for_wrong_terms(self, direct=kwargs)
|
||||
|
||||
validate_certs = self.get_option("validate_certs")
|
||||
url = self.get_option("url")
|
||||
version = self.get_option("version")
|
||||
|
||||
etcd = Etcd(url=url, version=version, validate_certs=validate_certs)
|
||||
|
||||
ret = []
|
||||
for term in terms:
|
||||
key = term.split()[0]
|
||||
value = etcd.get(key)
|
||||
ret.append(value)
|
||||
return ret
|
||||
@@ -0,0 +1,264 @@
|
||||
#
|
||||
# Copyright (c) 2020, SCC France, Eric Belhomme <ebelhomme@fr.scc.com>
|
||||
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
DOCUMENTATION = r"""
|
||||
author:
|
||||
- Eric Belhomme (@eric-belhomme) <ebelhomme@fr.scc.com>
|
||||
version_added: '0.2.0'
|
||||
name: etcd3
|
||||
short_description: Get key values from etcd3 server
|
||||
description:
|
||||
- Retrieves key values and/or key prefixes from etcd3 server using its native gRPC API.
|
||||
- Try to reuse M(community.general.etcd3) options for connection parameters, but add support for some E(ETCDCTL_*) environment
|
||||
variables.
|
||||
- See U(https://github.com/etcd-io/etcd/tree/master/Documentation/op-guide) for etcd overview.
|
||||
options:
|
||||
_terms:
|
||||
description:
|
||||
- The list of keys (or key prefixes) to look up on the etcd3 server.
|
||||
type: list
|
||||
elements: str
|
||||
required: true
|
||||
prefix:
|
||||
description:
|
||||
- Look for key or prefix key.
|
||||
type: bool
|
||||
default: false
|
||||
endpoints:
|
||||
description:
|
||||
- Counterpart of E(ETCDCTL_ENDPOINTS) environment variable. Specify the etcd3 connection with an URL form, for example
|
||||
V(https://hostname:2379), or V(<host>:<port>) form.
|
||||
- The V(host) part is overwritten by O(host) option, if defined.
|
||||
- The V(port) part is overwritten by O(port) option, if defined.
|
||||
- Note that specifying V(https://) in the endpoint URL does not by itself enable TLS. To connect to an HTTPS etcd3
|
||||
endpoint, you must provide O(ca_cert) (and optionally O(cert_cert) and O(cert_key)).
|
||||
env:
|
||||
- name: ETCDCTL_ENDPOINTS
|
||||
default: '127.0.0.1:2379'
|
||||
type: str
|
||||
host:
|
||||
description:
|
||||
- Etcd3 listening client host.
|
||||
- Takes precedence over O(endpoints).
|
||||
- Must be a bare hostname or IP address without a URL scheme. If a V(https://) or V(http://) prefix is present,
|
||||
it will be stripped automatically.
|
||||
type: str
|
||||
port:
|
||||
description:
|
||||
- Etcd3 listening client port.
|
||||
- Takes precedence over O(endpoints).
|
||||
type: int
|
||||
ca_cert:
|
||||
description:
|
||||
- Etcd3 CA authority.
|
||||
- Required to enable TLS when connecting to an HTTPS etcd3 endpoint.
|
||||
env:
|
||||
- name: ETCDCTL_CACERT
|
||||
type: path
|
||||
cert_cert:
|
||||
description:
|
||||
- Etcd3 client certificate.
|
||||
env:
|
||||
- name: ETCDCTL_CERT
|
||||
type: path
|
||||
cert_key:
|
||||
description:
|
||||
- Etcd3 client private key.
|
||||
env:
|
||||
- name: ETCDCTL_KEY
|
||||
type: path
|
||||
timeout:
|
||||
description:
|
||||
- Client timeout.
|
||||
default: 60
|
||||
env:
|
||||
- name: ETCDCTL_DIAL_TIMEOUT
|
||||
type: int
|
||||
user:
|
||||
description:
|
||||
- Authenticated user name.
|
||||
env:
|
||||
- name: ETCDCTL_USER
|
||||
type: str
|
||||
password:
|
||||
description:
|
||||
- Authenticated user password.
|
||||
env:
|
||||
- name: ETCDCTL_PASSWORD
|
||||
type: str
|
||||
secret: true
|
||||
|
||||
notes:
|
||||
- O(host) and O(port) options take precedence over O(endpoints) option.
|
||||
- The recommended way to connect to etcd3 server is using E(ETCDCTL_ENDPOINT) environment variable and keep O(endpoints),
|
||||
O(host), and O(port) unused.
|
||||
- To connect to an HTTPS etcd3 endpoint, the O(ca_cert) option must be provided. Merely specifying V(https://) in
|
||||
O(endpoints) is not sufficient to enable TLS.
|
||||
seealso:
|
||||
- module: community.general.etcd3
|
||||
- plugin: community.general.etcd
|
||||
plugin_type: lookup
|
||||
|
||||
requirements:
|
||||
- "etcd3 >= 0.10"
|
||||
"""
|
||||
|
||||
EXAMPLES = r"""
|
||||
- name: "a value from a locally running etcd"
|
||||
ansible.builtin.debug:
|
||||
msg: "{{ lookup('community.general.etcd3', 'foo/bar') }}"
|
||||
|
||||
- name: "values from multiple folders on a locally running etcd"
|
||||
ansible.builtin.debug:
|
||||
msg: "{{ lookup('community.general.etcd3', 'foo', 'bar', 'baz') }}"
|
||||
|
||||
- name: "look for a key prefix"
|
||||
ansible.builtin.debug:
|
||||
msg: "{{ lookup('community.general.etcd3', '/foo/bar', prefix=True) }}"
|
||||
|
||||
- name: "connect to etcd3 with a client certificate"
|
||||
ansible.builtin.debug:
|
||||
msg: "{{ lookup('community.general.etcd3', 'foo/bar', cert_cert='/etc/ssl/etcd/client.pem', cert_key='/etc/ssl/etcd/client.key') }}"
|
||||
|
||||
- name: "connect to etcd3 over HTTPS"
|
||||
ansible.builtin.debug:
|
||||
msg: "{{ lookup('community.general.etcd3', 'foo/bar', endpoints='https://etcd.example.com:2379', ca_cert='/etc/ssl/etcd/ca.pem') }}"
|
||||
"""
|
||||
|
||||
RETURN = r"""
|
||||
_raw:
|
||||
description:
|
||||
- List of keys and associated values.
|
||||
type: list
|
||||
elements: dict
|
||||
contains:
|
||||
key:
|
||||
description: The element's key.
|
||||
type: str
|
||||
value:
|
||||
description: The element's value.
|
||||
type: str
|
||||
"""
|
||||
|
||||
import re
|
||||
|
||||
from ansible.errors import AnsibleLookupError
|
||||
from ansible.module_utils.basic import missing_required_lib
|
||||
from ansible.module_utils.common.text.converters import to_native
|
||||
from ansible.plugins.lookup import LookupBase
|
||||
from ansible.utils.display import Display
|
||||
|
||||
from ansible_collections.community.general.plugins.plugin_utils._lookup import check_for_wrong_terms
|
||||
|
||||
try:
|
||||
import etcd3
|
||||
|
||||
HAS_ETCD = True
|
||||
except ImportError:
|
||||
HAS_ETCD = False
|
||||
|
||||
display = Display()
|
||||
|
||||
etcd3_cnx_opts = (
|
||||
"host",
|
||||
"port",
|
||||
"ca_cert",
|
||||
"cert_key",
|
||||
"cert_cert",
|
||||
"timeout",
|
||||
"user",
|
||||
"password",
|
||||
# 'grpc_options' Etcd3Client() option currently not supported by lookup module (maybe in future ?)
|
||||
)
|
||||
|
||||
|
||||
def etcd3_client(client_params):
|
||||
try:
|
||||
etcd = etcd3.client(**client_params)
|
||||
etcd.status()
|
||||
except Exception as exp:
|
||||
raise AnsibleLookupError(f"Cannot connect to etcd cluster: {exp}") from exp
|
||||
return etcd
|
||||
|
||||
|
||||
class LookupModule(LookupBase):
|
||||
def run(self, terms, variables, **kwargs):
|
||||
self.set_options(var_options=variables, direct=kwargs)
|
||||
check_for_wrong_terms(self, direct=kwargs)
|
||||
|
||||
if not HAS_ETCD:
|
||||
display.error(missing_required_lib("etcd3"))
|
||||
return None
|
||||
|
||||
# create the etcd3 connection parameters dict to pass to etcd3 class
|
||||
client_params = {}
|
||||
|
||||
# etcd3 class expects host and port as connection parameters, so endpoints
|
||||
# must be mangled a bit to fit in this scheme.
|
||||
# so here we use a regex to extract server and port
|
||||
is_https = False
|
||||
match = re.compile(
|
||||
r"^(?P<scheme>https?://)?(?P<host>(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})|([-_\d\w\.]+))(:(?P<port>\d{1,5}))?/?$"
|
||||
).match(self.get_option("endpoints"))
|
||||
if match:
|
||||
if match.group("host"):
|
||||
client_params["host"] = match.group("host")
|
||||
if match.group("port"):
|
||||
client_params["port"] = match.group("port")
|
||||
if match.group("scheme") and match.group("scheme").startswith("https"):
|
||||
is_https = True
|
||||
|
||||
for opt in etcd3_cnx_opts:
|
||||
if self.get_option(opt):
|
||||
client_params[opt] = self.get_option(opt)
|
||||
|
||||
# strip URL scheme from host if present
|
||||
if "host" in client_params:
|
||||
host_match = re.match(r"^(?P<scheme>https?://)(?P<host>.+)$", client_params["host"])
|
||||
if host_match:
|
||||
display.warning(
|
||||
f"The host option contained a URL scheme '{host_match.group('scheme')}' which has been removed. "
|
||||
"Use a bare hostname or IP address for the host option. "
|
||||
"To enable TLS, provide the ca_cert option."
|
||||
)
|
||||
client_params["host"] = host_match.group("host")
|
||||
if host_match.group("scheme").startswith("https"):
|
||||
is_https = True
|
||||
|
||||
if is_https and not self.get_option("ca_cert"):
|
||||
display.warning(
|
||||
"An HTTPS endpoint was specified but ca_cert was not provided. "
|
||||
"The connection will be attempted without TLS. "
|
||||
"To enable TLS, provide the ca_cert option."
|
||||
)
|
||||
|
||||
cnx_log = dict(client_params)
|
||||
if "password" in cnx_log:
|
||||
cnx_log["password"] = "<redacted>"
|
||||
display.verbose(f"etcd3 connection parameters: {cnx_log}")
|
||||
|
||||
# connect to etcd3 server
|
||||
etcd = etcd3_client(client_params)
|
||||
|
||||
ret = []
|
||||
# we can pass many keys to lookup
|
||||
for term in terms:
|
||||
if self.get_option("prefix"):
|
||||
try:
|
||||
for val, meta in etcd.get_prefix(term):
|
||||
if val and meta:
|
||||
ret.append({"key": to_native(meta.key), "value": to_native(val)})
|
||||
except Exception as exp:
|
||||
display.warning(f"Caught except during etcd3.get_prefix: {exp}")
|
||||
else:
|
||||
try:
|
||||
val, meta = etcd.get(term)
|
||||
if val and meta:
|
||||
ret.append({"key": to_native(meta.key), "value": to_native(val)})
|
||||
except Exception as exp:
|
||||
display.warning(f"Caught except during etcd3.get: {exp}")
|
||||
return ret
|
||||
+261
@@ -0,0 +1,261 @@
|
||||
# Copyright (c) 2016 Dag Wieers <dag@wieers.com>
|
||||
# Copyright (c) 2017 Ansible Project
|
||||
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
from __future__ import annotations
|
||||
|
||||
DOCUMENTATION = r"""
|
||||
name: filetree
|
||||
author: Dag Wieers (@dagwieers) <dag@wieers.com>
|
||||
short_description: Recursively match all files in a directory tree
|
||||
description:
|
||||
- This lookup enables you to template a complete tree of files on a target system while retaining permissions and ownership.
|
||||
- Supports directories, files and symlinks, including SELinux and other file properties.
|
||||
- If you provide more than one path, it implements a first_found logic, and does not process entries it already processed
|
||||
in previous paths. This enables merging different trees in order of importance, or add role_vars to specific paths to
|
||||
influence different instances of the same role.
|
||||
options:
|
||||
_terms:
|
||||
description: Path(s) of files to read.
|
||||
required: true
|
||||
type: list
|
||||
elements: string
|
||||
exclude:
|
||||
description:
|
||||
- A regular expression string to exclude files. Applies to the base name of the file or directory.
|
||||
type: str
|
||||
version_added: 12.0.0
|
||||
"""
|
||||
|
||||
EXAMPLES = r"""
|
||||
- name: Create directories
|
||||
ansible.builtin.file:
|
||||
path: /web/{{ item.path }}
|
||||
state: directory
|
||||
mode: '{{ item.mode }}'
|
||||
with_community.general.filetree: web/
|
||||
when: item.state == 'directory'
|
||||
|
||||
- name: Template files (explicitly skip directories in order to use the 'src' attribute)
|
||||
ansible.builtin.template:
|
||||
src: '{{ item.src }}'
|
||||
# Your template files should be stored with a .j2 file extension,
|
||||
# but should not be deployed with it. splitext|first removes it.
|
||||
dest: /web/{{ item.path | splitext | first }}
|
||||
mode: '{{ item.mode }}'
|
||||
with_community.general.filetree: web/
|
||||
when: item.state == 'file'
|
||||
|
||||
- name: Recreate symlinks
|
||||
ansible.builtin.file:
|
||||
src: '{{ item.src }}'
|
||||
dest: /web/{{ item.path }}
|
||||
state: link
|
||||
follow: false # avoid corrupting target files if the link already exists
|
||||
force: true
|
||||
mode: '{{ item.mode }}'
|
||||
with_community.general.filetree: web/
|
||||
when: item.state == 'link'
|
||||
|
||||
- name: list all files under web/
|
||||
ansible.builtin.debug:
|
||||
msg: "{{ lookup('community.general.filetree', 'web/') }}"
|
||||
|
||||
- name: list all files under web/; exclude .git and .node_modules
|
||||
ansible.builtin.debug:
|
||||
msg: >-
|
||||
{{ lookup('community.general.filetree', 'web/', exclude='^(\.git|\.node_modules)$') }}
|
||||
"""
|
||||
|
||||
RETURN = r"""
|
||||
_raw:
|
||||
description: List of dictionaries with file information.
|
||||
type: list
|
||||
elements: dict
|
||||
contains:
|
||||
src:
|
||||
description:
|
||||
- Full path to file.
|
||||
- Not returned when RV(_raw[].state) is set to V(directory).
|
||||
type: path
|
||||
root:
|
||||
description: Allows filtering by original location.
|
||||
type: path
|
||||
path:
|
||||
description: Contains the relative path to root.
|
||||
type: path
|
||||
mode:
|
||||
description: The permissions the resulting file or directory.
|
||||
type: str
|
||||
state:
|
||||
description:
|
||||
- Type of the resulting file or directory.
|
||||
- V(directory) for a directory, V(file) for a regular file, V(link) for a symbolic link.
|
||||
- Other file types are skipped and not returned.
|
||||
type: str
|
||||
choices: [directory, file, link]
|
||||
owner:
|
||||
description: Name of the user that owns the file/directory.
|
||||
type: raw
|
||||
group:
|
||||
description: Name of the group that owns the file/directory.
|
||||
type: raw
|
||||
seuser:
|
||||
description: The user part of the SELinux file context.
|
||||
type: raw
|
||||
serole:
|
||||
description: The role part of the SELinux file context.
|
||||
type: raw
|
||||
setype:
|
||||
description: The type part of the SELinux file context.
|
||||
type: raw
|
||||
selevel:
|
||||
description: The level part of the SELinux file context.
|
||||
type: raw
|
||||
uid:
|
||||
description: Owner ID of the file/directory.
|
||||
type: int
|
||||
gid:
|
||||
description: Group ID of the file/directory.
|
||||
type: int
|
||||
size:
|
||||
description: Size of the target.
|
||||
type: int
|
||||
mtime:
|
||||
description: Time of last modification.
|
||||
type: float
|
||||
ctime:
|
||||
description: Time of last metadata update or creation (depends on OS).
|
||||
type: float
|
||||
"""
|
||||
|
||||
import grp
|
||||
import os
|
||||
import pwd
|
||||
import re
|
||||
import stat
|
||||
|
||||
HAVE_SELINUX = False
|
||||
try:
|
||||
import selinux
|
||||
|
||||
HAVE_SELINUX = True
|
||||
except ImportError:
|
||||
pass
|
||||
|
||||
from ansible.errors import AnsibleLookupError
|
||||
from ansible.module_utils.common.text.converters import to_native, to_text
|
||||
from ansible.plugins.lookup import LookupBase
|
||||
from ansible.utils.display import Display
|
||||
|
||||
from ansible_collections.community.general.plugins.plugin_utils._lookup import check_for_wrong_terms
|
||||
|
||||
display = Display()
|
||||
|
||||
|
||||
# If selinux fails to find a default, return an array of None
|
||||
def selinux_context(path):
|
||||
context = [None, None, None, None]
|
||||
if HAVE_SELINUX and selinux.is_selinux_enabled():
|
||||
try:
|
||||
# note: the selinux module uses byte strings on python2 and text
|
||||
# strings on python3
|
||||
ret = selinux.lgetfilecon_raw(to_native(path))
|
||||
except OSError:
|
||||
return context
|
||||
if ret[0] != -1:
|
||||
# Limit split to 4 because the selevel, the last in the list,
|
||||
# may contain ':' characters
|
||||
context = ret[1].split(":", 3)
|
||||
return context
|
||||
|
||||
|
||||
def file_props(root, path):
|
||||
"""Returns dictionary with file properties, or return None on failure"""
|
||||
abspath = os.path.join(root, path)
|
||||
|
||||
try:
|
||||
st = os.lstat(abspath)
|
||||
except OSError as e:
|
||||
display.warning(f"filetree: Error using stat() on path {abspath} ({e})")
|
||||
return None
|
||||
|
||||
ret = dict(root=root, path=path)
|
||||
|
||||
if stat.S_ISLNK(st.st_mode):
|
||||
ret["state"] = "link"
|
||||
ret["src"] = os.readlink(abspath)
|
||||
elif stat.S_ISDIR(st.st_mode):
|
||||
ret["state"] = "directory"
|
||||
elif stat.S_ISREG(st.st_mode):
|
||||
ret["state"] = "file"
|
||||
ret["src"] = abspath
|
||||
else:
|
||||
display.warning(f"filetree: Error file type of {abspath} is not supported")
|
||||
return None
|
||||
|
||||
ret["uid"] = st.st_uid
|
||||
ret["gid"] = st.st_gid
|
||||
try:
|
||||
ret["owner"] = pwd.getpwuid(st.st_uid).pw_name
|
||||
except KeyError:
|
||||
ret["owner"] = st.st_uid
|
||||
try:
|
||||
ret["group"] = to_text(grp.getgrgid(st.st_gid).gr_name)
|
||||
except KeyError:
|
||||
ret["group"] = st.st_gid
|
||||
ret["mode"] = f"0{stat.S_IMODE(st.st_mode):03o}"
|
||||
ret["size"] = st.st_size
|
||||
ret["mtime"] = st.st_mtime
|
||||
ret["ctime"] = st.st_ctime
|
||||
|
||||
if HAVE_SELINUX and selinux.is_selinux_enabled() == 1:
|
||||
context = selinux_context(abspath)
|
||||
ret["seuser"] = context[0]
|
||||
ret["serole"] = context[1]
|
||||
ret["setype"] = context[2]
|
||||
ret["selevel"] = context[3]
|
||||
|
||||
return ret
|
||||
|
||||
|
||||
class LookupModule(LookupBase):
|
||||
def run(self, terms, variables=None, **kwargs):
|
||||
self.set_options(var_options=variables, direct=kwargs)
|
||||
check_for_wrong_terms(self, direct=kwargs)
|
||||
|
||||
basedir = self.get_basedir(variables)
|
||||
|
||||
# Regular expression for exclude
|
||||
exclude = self.get_option("exclude")
|
||||
if exclude:
|
||||
try:
|
||||
exclude_pattern = re.compile(exclude)
|
||||
except re.error as e:
|
||||
raise AnsibleLookupError(f"Invalid exclude regular expression {exclude!r}: {e}") from e
|
||||
else:
|
||||
exclude_pattern = None
|
||||
|
||||
ret = []
|
||||
for term in terms:
|
||||
term_file = os.path.basename(term)
|
||||
dwimmed_path = self._loader.path_dwim_relative(basedir, "files", os.path.dirname(term))
|
||||
path = os.path.join(dwimmed_path, term_file)
|
||||
display.debug(f"Walking '{path}'")
|
||||
for root, dirs, files in os.walk(path, topdown=True):
|
||||
# Filter files and directories using a regular expression
|
||||
if exclude_pattern is not None:
|
||||
dirs[:] = [d for d in dirs if not exclude_pattern.match(d)]
|
||||
files[:] = [f for f in files if not exclude_pattern.match(f)]
|
||||
|
||||
for entry in dirs + files:
|
||||
relpath = os.path.relpath(os.path.join(root, entry), path)
|
||||
|
||||
# Skip if relpath was already processed (from another root)
|
||||
if relpath not in [entry["path"] for entry in ret]:
|
||||
props = file_props(path, relpath)
|
||||
if props is not None:
|
||||
display.debug(f" found '{os.path.join(path, relpath)}'")
|
||||
ret.append(props)
|
||||
|
||||
return ret
|
||||
+89
@@ -0,0 +1,89 @@
|
||||
# Copyright (c) 2013, Serge van Ginderachter <serge@vanginderachter.be>
|
||||
# Copyright (c) 2017 Ansible Project
|
||||
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
from __future__ import annotations
|
||||
|
||||
DOCUMENTATION = r"""
|
||||
name: flattened
|
||||
author: Serge van Ginderachter (!UNKNOWN) <serge@vanginderachter.be>
|
||||
short_description: Return single list completely flattened
|
||||
description:
|
||||
- Given one or more lists, this lookup flattens any list elements found recursively until only 1 list is left.
|
||||
options:
|
||||
_terms:
|
||||
description: Lists to flatten.
|
||||
type: list
|
||||
elements: raw
|
||||
required: true
|
||||
notes:
|
||||
- Unlike the P(ansible.builtin.items#lookup) lookup which only flattens 1 level, this plugin continues to flatten until
|
||||
it cannot find lists anymore.
|
||||
- Aka highlander plugin, there can only be one (list).
|
||||
"""
|
||||
|
||||
EXAMPLES = r"""
|
||||
- name: "'unnest' all elements into single list"
|
||||
ansible.builtin.debug:
|
||||
msg: "all in one list {{lookup('community.general.flattened', [1,2,3,[5,6]], ['a','b','c'], [[5,6,1,3], [34,'a','b','c']])}}"
|
||||
"""
|
||||
|
||||
RETURN = r"""
|
||||
_raw:
|
||||
description:
|
||||
- Flattened list.
|
||||
type: list
|
||||
"""
|
||||
|
||||
from ansible.errors import AnsibleError
|
||||
from ansible.plugins.lookup import LookupBase
|
||||
from ansible.utils.listify import listify_lookup_plugin_terms
|
||||
|
||||
from ansible_collections.community.general.plugins.plugin_utils._lookup import check_for_wrong_terms
|
||||
|
||||
|
||||
class LookupModule(LookupBase):
|
||||
def _check_list_of_one_list(self, term):
|
||||
# make sure term is not a list of one (list of one..) item
|
||||
# return the final non list item if so
|
||||
|
||||
if isinstance(term, list) and len(term) == 1:
|
||||
term = term[0]
|
||||
if isinstance(term, list):
|
||||
term = self._check_list_of_one_list(term)
|
||||
|
||||
return term
|
||||
|
||||
def _do_flatten(self, terms, variables):
|
||||
ret = []
|
||||
for term in terms:
|
||||
term = self._check_list_of_one_list(term)
|
||||
|
||||
if term == "None" or term == "null":
|
||||
# ignore undefined items
|
||||
break
|
||||
|
||||
if isinstance(term, str):
|
||||
# convert a variable to a list
|
||||
term2 = listify_lookup_plugin_terms(term, templar=self._templar)
|
||||
# but avoid converting a plain string to a list of one string
|
||||
if term2 != [term]:
|
||||
term = term2
|
||||
|
||||
if isinstance(term, list):
|
||||
# if it is a list, check recursively for items that are a list
|
||||
term = self._do_flatten(term, variables)
|
||||
ret.extend(term)
|
||||
else:
|
||||
ret.append(term)
|
||||
|
||||
return ret
|
||||
|
||||
def run(self, terms, variables=None, **kwargs):
|
||||
if not isinstance(terms, list):
|
||||
raise AnsibleError("with_flattened expects a list")
|
||||
|
||||
self.set_options(var_options=variables, direct=kwargs)
|
||||
check_for_wrong_terms(self, direct=kwargs)
|
||||
|
||||
return self._do_flatten(terms, variables)
|
||||
+248
@@ -0,0 +1,248 @@
|
||||
# Copyright (c) 2023, Poh Wei Sheng <weisheng-p@hotmail.sg>
|
||||
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
from __future__ import annotations
|
||||
|
||||
DOCUMENTATION = r"""
|
||||
name: github_app_access_token
|
||||
author:
|
||||
- Poh Wei Sheng (@weisheng-p)
|
||||
- Bruno Lavoie (@blavoie)
|
||||
short_description: Obtain short-lived Github App Access tokens
|
||||
version_added: '8.2.0'
|
||||
requirements:
|
||||
- jwt (https://github.com/GehirnInc/python-jwt) OR
|
||||
- PyJWT (https://pypi.org/project/PyJWT/) AND cryptography (https://pypi.org/project/cryptography/)
|
||||
description:
|
||||
- This generates a Github access token that can be used with a C(git) command, if you use a Github App.
|
||||
options:
|
||||
key_path:
|
||||
description:
|
||||
- Path to your private key.
|
||||
- Either O(key_path) or O(private_key) must be specified.
|
||||
type: path
|
||||
app_id:
|
||||
description:
|
||||
- Your GitHub App's client ID or GitHub App ID. You can find these in the Settings page.
|
||||
- GitHub recommends using the client ID instead of the numeric
|
||||
app ID (see U(https://github.blog/changelog/2024-08-23-client-ids-are-now-included-in-app-api-responses/)).
|
||||
- The O(client_id) alias has been added in community.general 13.5.0.
|
||||
required: true
|
||||
type: str
|
||||
aliases: [client_id]
|
||||
installation_id:
|
||||
description:
|
||||
- The installation ID that contains the git repository you would like access to.
|
||||
- As of 2023-12-24, this can be found at Settings page > Integrations > Application. The last part of the URL in the
|
||||
configure button is the installation ID.
|
||||
- Alternatively, you can use PyGithub (U(https://github.com/PyGithub/PyGithub)) to get your installation ID.
|
||||
required: true
|
||||
type: str
|
||||
private_key:
|
||||
description:
|
||||
- GitHub App private key in PEM file format as string.
|
||||
- Either O(key_path) or O(private_key) must be specified.
|
||||
type: str
|
||||
version_added: 10.0.0
|
||||
secret: true
|
||||
token_expiry:
|
||||
description:
|
||||
- How long the token should last for in seconds.
|
||||
default: 600
|
||||
type: int
|
||||
github_url:
|
||||
description:
|
||||
- Base URL for the GitHub API (for GitHub Enterprise Server).
|
||||
- "Example: C(https://github-enterprise-server.example.com/api/v3)"
|
||||
default: https://api.github.com
|
||||
type: str
|
||||
version_added: 11.4.0
|
||||
"""
|
||||
|
||||
EXAMPLES = r"""
|
||||
- name: Get access token to be used for git checkout with app_id=123456, installation_id=64209
|
||||
ansible.builtin.git:
|
||||
repo: >-
|
||||
https://x-access-token:{{ github_token }}@github.com/hidden_user/super-secret-repo.git
|
||||
dest: /srv/checkout
|
||||
vars:
|
||||
github_token: >-
|
||||
{{ lookup('community.general.github_app_access_token', key_path='/home/to_your/key',
|
||||
app_id='123456', installation_id='64209') }}
|
||||
|
||||
- name: Get access token using the GitHub App's client ID instead of its numeric app ID
|
||||
ansible.builtin.git:
|
||||
repo: >-
|
||||
https://x-access-token:{{ github_token }}@github.com/hidden_user/super-secret-repo.git
|
||||
dest: /srv/checkout
|
||||
vars:
|
||||
github_token: >-
|
||||
{{ lookup('community.general.github_app_access_token', key_path='/home/to_your/key',
|
||||
client_id='Iv1.a1b2c3d4e5f6g7h8', installation_id='64209') }}
|
||||
"""
|
||||
|
||||
RETURN = r"""
|
||||
_raw:
|
||||
description:
|
||||
- A one-element list containing your GitHub access token.
|
||||
- B(Note) on ansible-core 2.22+, the token will be registered as a secret.
|
||||
See R(Masking secrets in Ansible output, secret_masking) for more information.
|
||||
type: list
|
||||
elements: str
|
||||
"""
|
||||
|
||||
try:
|
||||
import jwt
|
||||
|
||||
HAS_JWT = True
|
||||
except ImportError:
|
||||
HAS_JWT = False
|
||||
|
||||
HAS_PYTHON_JWT = False # vs pyjwt
|
||||
if HAS_JWT and hasattr(jwt, "JWT"):
|
||||
HAS_PYTHON_JWT = True
|
||||
from jwt import JWT, jwk_from_pem # type: ignore[attr-defined]
|
||||
|
||||
jwt_instance = JWT()
|
||||
|
||||
try:
|
||||
from cryptography.hazmat.primitives import serialization
|
||||
|
||||
HAS_CRYPTOGRAPHY = True
|
||||
except ImportError:
|
||||
HAS_CRYPTOGRAPHY = False
|
||||
|
||||
|
||||
import json
|
||||
import time
|
||||
from http import HTTPStatus
|
||||
from urllib.error import HTTPError
|
||||
|
||||
from ansible.errors import AnsibleError, AnsibleOptionsError
|
||||
from ansible.module_utils.urls import open_url
|
||||
from ansible.plugins.lookup import LookupBase
|
||||
from ansible.utils.display import Display
|
||||
|
||||
from ansible_collections.community.general.plugins.module_utils._secrets import mark_values_as_secrets
|
||||
from ansible_collections.community.general.plugins.plugin_utils._lookup import check_for_no_terms
|
||||
|
||||
display = Display()
|
||||
|
||||
|
||||
class PythonJWT:
|
||||
@staticmethod
|
||||
def read_key(path, private_key=None):
|
||||
try:
|
||||
if private_key:
|
||||
return jwk_from_pem(private_key.encode("utf-8"))
|
||||
with open(path, "rb") as pem_file:
|
||||
return jwk_from_pem(pem_file.read())
|
||||
except Exception as e:
|
||||
raise AnsibleError(f"Error while parsing key file: {e}") from e
|
||||
|
||||
@staticmethod
|
||||
def encode_jwt(app_id, jwk, exp=600):
|
||||
now = int(time.time())
|
||||
payload = {
|
||||
"iat": now,
|
||||
"exp": now + exp,
|
||||
"iss": app_id,
|
||||
}
|
||||
try:
|
||||
return jwt_instance.encode(payload, jwk, alg="RS256")
|
||||
except Exception as e:
|
||||
raise AnsibleError(f"Error while encoding jwt: {e}") from e
|
||||
|
||||
|
||||
def read_key(path, private_key=None):
|
||||
if HAS_PYTHON_JWT:
|
||||
return PythonJWT.read_key(path, private_key)
|
||||
try:
|
||||
if private_key:
|
||||
key_bytes = private_key.encode("utf-8")
|
||||
else:
|
||||
with open(path, "rb") as pem_file:
|
||||
key_bytes = pem_file.read()
|
||||
return serialization.load_pem_private_key(key_bytes, password=None)
|
||||
except Exception as e:
|
||||
raise AnsibleError(f"Error while parsing key file: {e}") from e
|
||||
|
||||
|
||||
def encode_jwt(app_id, private_key_obj, exp=600):
|
||||
if HAS_PYTHON_JWT:
|
||||
return PythonJWT.encode_jwt(app_id, private_key_obj)
|
||||
now = int(time.time())
|
||||
payload = {
|
||||
"iat": now,
|
||||
"exp": now + exp,
|
||||
"iss": app_id,
|
||||
}
|
||||
try:
|
||||
return jwt.encode(payload, private_key_obj, algorithm="RS256")
|
||||
except Exception as e:
|
||||
raise AnsibleError(f"Error while encoding jwt: {e}") from e
|
||||
|
||||
|
||||
def post_request(generated_jwt, installation_id, api_base):
|
||||
base = api_base.rstrip("/")
|
||||
github_url = f"{base}/app/installations/{installation_id}/access_tokens"
|
||||
|
||||
headers = {
|
||||
"Authorization": f"Bearer {generated_jwt}",
|
||||
"Accept": "application/vnd.github.v3+json",
|
||||
}
|
||||
try:
|
||||
response = open_url(github_url, headers=headers, method="POST")
|
||||
except HTTPError as e:
|
||||
try:
|
||||
error_body = json.loads(e.read().decode())
|
||||
display.vvv(f"Error returned: {error_body}")
|
||||
except Exception:
|
||||
error_body = {}
|
||||
if e.code == HTTPStatus.NOT_FOUND:
|
||||
raise AnsibleError("Github return error. Please confirm your installation_id value is valid") from e
|
||||
elif e.code == HTTPStatus.UNAUTHORIZED:
|
||||
raise AnsibleError("Github return error. Please confirm your private key is valid") from e
|
||||
raise AnsibleError(f"Unexpected data returned: {e} -- {error_body}") from e
|
||||
response_body = response.read()
|
||||
try:
|
||||
json_data = json.loads(response_body.decode("utf-8"))
|
||||
except json.decoder.JSONDecodeError as e:
|
||||
raise AnsibleError(f"Error while dencoding JSON respone from github: {e}") from e
|
||||
return json_data.get("token")
|
||||
|
||||
|
||||
def get_token(key_path, app_id, installation_id, private_key, github_url, expiry=600):
|
||||
jwk = read_key(key_path, private_key)
|
||||
generated_jwt = encode_jwt(app_id, jwk, exp=expiry)
|
||||
return post_request(generated_jwt, installation_id, github_url)
|
||||
|
||||
|
||||
class LookupModule(LookupBase):
|
||||
def run(self, terms, variables=None, **kwargs):
|
||||
if not HAS_JWT:
|
||||
raise AnsibleError('Python jwt library is required. Please install using "pip install pyjwt"')
|
||||
|
||||
if not HAS_PYTHON_JWT and not HAS_CRYPTOGRAPHY:
|
||||
raise AnsibleError(
|
||||
'Python cryptography library is required. Please install using "pip install cryptography"'
|
||||
)
|
||||
|
||||
self.set_options(var_options=variables, direct=kwargs)
|
||||
check_for_no_terms(self, terms=terms, direct=kwargs)
|
||||
|
||||
if not (self.get_option("key_path") or self.get_option("private_key")):
|
||||
raise AnsibleOptionsError("One of key_path or private_key is required")
|
||||
if self.get_option("key_path") and self.get_option("private_key"):
|
||||
raise AnsibleOptionsError("key_path and private_key are mutually exclusive")
|
||||
|
||||
t = get_token(
|
||||
self.get_option("key_path"),
|
||||
self.get_option("app_id"),
|
||||
self.get_option("installation_id"),
|
||||
self.get_option("private_key"),
|
||||
self.get_option("github_url"),
|
||||
self.get_option("token_expiry"),
|
||||
)
|
||||
|
||||
return [mark_values_as_secrets(t)]
|
||||
@@ -0,0 +1,80 @@
|
||||
# Copyright (c) 2016, Samuel Boucher <boucher.samuel.c@gmail.com>
|
||||
# Copyright (c) 2017 Ansible Project
|
||||
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
DOCUMENTATION = r"""
|
||||
name: keyring
|
||||
author:
|
||||
- Samuel Boucher (!UNKNOWN) <boucher.samuel.c@gmail.com>
|
||||
requirements:
|
||||
- keyring (python library)
|
||||
short_description: Grab secrets from the OS keyring
|
||||
description:
|
||||
- Allows you to access data stored in the OS provided keyring/keychain.
|
||||
options:
|
||||
_terms:
|
||||
description:
|
||||
- List of pairs of service and user name.
|
||||
- Every entry must be of the form V(servicename username).
|
||||
type: list
|
||||
elements: str
|
||||
"""
|
||||
|
||||
EXAMPLES = r"""
|
||||
- name: output secrets to screen (BAD IDEA)
|
||||
ansible.builtin.debug:
|
||||
msg: "Password: {{item}}"
|
||||
with_community.general.keyring:
|
||||
- 'servicename username'
|
||||
|
||||
- name: access mysql with password from keyring
|
||||
community.mysql.mysql_db:
|
||||
login_password: "{{ lookup('community.general.keyring', 'mysql joe') }}"
|
||||
login_user: joe
|
||||
"""
|
||||
|
||||
RETURN = r"""
|
||||
_raw:
|
||||
description: Secrets stored.
|
||||
type: list
|
||||
elements: str
|
||||
"""
|
||||
|
||||
HAS_KEYRING = True
|
||||
|
||||
from ansible.errors import AnsibleError
|
||||
from ansible.utils.display import Display
|
||||
|
||||
from ansible_collections.community.general.plugins.plugin_utils._lookup import check_for_wrong_terms
|
||||
|
||||
try:
|
||||
import keyring
|
||||
except ImportError:
|
||||
HAS_KEYRING = False
|
||||
|
||||
from ansible.plugins.lookup import LookupBase
|
||||
|
||||
display = Display()
|
||||
|
||||
|
||||
class LookupModule(LookupBase):
|
||||
def run(self, terms, variables=None, **kwargs):
|
||||
if not HAS_KEYRING:
|
||||
raise AnsibleError("Can't LOOKUP(keyring): missing required python library 'keyring'")
|
||||
|
||||
self.set_options(var_options=variables, direct=kwargs)
|
||||
check_for_wrong_terms(self, direct=kwargs)
|
||||
|
||||
display.vvvv(f"keyring: {keyring.get_keyring()}")
|
||||
ret = []
|
||||
for term in terms:
|
||||
(servicename, username) = (term.split()[0], term.split()[1])
|
||||
display.vvvv(f"username: {username}, servicename: {servicename} ")
|
||||
password = keyring.get_password(servicename, username)
|
||||
if password is None:
|
||||
raise AnsibleError(f"servicename: {servicename} for user {username} not found")
|
||||
ret.append(password.rstrip())
|
||||
return ret
|
||||
+105
@@ -0,0 +1,105 @@
|
||||
# Copyright (c) 2016, Andrew Zenk <azenk@umn.edu>
|
||||
# Copyright (c) 2017 Ansible Project
|
||||
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
from __future__ import annotations
|
||||
|
||||
DOCUMENTATION = r"""
|
||||
name: lastpass
|
||||
author:
|
||||
- Andrew Zenk (!UNKNOWN) <azenk@umn.edu>
|
||||
requirements:
|
||||
- lpass (command line utility)
|
||||
- must have already logged into LastPass
|
||||
short_description: Fetch data from LastPass
|
||||
description:
|
||||
- Use the lpass command line utility to fetch specific fields from LastPass.
|
||||
options:
|
||||
_terms:
|
||||
description: Key from which you want to retrieve the field.
|
||||
required: true
|
||||
type: list
|
||||
elements: str
|
||||
field:
|
||||
description: Field to return from LastPass.
|
||||
default: 'password'
|
||||
type: str
|
||||
"""
|
||||
|
||||
EXAMPLES = r"""
|
||||
- name: get 'custom_field' from LastPass entry 'entry-name'
|
||||
ansible.builtin.debug:
|
||||
msg: "{{ lookup('community.general.lastpass', 'entry-name', field='custom_field') }}"
|
||||
"""
|
||||
|
||||
RETURN = r"""
|
||||
_raw:
|
||||
description: Secrets stored.
|
||||
type: list
|
||||
elements: str
|
||||
"""
|
||||
|
||||
from subprocess import PIPE, Popen
|
||||
|
||||
from ansible.errors import AnsibleError
|
||||
from ansible.module_utils.common.text.converters import to_bytes, to_text
|
||||
from ansible.plugins.lookup import LookupBase
|
||||
|
||||
from ansible_collections.community.general.plugins.plugin_utils._lookup import check_for_wrong_terms
|
||||
|
||||
|
||||
class LPassException(AnsibleError):
|
||||
pass
|
||||
|
||||
|
||||
class LPass:
|
||||
def __init__(self, path="lpass"):
|
||||
self._cli_path = path
|
||||
|
||||
@property
|
||||
def cli_path(self):
|
||||
return self._cli_path
|
||||
|
||||
@property
|
||||
def logged_in(self):
|
||||
out, err = self._run(self._build_args("logout"), stdin="n\n", expected_rc=1)
|
||||
return err.startswith("Are you sure you would like to log out?")
|
||||
|
||||
def _run(self, args, stdin=None, expected_rc=0):
|
||||
p = Popen([self.cli_path] + args, stdout=PIPE, stderr=PIPE, stdin=PIPE)
|
||||
out, err = p.communicate(to_bytes(stdin))
|
||||
rc = p.wait()
|
||||
if rc != expected_rc:
|
||||
raise LPassException(err)
|
||||
return to_text(out, errors="surrogate_or_strict"), to_text(err, errors="surrogate_or_strict")
|
||||
|
||||
def _build_args(self, command, args=None):
|
||||
if args is None:
|
||||
args = []
|
||||
args = [command] + args
|
||||
args += ["--color=never"]
|
||||
return args
|
||||
|
||||
def get_field(self, key, field):
|
||||
if field in ["username", "password", "url", "notes", "id", "name"]:
|
||||
out, err = self._run(self._build_args("show", [f"--{field}", key]))
|
||||
else:
|
||||
out, err = self._run(self._build_args("show", [f"--field={field}", key]))
|
||||
return out.strip()
|
||||
|
||||
|
||||
class LookupModule(LookupBase):
|
||||
def run(self, terms, variables=None, **kwargs):
|
||||
self.set_options(var_options=variables, direct=kwargs)
|
||||
check_for_wrong_terms(self, direct=kwargs)
|
||||
field = self.get_option("field")
|
||||
|
||||
lp = LPass()
|
||||
|
||||
if not lp.logged_in:
|
||||
raise AnsibleError("Not logged into LastPass: please run 'lpass login' first")
|
||||
|
||||
values = []
|
||||
for term in terms:
|
||||
values.append(lp.get_field(term, field))
|
||||
return values
|
||||
@@ -0,0 +1,125 @@
|
||||
# Copyright (c) 2017-2018, Jan-Piet Mens <jpmens(at)gmail.com>
|
||||
# Copyright (c) 2018 Ansible Project
|
||||
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
from __future__ import annotations
|
||||
|
||||
DOCUMENTATION = r"""
|
||||
name: lmdb_kv
|
||||
author:
|
||||
- Jan-Piet Mens (@jpmens)
|
||||
version_added: '0.2.0'
|
||||
short_description: Fetch data from LMDB
|
||||
description:
|
||||
- This lookup returns a list of results from an LMDB DB corresponding to a list of items given to it.
|
||||
requirements:
|
||||
- lmdb (Python library U(https://lmdb.readthedocs.io/en/latest/))
|
||||
options:
|
||||
_terms:
|
||||
description: List of keys to query.
|
||||
type: list
|
||||
elements: str
|
||||
db:
|
||||
description: Path to LMDB database.
|
||||
type: str
|
||||
default: 'ansible.mdb'
|
||||
vars:
|
||||
- name: lmdb_kv_db
|
||||
"""
|
||||
|
||||
EXAMPLES = r"""
|
||||
- name: query LMDB for a list of country codes
|
||||
ansible.builtin.debug:
|
||||
msg: "{{ query('community.general.lmdb_kv', 'nl', 'be', 'lu', db='jp.mdb') }}"
|
||||
|
||||
- name: use list of values in a loop by key wildcard
|
||||
ansible.builtin.debug:
|
||||
msg: "Hello from {{ item.0 }} a.k.a. {{ item.1 }}"
|
||||
vars:
|
||||
lmdb_kv_db: jp.mdb
|
||||
with_community.general.lmdb_kv:
|
||||
- "n*"
|
||||
|
||||
- name: get an item by key
|
||||
ansible.builtin.assert:
|
||||
that:
|
||||
- item == 'Belgium'
|
||||
vars:
|
||||
lmdb_kv_db: jp.mdb
|
||||
with_community.general.lmdb_kv:
|
||||
- be
|
||||
"""
|
||||
|
||||
RETURN = r"""
|
||||
_raw:
|
||||
description: Value(s) stored in LMDB.
|
||||
type: list
|
||||
elements: raw
|
||||
"""
|
||||
|
||||
|
||||
from ansible.errors import AnsibleError
|
||||
from ansible.module_utils.common.text.converters import to_native, to_text
|
||||
from ansible.plugins.lookup import LookupBase
|
||||
|
||||
from ansible_collections.community.general.plugins.plugin_utils._lookup import check_for_wrong_terms
|
||||
|
||||
HAVE_LMDB = True
|
||||
try:
|
||||
import lmdb
|
||||
except ImportError:
|
||||
HAVE_LMDB = False
|
||||
|
||||
|
||||
class LookupModule(LookupBase):
|
||||
def run(self, terms, variables=None, **kwargs):
|
||||
"""
|
||||
terms contain any number of keys to be retrieved.
|
||||
If terms is None, all keys from the database are returned
|
||||
with their values, and if term ends in an asterisk, we
|
||||
start searching there
|
||||
|
||||
The LMDB database defaults to 'ansible.mdb' if Ansible's
|
||||
variable 'lmdb_kv_db' is not set:
|
||||
|
||||
vars:
|
||||
lmdb_kv_db: "jp.mdb"
|
||||
"""
|
||||
if HAVE_LMDB is False:
|
||||
raise AnsibleError("Can't LOOKUP(lmdb_kv): this module requires lmdb to be installed")
|
||||
|
||||
self.set_options(var_options=variables, direct=kwargs)
|
||||
check_for_wrong_terms(self, direct=kwargs)
|
||||
|
||||
db = self.get_option("db")
|
||||
|
||||
try:
|
||||
env = lmdb.open(str(db), readonly=True)
|
||||
except Exception as e:
|
||||
raise AnsibleError(f"LMDB cannot open database {db}: {e}") from e
|
||||
|
||||
ret = []
|
||||
if len(terms) == 0:
|
||||
with env.begin() as txn:
|
||||
cursor = txn.cursor()
|
||||
cursor.first()
|
||||
for key, value in cursor:
|
||||
ret.append((to_text(key), to_native(value)))
|
||||
|
||||
else:
|
||||
for term in terms:
|
||||
with env.begin() as txn:
|
||||
if term.endswith("*"):
|
||||
cursor = txn.cursor()
|
||||
prefix = term[:-1] # strip asterisk
|
||||
cursor.set_range(to_text(term).encode())
|
||||
while cursor.key().startswith(to_text(prefix).encode()):
|
||||
for key, value in cursor:
|
||||
ret.append((to_text(key), to_native(value)))
|
||||
cursor.next()
|
||||
else:
|
||||
value = txn.get(to_text(term).encode())
|
||||
if value is not None:
|
||||
ret.append(to_native(value))
|
||||
|
||||
return ret
|
||||
+671
@@ -0,0 +1,671 @@
|
||||
# Copyright (c) 2020, Thales Netherlands
|
||||
# Copyright (c) 2021, Ansible Project
|
||||
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
from __future__ import annotations
|
||||
|
||||
DOCUMENTATION = r"""
|
||||
author:
|
||||
- Roy Lenferink (@rlenferink)
|
||||
- Mark Ettema (@m-a-r-k-e)
|
||||
- Alexander Petrenz (@alpex8)
|
||||
- Christoph Fiehe (@cfiehe)
|
||||
name: merge_variables
|
||||
short_description: Merge variables whose names match a given pattern
|
||||
description:
|
||||
- This lookup returns the merged result of all variables in scope that match the given prefixes, suffixes, or regular expressions,
|
||||
optionally.
|
||||
version_added: 6.5.0
|
||||
options:
|
||||
_terms:
|
||||
description:
|
||||
- Depending on the value of O(pattern_type), this is a list of prefixes, suffixes, or regular expressions that is used
|
||||
to match all variables that should be merged.
|
||||
required: true
|
||||
type: list
|
||||
elements: str
|
||||
pattern_type:
|
||||
description:
|
||||
- Change the way of searching for the specified pattern.
|
||||
type: str
|
||||
default: 'regex'
|
||||
choices:
|
||||
- prefix
|
||||
- suffix
|
||||
- regex
|
||||
env:
|
||||
- name: ANSIBLE_MERGE_VARIABLES_PATTERN_TYPE
|
||||
ini:
|
||||
- section: merge_variables_lookup
|
||||
key: pattern_type
|
||||
initial_value:
|
||||
description:
|
||||
- An initial value to start with.
|
||||
type: raw
|
||||
override:
|
||||
description:
|
||||
- Return an error, print a warning or ignore it when a key is overwritten.
|
||||
- The default behavior V(error) makes the plugin fail when a key would be overwritten.
|
||||
- When V(warn) and V(ignore) are used, note that it is important to know that the variables are sorted by name before
|
||||
being merged. Keys for later variables in this order overwrite keys of the same name for variables earlier in this
|
||||
order. To avoid potential confusion, better use O(override=error) whenever possible.
|
||||
type: str
|
||||
default: 'error'
|
||||
choices:
|
||||
- error
|
||||
- warn
|
||||
- ignore
|
||||
env:
|
||||
- name: ANSIBLE_MERGE_VARIABLES_OVERRIDE
|
||||
ini:
|
||||
- section: merge_variables_lookup
|
||||
key: override
|
||||
groups:
|
||||
description:
|
||||
- Search for variables across hosts that belong to the given groups. This allows to collect configuration pieces across
|
||||
different hosts (for example a service on a host with its database on another host).
|
||||
type: list
|
||||
elements: str
|
||||
version_added: 8.5.0
|
||||
dict_merge:
|
||||
description:
|
||||
- Behavior when encountering dictionary values.
|
||||
type: str
|
||||
default: deep
|
||||
choices:
|
||||
deep: Merge dictionaries recursively.
|
||||
shallow: Merge only top-level values.
|
||||
replace: Overwrite existing dictionaries.
|
||||
keep: Keep existing dictionaries.
|
||||
version_added: 12.5.0
|
||||
list_merge:
|
||||
description:
|
||||
- Behavior when encountering list values.
|
||||
type: str
|
||||
default: append
|
||||
choices:
|
||||
replace: Overwrite existing lists.
|
||||
keep: Keep existing lists.
|
||||
append: Append elements to the end of an existing list.
|
||||
prepend: Insert elements at the beginning of an existing list.
|
||||
merge: Take the index as key and merge each element.
|
||||
version_added: 12.5.0
|
||||
type_conflict_merge:
|
||||
description:
|
||||
- Merge strategy to apply on type conflicts.
|
||||
- This value is only considered in case of O(override=warn) or O(override=ignore).
|
||||
type: str
|
||||
default: replace
|
||||
choices:
|
||||
replace: Overwrite existing values.
|
||||
keep: Keep existing values.
|
||||
version_added: 12.5.0
|
||||
default_merge:
|
||||
description:
|
||||
- Merge strategy applied to other types.
|
||||
- This value is only considered in case of O(override=warn) or O(override=ignore).
|
||||
type: str
|
||||
default: replace
|
||||
choices:
|
||||
replace: Overwrite existing values.
|
||||
keep: Keep existing values.
|
||||
version_added: 12.5.0
|
||||
list_transformations:
|
||||
description:
|
||||
- List transformations applied to list types.
|
||||
- The definition order corresponds to the order in which these transformations are applied.
|
||||
- Elements can be a dict with the keys mentioned below or a string naming the transformation to apply.
|
||||
type: list
|
||||
elements: raw
|
||||
suboptions:
|
||||
name:
|
||||
description:
|
||||
- Name of the list transformation.
|
||||
required: true
|
||||
type: str
|
||||
choices:
|
||||
flatten: Flatten lists, converting nested lists into single lists. Does not support any additional options.
|
||||
dedup: Remove duplicates from lists. Supported option is C(keep).
|
||||
options:
|
||||
description:
|
||||
- Options as key value pairs.
|
||||
type: dict
|
||||
suboptions:
|
||||
keep:
|
||||
description:
|
||||
- Determines which duplicates (if any) to keep.
|
||||
- Only valid in combination with the O(list_transformations[].name=dedup) list transformation.
|
||||
type: str
|
||||
default: first
|
||||
choices:
|
||||
first: Drop duplicates except for the first occurrence.
|
||||
last: Drop duplicates except for the last occurrence.
|
||||
default: []
|
||||
version_added: 12.5.0
|
||||
"""
|
||||
|
||||
EXAMPLES = r"""
|
||||
# Some example variables, they can be defined anywhere as long as they are in scope
|
||||
test_init_list:
|
||||
- "list init item 1"
|
||||
- "list init item 2"
|
||||
|
||||
testa__test_list:
|
||||
- "test a item 1"
|
||||
|
||||
testb__test_list:
|
||||
- "test b item 1"
|
||||
|
||||
testa__test_dict:
|
||||
ports:
|
||||
- 1
|
||||
|
||||
testb__test_dict:
|
||||
ports:
|
||||
- 3
|
||||
|
||||
testa_low_dict__test:
|
||||
a:
|
||||
a:
|
||||
x: low_value
|
||||
y: low_value
|
||||
list:
|
||||
- low_value
|
||||
b:
|
||||
- 1
|
||||
- 1
|
||||
- 2
|
||||
- 3
|
||||
|
||||
testb_high_dict__test:
|
||||
a:
|
||||
a:
|
||||
y: high_value
|
||||
z: high_value
|
||||
list:
|
||||
- high_value
|
||||
b:
|
||||
- 3
|
||||
- 4
|
||||
- 4
|
||||
- '5': value
|
||||
|
||||
# Merge variables that end with '__test_dict' and store the result in a variable 'example_a'
|
||||
example_a: "{{ lookup('community.general.merge_variables', '__test_dict', pattern_type='suffix') }}"
|
||||
|
||||
# The variable example_a now contains:
|
||||
# ports:
|
||||
# - 1
|
||||
# - 3
|
||||
|
||||
# Merge variables that match the '^.+__test_list$' regular expression, starting with an initial value and store the
|
||||
# result in a variable 'example_b'
|
||||
example_b: "{{ lookup('community.general.merge_variables', '^.+__test_list$', initial_value=test_init_list) }}"
|
||||
|
||||
# The variable example_b now contains:
|
||||
# - "list init item 1"
|
||||
# - "list init item 2"
|
||||
# - "test a item 1"
|
||||
# - "test b item 1"
|
||||
|
||||
# Shallow merge variables that end with '__test', insert list elements at the beginning of the list,
|
||||
# remove duplicates from lists (keep the first occurrence), and store the result in a variable 'example_c'
|
||||
example_c: "{{
|
||||
lookup(
|
||||
'community.general.merge_variables',
|
||||
'^.+__test$',
|
||||
dict_merge='shallow',
|
||||
list_merge='prepend',
|
||||
list_transformations=['dedup']) }}"
|
||||
|
||||
# The variable example_c now contains:
|
||||
# a:
|
||||
# a:
|
||||
# y: high_value
|
||||
# z: high_value
|
||||
# list:
|
||||
# - high_value
|
||||
# b:
|
||||
# - 3
|
||||
# - 4
|
||||
# - '5': value
|
||||
# - 1
|
||||
# - 2
|
||||
|
||||
# Deep merge variables that end with '__test', merge list elements by index, ignore overrides, apply the strategies
|
||||
# 'keep' for type conflicts and 'replace' for other types, and store the result in a variable 'example_d'
|
||||
example_d: "{{
|
||||
lookup(
|
||||
'community.general.merge_variables',
|
||||
'^.+__test$',
|
||||
dict_merge='deep',
|
||||
list_merge='merge',
|
||||
override='ignore',
|
||||
type_conflict_merge='keep',
|
||||
default_merge='replace') }}"
|
||||
|
||||
# The variable example_d now contains:
|
||||
# a:
|
||||
# a:
|
||||
# x: low_value
|
||||
# y: high_value
|
||||
# list:
|
||||
# - high_value
|
||||
# z: high_value
|
||||
# b:
|
||||
# - 3
|
||||
# - 4
|
||||
# - 4
|
||||
# - 3
|
||||
"""
|
||||
|
||||
RETURN = r"""
|
||||
_raw:
|
||||
description: In case the search matches list items, a list is returned. In case the search matches dicts, a dict is returned.
|
||||
type: raw
|
||||
elements: raw
|
||||
"""
|
||||
|
||||
|
||||
import re
|
||||
import typing as t
|
||||
from abc import ABC, abstractmethod
|
||||
|
||||
from ansible.errors import AnsibleError
|
||||
from ansible.plugins.lookup import LookupBase
|
||||
from ansible.utils.display import Display
|
||||
|
||||
from ansible_collections.community.general.plugins.plugin_utils._lookup import check_for_wrong_terms
|
||||
|
||||
if t.TYPE_CHECKING:
|
||||
from collections.abc import Callable
|
||||
|
||||
|
||||
display = Display()
|
||||
|
||||
|
||||
def _verify_and_get_type(variable: t.Any) -> str:
|
||||
if isinstance(variable, list):
|
||||
return "list"
|
||||
elif isinstance(variable, dict):
|
||||
return "dict"
|
||||
else:
|
||||
raise AnsibleError(f"Not supported type detected, variable must be a list or a dict: '{variable}'")
|
||||
|
||||
|
||||
class LookupModule(LookupBase):
|
||||
def run(self, terms: list[str], variables: dict[str, t.Any], **kwargs) -> list[t.Any]:
|
||||
self.set_options(direct=kwargs)
|
||||
check_for_wrong_terms(self, direct=kwargs)
|
||||
initial_value = self.get_option("initial_value", None)
|
||||
self._override_behavior = self.get_option("override", "error")
|
||||
self._pattern_type = self.get_option("pattern_type", "regex")
|
||||
self._groups = self.get_option("groups", None)
|
||||
self._dict_merge = self.get_option("dict_merge", "deep")
|
||||
self._list_merge = self.get_option("list_merge", "append")
|
||||
self._type_conflict_merge = self.get_option("type_conflict_merge", "replace")
|
||||
self._default_merge = self.get_option("default_merge", "replace")
|
||||
self._list_transformations = self.get_option("list_transformations", [])
|
||||
|
||||
ret = []
|
||||
for term in terms:
|
||||
if not isinstance(term, str):
|
||||
raise AnsibleError(f"Non-string type '{type(term)}' passed, only 'str' types are allowed!")
|
||||
|
||||
if not self._groups: # consider only own variables
|
||||
ret.append(self._merge_vars(term, initial_value, variables))
|
||||
else: # consider variables of hosts in given groups
|
||||
cross_host_merge_result = initial_value
|
||||
for host in variables["hostvars"]:
|
||||
if self._is_host_in_allowed_groups(variables["hostvars"][host]["group_names"]):
|
||||
host_variables = dict(variables["hostvars"].raw_get(host))
|
||||
host_variables["hostvars"] = variables["hostvars"] # re-add hostvars
|
||||
cross_host_merge_result = self._merge_vars(term, cross_host_merge_result, host_variables)
|
||||
ret.append(cross_host_merge_result)
|
||||
|
||||
return ret
|
||||
|
||||
def _is_host_in_allowed_groups(self, host_groups: list[str]) -> bool:
|
||||
if "all" in self._groups:
|
||||
return True
|
||||
|
||||
group_intersection = [host_group_name for host_group_name in host_groups if host_group_name in self._groups]
|
||||
return bool(group_intersection)
|
||||
|
||||
def _var_matches(self, key: str, search_pattern: str) -> bool:
|
||||
if self._pattern_type == "prefix":
|
||||
return key.startswith(search_pattern)
|
||||
elif self._pattern_type == "suffix":
|
||||
return key.endswith(search_pattern)
|
||||
elif self._pattern_type == "regex":
|
||||
matcher = re.compile(search_pattern)
|
||||
return matcher.search(key) is not None
|
||||
|
||||
return False
|
||||
|
||||
def _merge_vars(self, search_pattern: str, initial_value: t.Any, variables: dict[str, t.Any]) -> t.Any:
|
||||
display.vvv(f"Merge variables with {self._pattern_type}: {search_pattern}")
|
||||
var_merge_names = sorted([key for key in variables.keys() if self._var_matches(key, search_pattern)])
|
||||
display.vvv(f"The following variables will be merged: {var_merge_names}")
|
||||
prev_var_type = None
|
||||
result = None
|
||||
|
||||
if initial_value is not None:
|
||||
prev_var_type = _verify_and_get_type(initial_value)
|
||||
result = initial_value
|
||||
|
||||
builder = (
|
||||
MergerBuilder()
|
||||
.with_type_strategy(list, ListMergeStrategies.from_name(self._list_merge))
|
||||
.with_type_conflict_strategy(BaseMergeStrategies.from_name(self._type_conflict_merge))
|
||||
.with_default_strategy(BaseMergeStrategies.from_name(self._default_merge))
|
||||
.with_override_behavior(self._override_behavior)
|
||||
)
|
||||
|
||||
if self._dict_merge == "deep":
|
||||
builder.with_type_strategy(dict, DictMergeStrategies.Merge())
|
||||
elif self._dict_merge == "shallow":
|
||||
builder.with_shallow_merge()
|
||||
else:
|
||||
builder.with_type_strategy(dict, DictMergeStrategies.from_name(self._dict_merge))
|
||||
|
||||
for transformation in self._list_transformations:
|
||||
if isinstance(transformation, str):
|
||||
builder.with_transformation(list, ListTransformations.from_name(transformation))
|
||||
elif isinstance(transformation, dict):
|
||||
name = transformation["name"]
|
||||
options = transformation.get("options", {})
|
||||
builder.with_transformation(list, ListTransformations.from_name(name, **options))
|
||||
else:
|
||||
raise AnsibleError(
|
||||
f"Transformations must be specified through values of type 'str' or 'dict', but a value of type '{type(transformation)}' was given"
|
||||
)
|
||||
|
||||
merger = builder.build()
|
||||
|
||||
if self._templar is None:
|
||||
raise AnsibleError("Templar is not available")
|
||||
|
||||
templar = self._templar.copy_with_new_env(available_variables=variables)
|
||||
|
||||
for var_name in var_merge_names:
|
||||
var_value = templar.template(variables[var_name]) # Render jinja2 templates
|
||||
var_type = _verify_and_get_type(var_value)
|
||||
|
||||
if prev_var_type is None:
|
||||
prev_var_type = var_type
|
||||
elif prev_var_type != var_type:
|
||||
raise AnsibleError("Unable to merge, not all variables are of the same type")
|
||||
|
||||
if result is None:
|
||||
result = var_value
|
||||
continue
|
||||
|
||||
result = merger.merge(path=[var_name], left=result, right=var_value)
|
||||
|
||||
return result
|
||||
|
||||
|
||||
class MergeStrategy(ABC):
|
||||
@abstractmethod
|
||||
def merge(self, merger: ObjectMerger, path: list[str], left: t.Any, right: t.Any) -> t.Any:
|
||||
raise NotImplementedError
|
||||
|
||||
|
||||
class MergeStrategies:
|
||||
@classmethod
|
||||
def from_name(cls, name: str, *args, **kwargs) -> MergeStrategy:
|
||||
if name in cls.strategies:
|
||||
return cls.strategies[name](*args, **kwargs)
|
||||
else:
|
||||
raise AnsibleError(f"Unknown merge strategy '{name}'")
|
||||
|
||||
strategies: dict[str, Callable[..., t.Any]] = {}
|
||||
|
||||
|
||||
class BaseMergeStrategies(MergeStrategies):
|
||||
class Replace(MergeStrategy):
|
||||
def merge(self, merger: ObjectMerger, path: list[str], left: t.Any, right: t.Any) -> t.Any:
|
||||
return right
|
||||
|
||||
class Keep(MergeStrategy):
|
||||
def merge(self, merger: ObjectMerger, path: list[str], left: t.Any, right: t.Any) -> t.Any:
|
||||
return left
|
||||
|
||||
strategies = {
|
||||
"replace": Replace,
|
||||
"keep": Keep,
|
||||
}
|
||||
|
||||
|
||||
class DictMergeStrategies(MergeStrategies):
|
||||
class Merge(MergeStrategy):
|
||||
def merge(
|
||||
self, merger: ObjectMerger, path: list[str], left: dict[str, t.Any], right: dict[str, t.Any]
|
||||
) -> dict[str, t.Any]:
|
||||
result = left
|
||||
for key, value in right.items():
|
||||
if key not in result:
|
||||
result[key] = value
|
||||
else:
|
||||
path.append(key)
|
||||
merged = merger.merge(path=path, left=result[key], right=value)
|
||||
merger.before_override(path=path, old_value=result[key], new_value=merged)
|
||||
result[key] = merged
|
||||
|
||||
return result
|
||||
|
||||
strategies = {
|
||||
"merge": Merge,
|
||||
"replace": BaseMergeStrategies.Replace,
|
||||
"keep": BaseMergeStrategies.Keep,
|
||||
}
|
||||
|
||||
|
||||
class ListMergeStrategies(MergeStrategies):
|
||||
class Append(MergeStrategy):
|
||||
def merge(self, merger: ObjectMerger, path: list[str], left: list[t.Any], right: list[t.Any]) -> list[t.Any]:
|
||||
return left + right
|
||||
|
||||
class Prepend(MergeStrategy):
|
||||
def merge(self, merger: ObjectMerger, path: list[str], left: list[t.Any], right: list[t.Any]) -> list[t.Any]:
|
||||
return right + left
|
||||
|
||||
class Merge(MergeStrategy):
|
||||
def merge(self, merger: ObjectMerger, path: list[str], left: list[t.Any], right: list[t.Any]) -> list[t.Any]:
|
||||
result = left
|
||||
for i, value in enumerate(right):
|
||||
if i >= len(result):
|
||||
result.extend(right[i:])
|
||||
break
|
||||
|
||||
path.append(str(i))
|
||||
merged = merger.merge(path=path, left=result[i], right=value)
|
||||
merger.before_override(path=path, old_value=result[i], new_value=merged)
|
||||
result[i] = merged
|
||||
|
||||
return result
|
||||
|
||||
strategies = {
|
||||
"append": Append,
|
||||
"prepend": Prepend,
|
||||
"merge": Merge,
|
||||
"replace": BaseMergeStrategies.Replace,
|
||||
"keep": BaseMergeStrategies.Keep,
|
||||
}
|
||||
|
||||
|
||||
class Transformation(ABC):
|
||||
@abstractmethod
|
||||
def transform(self, merger: ObjectMerger, value: t.Any) -> t.Any:
|
||||
raise NotImplementedError
|
||||
|
||||
|
||||
class Transformations:
|
||||
@classmethod
|
||||
def from_name(cls, name: str, *args, **kwargs) -> Transformation:
|
||||
if name in cls.transformations:
|
||||
return cls.transformations[name](*args, **kwargs)
|
||||
else:
|
||||
raise AnsibleError(f"Unknown transformation '{name}'")
|
||||
|
||||
transformations: dict[str, Callable[..., t.Any]] = {}
|
||||
|
||||
|
||||
class ListTransformations(Transformations):
|
||||
class Dedup(Transformation):
|
||||
def __init__(self, keep: str = "first"):
|
||||
self.keep = keep
|
||||
|
||||
def transform(self, merger: ObjectMerger, value: list[t.Any]) -> list[t.Any]:
|
||||
result = []
|
||||
if self.keep == "first":
|
||||
for item in value:
|
||||
if item not in result:
|
||||
result.append(item)
|
||||
elif self.keep == "last":
|
||||
for item in reversed(value):
|
||||
if item not in result:
|
||||
result.insert(0, item)
|
||||
else:
|
||||
raise AnsibleError(
|
||||
f"Unsupported 'keep' value for deduplication transformation. Given was '{self.keep}', but must be either 'first' or 'last'"
|
||||
)
|
||||
|
||||
return result
|
||||
|
||||
class Flatten(Transformation):
|
||||
def transform(self, merger: ObjectMerger, value: list[t.Any]) -> list[t.Any]:
|
||||
result = []
|
||||
for item in value:
|
||||
if isinstance(item, list):
|
||||
result.extend(self.transform(merger, item))
|
||||
else:
|
||||
result.append(item)
|
||||
return result
|
||||
|
||||
transformations = {
|
||||
"dedup": Dedup,
|
||||
"flatten": Flatten,
|
||||
}
|
||||
|
||||
|
||||
class MergerBuilder:
|
||||
def __init__(self) -> None:
|
||||
self.type_strategies: list[tuple[type, MergeStrategy]] = []
|
||||
self.type_conflict_strategy: MergeStrategy = BaseMergeStrategies.Replace()
|
||||
self.default_strategy: MergeStrategy = BaseMergeStrategies.Replace()
|
||||
self.transformations: list[tuple[type, Transformation]] = []
|
||||
self.override_behavior: str = "error"
|
||||
self.shallow_merge: bool = False
|
||||
|
||||
def with_shallow_merge(self, shallow_merge: bool = True) -> MergerBuilder:
|
||||
self.shallow_merge = shallow_merge
|
||||
return self
|
||||
|
||||
def with_override_behavior(self, override_behavior: str) -> MergerBuilder:
|
||||
self.override_behavior = override_behavior
|
||||
return self
|
||||
|
||||
def with_type_strategy(self, cls, merge_strategy: MergeStrategy) -> MergerBuilder:
|
||||
self.type_strategies.append((cls, merge_strategy))
|
||||
return self
|
||||
|
||||
def with_default_strategy(self, merge_strategy: MergeStrategy) -> MergerBuilder:
|
||||
self.default_strategy = merge_strategy
|
||||
return self
|
||||
|
||||
def with_type_conflict_strategy(self, merge_strategy: MergeStrategy) -> MergerBuilder:
|
||||
self.type_conflict_strategy = merge_strategy
|
||||
return self
|
||||
|
||||
def with_transformation(self, cls, *args: Transformation) -> MergerBuilder:
|
||||
for transformation in args:
|
||||
self.transformations.append((cls, transformation))
|
||||
return self
|
||||
|
||||
def build(self) -> Merger:
|
||||
merger = ObjectMerger(
|
||||
type_strategies=self.type_strategies,
|
||||
type_conflict_strategy=self.type_conflict_strategy,
|
||||
default_strategy=self.default_strategy,
|
||||
transformations=self.transformations,
|
||||
override_behavior=self.override_behavior,
|
||||
)
|
||||
|
||||
if self.shallow_merge:
|
||||
return ShallowMerger(merger)
|
||||
|
||||
return merger
|
||||
|
||||
|
||||
class Merger(ABC):
|
||||
@abstractmethod
|
||||
def merge(self, path: list[str], left: t.Any, right: t.Any) -> t.Any:
|
||||
raise NotImplementedError
|
||||
|
||||
|
||||
class ObjectMerger(Merger):
|
||||
def __init__(
|
||||
self,
|
||||
type_strategies: list[tuple[type, MergeStrategy]],
|
||||
type_conflict_strategy: MergeStrategy,
|
||||
default_strategy: MergeStrategy,
|
||||
transformations: list[tuple[type, Transformation]],
|
||||
override_behavior: str,
|
||||
) -> None:
|
||||
self.type_strategies = type_strategies
|
||||
self.type_conflict_strategy = type_conflict_strategy
|
||||
self.default_strategy = default_strategy
|
||||
self.transformations = transformations
|
||||
self.override_behavior = override_behavior
|
||||
|
||||
def before_override(self, path: list[str], old_value: t.Any, new_value: t.Any) -> None:
|
||||
if (
|
||||
not isinstance(old_value, type(new_value))
|
||||
and not isinstance(new_value, type(old_value))
|
||||
or not isinstance(new_value, dict)
|
||||
and not isinstance(new_value, list)
|
||||
and old_value != new_value
|
||||
):
|
||||
# An override is regarded as a value type conflict or
|
||||
# when both values are neither dicts nor lists and
|
||||
# have different values
|
||||
msg = f"The key '{path[-1]}' with value '{old_value}' will be overwritten with value '{new_value}' from '{'.'.join(path)}'"
|
||||
if self.override_behavior == "error":
|
||||
raise AnsibleError(msg)
|
||||
elif self.override_behavior == "warn":
|
||||
display.warning(msg)
|
||||
|
||||
def transform(self, value: t.Any) -> t.Any:
|
||||
for cls, transformation in self.transformations:
|
||||
if isinstance(value, cls):
|
||||
value = transformation.transform(self, value)
|
||||
return value
|
||||
|
||||
def lookup_merge_strategy(self, left: t.Any, right: t.Any) -> MergeStrategy:
|
||||
for cls, merge_strategy in self.type_strategies:
|
||||
if isinstance(left, cls) and isinstance(right, cls):
|
||||
return merge_strategy
|
||||
|
||||
if not isinstance(left, type(right)) and not isinstance(right, type(left)):
|
||||
return self.type_conflict_strategy
|
||||
|
||||
return self.default_strategy
|
||||
|
||||
def apply_merge_strategy(self, merge_strategy: MergeStrategy, path: list[str], left: t.Any, right: t.Any) -> t.Any:
|
||||
return self.transform(merge_strategy.merge(self, path, left, right))
|
||||
|
||||
def merge(self, path: list[str], left: t.Any, right: t.Any) -> t.Any:
|
||||
return self.apply_merge_strategy(self.lookup_merge_strategy(left, right), path, left, right)
|
||||
|
||||
|
||||
class ShallowMerger(Merger):
|
||||
def __init__(self, merger: ObjectMerger) -> None:
|
||||
self.merger = merger
|
||||
|
||||
def merge(self, path: list[str], left: t.Any, right: t.Any) -> t.Any:
|
||||
if isinstance(left, dict) and isinstance(right, dict):
|
||||
return self.merger.apply_merge_strategy(DictMergeStrategies.Merge(), path, left, right)
|
||||
|
||||
return self.merger.merge(path, left, right)
|
||||
+163
@@ -0,0 +1,163 @@
|
||||
# Copyright (c) 2018, Scott Buchanan <scott@buchanan.works>
|
||||
# Copyright (c) 2016, Andrew Zenk <azenk@umn.edu> (lastpass.py used as starting point)
|
||||
# Copyright (c) 2018, Ansible Project
|
||||
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
DOCUMENTATION = r"""
|
||||
name: onepassword
|
||||
author:
|
||||
- Scott Buchanan (@scottsb)
|
||||
- Andrew Zenk (@azenk)
|
||||
- Sam Doran (@samdoran)
|
||||
short_description: Fetch field values from 1Password
|
||||
description:
|
||||
- P(community.general.onepassword#lookup) wraps the C(op) command line utility to fetch specific field values from 1Password.
|
||||
options:
|
||||
_terms:
|
||||
description:
|
||||
- Identifier(s) (case-insensitive UUID or name or secret reference) of item(s) to retrieve.
|
||||
- Secret references start with V(op://) and are supported since community.general 13.0.0.
|
||||
required: true
|
||||
type: list
|
||||
elements: string
|
||||
account_id:
|
||||
version_added: 7.5.0
|
||||
domain:
|
||||
version_added: 3.2.0
|
||||
field:
|
||||
description:
|
||||
- Field to return from each matching item (case-insensitive).
|
||||
- Ignored when using a secret reference, as the field is included in the secret reference.
|
||||
default: 'password'
|
||||
type: str
|
||||
service_account_token:
|
||||
version_added: 7.1.0
|
||||
extends_documentation_fragment:
|
||||
- community.general._onepassword
|
||||
- community.general._onepassword.lookup
|
||||
"""
|
||||
|
||||
EXAMPLES = r"""
|
||||
# These examples only work when already signed in to 1Password
|
||||
- name: Retrieve password for KITT when already signed in to 1Password
|
||||
ansible.builtin.debug:
|
||||
var: lookup('community.general.onepassword', 'KITT')
|
||||
|
||||
- name: Retrieve password for Wintermute when already signed in to 1Password
|
||||
ansible.builtin.debug:
|
||||
var: lookup('community.general.onepassword', 'Tessier-Ashpool', section='Wintermute')
|
||||
|
||||
- name: Retrieve username for HAL when already signed in to 1Password
|
||||
ansible.builtin.debug:
|
||||
var: lookup('community.general.onepassword', 'HAL 9000', field='username', vault='Discovery')
|
||||
|
||||
- name: Retrieve password for HAL when not signed in to 1Password
|
||||
ansible.builtin.debug:
|
||||
var: lookup('community.general.onepassword', 'HAL 9000', subdomain='Discovery', master_password=vault_master_password)
|
||||
|
||||
- name: Retrieve password for HAL when never signed in to 1Password
|
||||
ansible.builtin.debug:
|
||||
var: >-
|
||||
lookup('community.general.onepassword', 'HAL 9000', subdomain='Discovery', master_password=vault_master_password,
|
||||
username='tweety@acme.com', secret_key=vault_secret_key)
|
||||
|
||||
- name: Retrieve password from specific account
|
||||
ansible.builtin.debug:
|
||||
var: lookup('community.general.onepassword', 'HAL 9000', account_id='abc123')
|
||||
"""
|
||||
|
||||
RETURN = r"""
|
||||
_raw:
|
||||
description: Field data requested.
|
||||
type: list
|
||||
elements: str
|
||||
"""
|
||||
|
||||
import os
|
||||
import subprocess
|
||||
from contextlib import contextmanager
|
||||
|
||||
from ansible.errors import AnsibleLookupError, AnsibleOptionsError
|
||||
from ansible.plugins.lookup import LookupBase
|
||||
|
||||
from ansible_collections.community.general.plugins.module_utils._onepassword_cli import (
|
||||
OnePass,
|
||||
OnePasswordError,
|
||||
OnePasswordOptionsError,
|
||||
)
|
||||
from ansible_collections.community.general.plugins.plugin_utils._lookup import check_for_wrong_terms
|
||||
|
||||
|
||||
@contextmanager
|
||||
def onepassword_errors():
|
||||
try:
|
||||
yield
|
||||
except OnePasswordOptionsError as e:
|
||||
raise AnsibleOptionsError(str(e)) from e
|
||||
except OnePasswordError as e:
|
||||
raise AnsibleLookupError(str(e)) from e
|
||||
|
||||
|
||||
def run_command(command, command_input=None, environment_update=None):
|
||||
call_kwargs = {
|
||||
"stdout": subprocess.PIPE,
|
||||
"stderr": subprocess.PIPE,
|
||||
"stdin": subprocess.PIPE,
|
||||
}
|
||||
|
||||
if environment_update:
|
||||
env = os.environ.copy()
|
||||
env.update(environment_update)
|
||||
call_kwargs["env"] = env
|
||||
|
||||
p = subprocess.Popen(command, **call_kwargs)
|
||||
out, err = p.communicate(input=command_input)
|
||||
rc = p.wait()
|
||||
|
||||
return rc, out, err
|
||||
|
||||
|
||||
class LookupModule(LookupBase):
|
||||
@onepassword_errors()
|
||||
def run(self, terms, variables=None, **kwargs):
|
||||
self.set_options(var_options=variables, direct=kwargs)
|
||||
check_for_wrong_terms(self, direct=kwargs)
|
||||
|
||||
field = self.get_option("field")
|
||||
section = self.get_option("section")
|
||||
vault = self.get_option("vault")
|
||||
subdomain = self.get_option("subdomain")
|
||||
domain = self.get_option("domain")
|
||||
username = self.get_option("username")
|
||||
secret_key = self.get_option("secret_key")
|
||||
master_password = self.get_option("master_password")
|
||||
service_account_token = self.get_option("service_account_token")
|
||||
account_id = self.get_option("account_id")
|
||||
connect_host = self.get_option("connect_host")
|
||||
connect_token = self.get_option("connect_token")
|
||||
|
||||
op = OnePass(
|
||||
subdomain=subdomain,
|
||||
domain=domain,
|
||||
username=username,
|
||||
secret_key=secret_key,
|
||||
master_password=master_password,
|
||||
service_account_token=service_account_token,
|
||||
account_id=account_id,
|
||||
connect_host=connect_host,
|
||||
connect_token=connect_token,
|
||||
run_command=run_command,
|
||||
)
|
||||
op.assert_logged_in()
|
||||
|
||||
values = []
|
||||
for term in terms:
|
||||
if term.startswith("op://"):
|
||||
values.append(op.get_secret_reference(term))
|
||||
else:
|
||||
values.append(op.get_field(term, field, section, vault))
|
||||
|
||||
return values
|
||||
+92
@@ -0,0 +1,92 @@
|
||||
# Copyright (c) 2023, Ansible Project
|
||||
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
DOCUMENTATION = r"""
|
||||
name: onepassword_doc
|
||||
author:
|
||||
- Sam Doran (@samdoran)
|
||||
short_description: Fetch documents stored in 1Password
|
||||
version_added: "8.1.0"
|
||||
description:
|
||||
- P(community.general.onepassword_doc#lookup) wraps C(op) command line utility to fetch one or more documents from 1Password.
|
||||
notes:
|
||||
- The document contents are a string exactly as stored in 1Password.
|
||||
options:
|
||||
_terms:
|
||||
description: Identifier(s) (case-insensitive UUID or name) of item(s) to retrieve.
|
||||
required: true
|
||||
type: list
|
||||
elements: string
|
||||
|
||||
extends_documentation_fragment:
|
||||
- community.general._onepassword
|
||||
- community.general._onepassword.lookup
|
||||
"""
|
||||
|
||||
EXAMPLES = r"""
|
||||
---
|
||||
- name: Retrieve a private key from 1Password
|
||||
ansible.builtin.debug:
|
||||
var: lookup('community.general.onepassword_doc', 'Private key')
|
||||
"""
|
||||
|
||||
RETURN = r"""
|
||||
_raw:
|
||||
description: Requested document.
|
||||
type: list
|
||||
elements: string
|
||||
"""
|
||||
|
||||
from ansible.plugins.lookup import LookupBase
|
||||
|
||||
from ansible_collections.community.general.plugins.lookup.onepassword import onepassword_errors, run_command
|
||||
from ansible_collections.community.general.plugins.module_utils._onepassword_cli import OnePass, OnePassCLIv2
|
||||
from ansible_collections.community.general.plugins.plugin_utils._lookup import check_for_wrong_terms
|
||||
|
||||
|
||||
class OnePassCLIv2Doc(OnePassCLIv2):
|
||||
def get_raw(self, item_id, vault=None, token=None):
|
||||
args = ["document", "get", item_id]
|
||||
return self._add_parameters_and_run(args, vault=vault, token=token)
|
||||
|
||||
|
||||
class LookupModule(LookupBase):
|
||||
@onepassword_errors()
|
||||
def run(self, terms, variables=None, **kwargs):
|
||||
self.set_options(var_options=variables, direct=kwargs)
|
||||
check_for_wrong_terms(self, direct=kwargs)
|
||||
|
||||
vault = self.get_option("vault")
|
||||
subdomain = self.get_option("subdomain")
|
||||
domain = self.get_option("domain", "1password.com")
|
||||
username = self.get_option("username")
|
||||
secret_key = self.get_option("secret_key")
|
||||
master_password = self.get_option("master_password")
|
||||
service_account_token = self.get_option("service_account_token")
|
||||
account_id = self.get_option("account_id")
|
||||
connect_host = self.get_option("connect_host")
|
||||
connect_token = self.get_option("connect_token")
|
||||
|
||||
op = OnePass(
|
||||
subdomain=subdomain,
|
||||
domain=domain,
|
||||
username=username,
|
||||
secret_key=secret_key,
|
||||
master_password=master_password,
|
||||
service_account_token=service_account_token,
|
||||
account_id=account_id,
|
||||
connect_host=connect_host,
|
||||
connect_token=connect_token,
|
||||
run_command=run_command,
|
||||
cli_class=OnePassCLIv2Doc,
|
||||
)
|
||||
op.assert_logged_in()
|
||||
|
||||
values = []
|
||||
for term in terms:
|
||||
values.append(op.get_raw(term, vault))
|
||||
|
||||
return values
|
||||
+98
@@ -0,0 +1,98 @@
|
||||
# Copyright (c) 2018, Scott Buchanan <sbuchanan@ri.pn>
|
||||
# Copyright (c) 2016, Andrew Zenk <azenk@umn.edu> (lastpass.py used as starting point)
|
||||
# Copyright (c) 2018, Ansible Project
|
||||
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
DOCUMENTATION = r"""
|
||||
name: onepassword_raw
|
||||
author:
|
||||
- Scott Buchanan (@scottsb)
|
||||
- Andrew Zenk (@azenk)
|
||||
- Sam Doran (@samdoran)
|
||||
short_description: Fetch an entire item from 1Password
|
||||
description:
|
||||
- P(community.general.onepassword_raw#lookup) wraps C(op) command line utility to fetch an entire item from 1Password.
|
||||
options:
|
||||
_terms:
|
||||
description: Identifier(s) (case-insensitive UUID or name) of item(s) to retrieve.
|
||||
required: true
|
||||
type: list
|
||||
elements: string
|
||||
account_id:
|
||||
version_added: 7.5.0
|
||||
domain:
|
||||
version_added: 6.0.0
|
||||
service_account_token:
|
||||
version_added: 7.1.0
|
||||
extends_documentation_fragment:
|
||||
- community.general._onepassword
|
||||
- community.general._onepassword.lookup
|
||||
"""
|
||||
|
||||
EXAMPLES = r"""
|
||||
---
|
||||
- name: Retrieve all data about Wintermute
|
||||
ansible.builtin.debug:
|
||||
var: lookup('community.general.onepassword_raw', 'Wintermute')
|
||||
|
||||
- name: Retrieve all data about Wintermute when not signed in to 1Password
|
||||
ansible.builtin.debug:
|
||||
var: lookup('community.general.onepassword_raw', 'Wintermute', subdomain='Turing', vault_password='DmbslfLvasjdl')
|
||||
"""
|
||||
|
||||
RETURN = r"""
|
||||
_raw:
|
||||
description: Entire item requested.
|
||||
type: list
|
||||
elements: dict
|
||||
"""
|
||||
|
||||
import json
|
||||
|
||||
from ansible.plugins.lookup import LookupBase
|
||||
|
||||
from ansible_collections.community.general.plugins.lookup.onepassword import onepassword_errors, run_command
|
||||
from ansible_collections.community.general.plugins.module_utils._onepassword_cli import OnePass
|
||||
from ansible_collections.community.general.plugins.plugin_utils._lookup import check_for_wrong_terms
|
||||
|
||||
|
||||
class LookupModule(LookupBase):
|
||||
@onepassword_errors()
|
||||
def run(self, terms, variables=None, **kwargs):
|
||||
self.set_options(var_options=variables, direct=kwargs)
|
||||
check_for_wrong_terms(self, direct=kwargs)
|
||||
|
||||
vault = self.get_option("vault")
|
||||
subdomain = self.get_option("subdomain")
|
||||
domain = self.get_option("domain", "1password.com")
|
||||
username = self.get_option("username")
|
||||
secret_key = self.get_option("secret_key")
|
||||
master_password = self.get_option("master_password")
|
||||
service_account_token = self.get_option("service_account_token")
|
||||
account_id = self.get_option("account_id")
|
||||
connect_host = self.get_option("connect_host")
|
||||
connect_token = self.get_option("connect_token")
|
||||
|
||||
op = OnePass(
|
||||
subdomain=subdomain,
|
||||
domain=domain,
|
||||
username=username,
|
||||
secret_key=secret_key,
|
||||
master_password=master_password,
|
||||
service_account_token=service_account_token,
|
||||
account_id=account_id,
|
||||
connect_host=connect_host,
|
||||
connect_token=connect_token,
|
||||
run_command=run_command,
|
||||
)
|
||||
op.assert_logged_in()
|
||||
|
||||
values = []
|
||||
for term in terms:
|
||||
data = json.loads(op.get_raw(term, vault))
|
||||
values.append(data)
|
||||
|
||||
return values
|
||||
+114
@@ -0,0 +1,114 @@
|
||||
# Copyright (c) 2025, Ansible Project
|
||||
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
DOCUMENTATION = r"""
|
||||
name: onepassword_ssh_key
|
||||
author:
|
||||
- Mohammed Babelly (@mohammedbabelly20)
|
||||
short_description: Fetch SSH keys stored in 1Password
|
||||
version_added: "10.3.0"
|
||||
description:
|
||||
- P(community.general.onepassword_ssh_key#lookup) wraps C(op) command line utility to fetch SSH keys from 1Password.
|
||||
notes:
|
||||
- By default, it returns the private key value in PKCS#8 format, unless O(ssh_format=true) is passed.
|
||||
- The pluging works only for C(SSHKEY) type items.
|
||||
options:
|
||||
_terms:
|
||||
description: Identifier(s) (case-insensitive UUID or name) of item(s) to retrieve.
|
||||
required: true
|
||||
type: list
|
||||
elements: string
|
||||
ssh_format:
|
||||
description: Output key in SSH format if V(true). Otherwise, outputs in the default format (PKCS#8).
|
||||
default: false
|
||||
type: bool
|
||||
|
||||
extends_documentation_fragment:
|
||||
- community.general._onepassword
|
||||
- community.general._onepassword.lookup
|
||||
"""
|
||||
|
||||
EXAMPLES = r"""
|
||||
---
|
||||
- name: Retrieve the private SSH key from 1Password
|
||||
ansible.builtin.debug:
|
||||
msg: "{{ lookup('community.general.onepassword_ssh_key', 'SSH Key', ssh_format=true) }}"
|
||||
"""
|
||||
|
||||
RETURN = r"""
|
||||
_raw:
|
||||
description: Private key of SSH keypair.
|
||||
type: list
|
||||
elements: string
|
||||
"""
|
||||
import json
|
||||
|
||||
from ansible.errors import AnsibleLookupError
|
||||
from ansible.plugins.lookup import LookupBase
|
||||
|
||||
from ansible_collections.community.general.plugins.lookup.onepassword import onepassword_errors, run_command
|
||||
from ansible_collections.community.general.plugins.module_utils._onepassword_cli import (
|
||||
OnePass,
|
||||
OnePassCLIv2,
|
||||
)
|
||||
from ansible_collections.community.general.plugins.plugin_utils._lookup import check_for_wrong_terms
|
||||
|
||||
|
||||
class LookupModule(LookupBase):
|
||||
def get_ssh_key(self, out, item_id, ssh_format=False):
|
||||
data = json.loads(out)
|
||||
|
||||
if data.get("category") != "SSH_KEY":
|
||||
raise AnsibleLookupError(f"Item {item_id} is not an SSH key")
|
||||
|
||||
private_key_field = next(
|
||||
(
|
||||
field
|
||||
for field in data.get("fields", {})
|
||||
if field.get("id") == "private_key" and field.get("type") == "SSHKEY"
|
||||
),
|
||||
None,
|
||||
)
|
||||
if not private_key_field:
|
||||
raise AnsibleLookupError(f"No private key found for item {item_id}.")
|
||||
|
||||
if ssh_format:
|
||||
return private_key_field.get("ssh_formats", {}).get("openssh", {}).get("value", "")
|
||||
return private_key_field.get("value", "")
|
||||
|
||||
@onepassword_errors()
|
||||
def run(self, terms, variables=None, **kwargs):
|
||||
self.set_options(var_options=variables, direct=kwargs)
|
||||
check_for_wrong_terms(self, direct=kwargs)
|
||||
|
||||
ssh_format = self.get_option("ssh_format")
|
||||
vault = self.get_option("vault")
|
||||
subdomain = self.get_option("subdomain")
|
||||
domain = self.get_option("domain", "1password.com")
|
||||
username = self.get_option("username")
|
||||
secret_key = self.get_option("secret_key")
|
||||
master_password = self.get_option("master_password")
|
||||
service_account_token = self.get_option("service_account_token")
|
||||
account_id = self.get_option("account_id")
|
||||
connect_host = self.get_option("connect_host")
|
||||
connect_token = self.get_option("connect_token")
|
||||
|
||||
op = OnePass(
|
||||
subdomain=subdomain,
|
||||
domain=domain,
|
||||
username=username,
|
||||
secret_key=secret_key,
|
||||
master_password=master_password,
|
||||
service_account_token=service_account_token,
|
||||
account_id=account_id,
|
||||
connect_host=connect_host,
|
||||
connect_token=connect_token,
|
||||
run_command=run_command,
|
||||
cli_class=OnePassCLIv2,
|
||||
)
|
||||
op.assert_logged_in()
|
||||
|
||||
return [self.get_ssh_key(op.get_raw(term, vault), term, ssh_format=ssh_format) for term in terms]
|
||||
+616
@@ -0,0 +1,616 @@
|
||||
# Copyright (c) 2017, Patrick Deelman <patrick@patrickdeelman.nl>
|
||||
# Copyright (c) 2017 Ansible Project
|
||||
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
from __future__ import annotations
|
||||
|
||||
DOCUMENTATION = r"""
|
||||
name: passwordstore
|
||||
author:
|
||||
- Patrick Deelman (!UNKNOWN) <patrick@patrickdeelman.nl>
|
||||
short_description: Manage passwords with passwordstore.org's pass utility
|
||||
description:
|
||||
- Enables Ansible to retrieve, create or update passwords from the passwordstore.org pass utility. It can also retrieve,
|
||||
create or update YAML style keys stored as multilines in the passwordfile.
|
||||
- To avoid problems when accessing multiple secrets at once, add C(auto-expand-secmem) to C(~/.gnupg/gpg-agent.conf). Where
|
||||
this is not possible, consider using O(lock=readwrite) instead.
|
||||
options:
|
||||
_terms:
|
||||
description: Query key.
|
||||
required: true
|
||||
directory:
|
||||
description:
|
||||
- The directory of the password store.
|
||||
- If O(backend=pass), the default is V(~/.password-store) is used.
|
||||
- If O(backend=gopass), then the default is the C(path) field in C(~/.config/gopass/config.yml), falling back to V(~/.local/share/gopass/stores/root)
|
||||
if C(path) is not defined in the gopass config.
|
||||
type: path
|
||||
ini:
|
||||
- section: passwordstore_lookup
|
||||
key: directory
|
||||
version_added: 13.2.0
|
||||
vars:
|
||||
- name: passwordstore
|
||||
env:
|
||||
- name: PASSWORD_STORE_DIR
|
||||
create:
|
||||
description: Create the password or the subkey if it does not already exist. Takes precedence over O(missing).
|
||||
type: bool
|
||||
default: false
|
||||
overwrite:
|
||||
description: Overwrite the password or the subkey if it does already exist.
|
||||
type: bool
|
||||
default: false
|
||||
umask:
|
||||
description:
|
||||
- Sets the umask for the created V(.gpg) files. The first octed must be greater than 3 (user readable).
|
||||
- Note pass' default value is V('077').
|
||||
type: string
|
||||
env:
|
||||
- name: PASSWORD_STORE_UMASK
|
||||
version_added: 1.3.0
|
||||
returnall:
|
||||
description: Return all the content of the password, not only the first line.
|
||||
type: bool
|
||||
default: false
|
||||
keep_trailing_newline:
|
||||
description:
|
||||
- Keep the trailing newline in the password file content when O(returnall=true).
|
||||
- Only used when O(returnall=true), ignored otherwise.
|
||||
type: bool
|
||||
default: false
|
||||
version_added: 13.4.0
|
||||
subkey:
|
||||
description:
|
||||
- By default return a specific subkey of the password. When set to V(password), always returns the first line.
|
||||
- With O(overwrite=true), it creates the subkey and returns it.
|
||||
type: str
|
||||
default: password
|
||||
userpass:
|
||||
description: Specify a password to save, instead of a generated one.
|
||||
type: str
|
||||
secret: true
|
||||
length:
|
||||
description: The length of the generated password.
|
||||
type: integer
|
||||
default: 16
|
||||
backup:
|
||||
description: Used with O(overwrite=true). Backup the previous password or subkey in a subkey.
|
||||
type: bool
|
||||
default: false
|
||||
nosymbols:
|
||||
description: Use alphanumeric characters.
|
||||
type: bool
|
||||
default: false
|
||||
missing:
|
||||
description:
|
||||
- List of preference about what to do if the password file is missing.
|
||||
- If O(create=true), the value for this option is ignored and assumed to be V(create).
|
||||
- If set to V(error), the lookup fails out if the passname does not exist.
|
||||
- If set to V(create), the passname is created with the provided length O(length) if it does not exist.
|
||||
- If set to V(empty) or V(warn), it returns a V(none) in case the passname does not exist. When using C(lookup) and
|
||||
not C(query), this is translated to an empty string.
|
||||
version_added: 3.1.0
|
||||
type: str
|
||||
default: error
|
||||
choices:
|
||||
- error
|
||||
- warn
|
||||
- empty
|
||||
- create
|
||||
lock:
|
||||
description:
|
||||
- How to synchronize operations.
|
||||
- The default of V(write) only synchronizes write operations.
|
||||
- V(readwrite) synchronizes all operations (including read). This makes sure that gpg-agent is never called in parallel.
|
||||
- V(none) does not do any synchronization.
|
||||
ini:
|
||||
- section: passwordstore_lookup
|
||||
key: lock
|
||||
type: str
|
||||
default: write
|
||||
choices:
|
||||
- readwrite
|
||||
- write
|
||||
- none
|
||||
version_added: 4.5.0
|
||||
locktimeout:
|
||||
description:
|
||||
- Lock timeout applied when O(lock) is not V(none).
|
||||
- Time with a unit suffix, V(s), V(m), V(h) for seconds, minutes, and hours, respectively. For example, V(900s) equals
|
||||
V(15m).
|
||||
- Correlates with C(pinentry-timeout) in C(~/.gnupg/gpg-agent.conf), see C(man gpg-agent) for details.
|
||||
ini:
|
||||
- section: passwordstore_lookup
|
||||
key: locktimeout
|
||||
type: str
|
||||
default: 15m
|
||||
version_added: 4.5.0
|
||||
backend:
|
||||
description:
|
||||
- Specify which backend to use.
|
||||
- Defaults to V(pass), passwordstore.org's original pass utility.
|
||||
- V(gopass) support is incomplete.
|
||||
ini:
|
||||
- section: passwordstore_lookup
|
||||
key: backend
|
||||
vars:
|
||||
- name: passwordstore_backend
|
||||
type: str
|
||||
default: pass
|
||||
choices:
|
||||
- pass
|
||||
- gopass
|
||||
version_added: 5.2.0
|
||||
timestamp:
|
||||
description: Add the password generation information to the end of the file.
|
||||
type: bool
|
||||
default: true
|
||||
version_added: 8.1.0
|
||||
preserve:
|
||||
description: Include the old (edited) password inside the pass file.
|
||||
type: bool
|
||||
default: true
|
||||
version_added: 8.1.0
|
||||
missing_subkey:
|
||||
description:
|
||||
- Preference about what to do if the password subkey is missing.
|
||||
- If set to V(error), the lookup fails out if the subkey does not exist.
|
||||
- If set to V(empty) or V(warn), it returns a V(none) in case the subkey does not exist.
|
||||
version_added: 8.6.0
|
||||
type: str
|
||||
default: empty
|
||||
choices:
|
||||
- error
|
||||
- warn
|
||||
- empty
|
||||
ini:
|
||||
- section: passwordstore_lookup
|
||||
key: missing_subkey
|
||||
notes:
|
||||
- The lookup supports passing all options as lookup parameters since community.general 6.0.0.
|
||||
"""
|
||||
EXAMPLES = r"""
|
||||
ansible.cfg: |
|
||||
[passwordstore_lookup]
|
||||
lock=readwrite
|
||||
locktimeout=45s
|
||||
missing_subkey=warn
|
||||
|
||||
tasks.yml: |-
|
||||
---
|
||||
|
||||
# Debug is used for examples, BAD IDEA to show passwords on screen
|
||||
- name: Basic lookup. Fails if example/test does not exist
|
||||
ansible.builtin.debug:
|
||||
msg: "{{ lookup('community.general.passwordstore', 'example/test')}}"
|
||||
|
||||
- name: Basic lookup. Warns if example/test does not exist and returns empty string
|
||||
ansible.builtin.debug:
|
||||
msg: "{{ lookup('community.general.passwordstore', 'example/test', missing='warn')}}"
|
||||
|
||||
- name: Create pass with random 16 character password. If password exists just give the password
|
||||
ansible.builtin.debug:
|
||||
var: mypassword
|
||||
vars:
|
||||
mypassword: "{{ lookup('community.general.passwordstore', 'example/test', create=true)}}"
|
||||
|
||||
- name: Create pass with random 16 character password. If password exists just give the password
|
||||
ansible.builtin.debug:
|
||||
var: mypassword
|
||||
vars:
|
||||
mypassword: "{{ lookup('community.general.passwordstore', 'example/test', missing='create')}}"
|
||||
|
||||
- name: >-
|
||||
Create a random 16 character password in a subkey. If the password file already exists, just add the subkey in it.
|
||||
If the subkey exists, returns it
|
||||
ansible.builtin.debug:
|
||||
msg: "{{ lookup('community.general.passwordstore', 'example/test', create=true, subkey='foo') }}"
|
||||
|
||||
- name: >-
|
||||
Create a random 16 character password in a subkey. Overwrite if it already exists and backup the old one.
|
||||
ansible.builtin.debug:
|
||||
msg: "{{ lookup('community.general.passwordstore', 'example/test', create=true, subkey='user', overwrite=true, backup=true) }}"
|
||||
|
||||
- name: Prints 'abc' if example/test does not exist, just give the password otherwise
|
||||
ansible.builtin.debug:
|
||||
var: mypassword
|
||||
vars:
|
||||
mypassword: >-
|
||||
{{ lookup('community.general.passwordstore', 'example/test', missing='empty')
|
||||
| default('abc', true) }}
|
||||
|
||||
- name: Different size password
|
||||
ansible.builtin.debug:
|
||||
msg: "{{ lookup('community.general.passwordstore', 'example/test', create=true, length=42)}}"
|
||||
|
||||
- name: >-
|
||||
Create password and overwrite the password if it exists.
|
||||
As a bonus, this module includes the old password inside the pass file
|
||||
ansible.builtin.debug:
|
||||
msg: "{{ lookup('community.general.passwordstore', 'example/test', create=true, overwrite=true)}}"
|
||||
|
||||
- name: Create an alphanumeric password
|
||||
ansible.builtin.debug:
|
||||
msg: "{{ lookup('community.general.passwordstore', 'example/test', create=true, nosymbols=true) }}"
|
||||
|
||||
- name: Return the value for user in the KV pair user, username
|
||||
ansible.builtin.debug:
|
||||
msg: "{{ lookup('community.general.passwordstore', 'example/test', subkey='user')}}"
|
||||
|
||||
- name: Return the entire password file content
|
||||
ansible.builtin.set_fact:
|
||||
passfilecontent: "{{ lookup('community.general.passwordstore', 'example/test', returnall=true)}}"
|
||||
|
||||
- name: Return the entire password file content, keeping its trailing newline
|
||||
ansible.builtin.set_fact:
|
||||
passfilecontent: "{{ lookup('community.general.passwordstore', 'example/test', returnall=true, keep_trailing_newline=true)}}"
|
||||
"""
|
||||
|
||||
RETURN = r"""
|
||||
_raw:
|
||||
description:
|
||||
- A password.
|
||||
type: list
|
||||
elements: str
|
||||
"""
|
||||
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import time
|
||||
from contextlib import contextmanager
|
||||
|
||||
import yaml
|
||||
from ansible import constants as C
|
||||
from ansible.errors import AnsibleAssertionError, AnsibleError
|
||||
from ansible.module_utils.common.text.converters import to_bytes, to_native, to_text
|
||||
from ansible.module_utils.parsing.convert_bool import boolean
|
||||
from ansible.plugins.lookup import LookupBase
|
||||
from ansible.utils.display import Display
|
||||
from ansible.utils.encrypt import random_password
|
||||
|
||||
from ansible_collections.community.general.plugins.module_utils._filelock import FileLock
|
||||
from ansible_collections.community.general.plugins.plugin_utils._lookup import check_for_wrong_terms
|
||||
|
||||
display = Display()
|
||||
|
||||
|
||||
def run_backend_cmd(cmd, *, input=None, env=None):
|
||||
result = subprocess.run(
|
||||
cmd,
|
||||
check=False,
|
||||
capture_output=True,
|
||||
input=to_bytes(input, errors="surrogate_or_strict") if input else None,
|
||||
env=env,
|
||||
)
|
||||
b_out, b_err = result.stdout, result.stderr
|
||||
retcode = result.returncode
|
||||
if retcode == 0 and (
|
||||
b"encryption failed: Unusable public key" in b_out or b"encryption failed: Unusable public key" in b_err
|
||||
):
|
||||
retcode = 78 # os.EX_CONFIG
|
||||
if retcode != 0:
|
||||
raise subprocess.CalledProcessError(retcode, cmd, to_native(b_out + b_err, errors="surrogate_or_strict"))
|
||||
return b_out
|
||||
|
||||
|
||||
class LookupModule(LookupBase):
|
||||
def __init__(self, loader=None, templar=None, **kwargs):
|
||||
super().__init__(loader, templar, **kwargs)
|
||||
self.realpass = None
|
||||
|
||||
def is_real_pass(self):
|
||||
if self.realpass is None:
|
||||
try:
|
||||
passoutput = to_text(
|
||||
run_backend_cmd([self.pass_cmd, "--version"], env=self.env), errors="surrogate_or_strict"
|
||||
)
|
||||
self.realpass = "pass: the standard unix password manager" in passoutput
|
||||
except subprocess.CalledProcessError as e:
|
||||
raise AnsibleError(f"exit code {e.returncode} while running {e.cmd}. Error output: {e.output}") from e
|
||||
|
||||
return self.realpass
|
||||
|
||||
def is_gopass_secret(self):
|
||||
# gopass shows the folder tree when the passname is a folder, so look it up in the listing of its parent folder,
|
||||
# which gopass resolves through its mounts
|
||||
parent = self.passname.rpartition("/")[0]
|
||||
try:
|
||||
listing = to_text(
|
||||
run_backend_cmd(
|
||||
[self.pass_cmd, "ls", "--flat", "--limit", "0"] + ([parent] if parent else []), env=self.env
|
||||
),
|
||||
errors="surrogate_or_strict",
|
||||
)
|
||||
except subprocess.CalledProcessError as e:
|
||||
raise AnsibleError(f"exit code {e.returncode} while running {e.cmd}. Error output: {e.output}") from e
|
||||
|
||||
return self.passname in listing.splitlines()
|
||||
|
||||
def parse_params(self, term):
|
||||
# I went with the "traditional" param followed with space separated KV pairs.
|
||||
# Waiting for final implementation of lookup parameter parsing.
|
||||
# See: https://github.com/ansible/ansible/issues/12255
|
||||
params = term.split()
|
||||
if len(params) > 0:
|
||||
# the first param is the pass-name
|
||||
self.passname = params[0]
|
||||
# next parse the optional parameters in keyvalue pairs
|
||||
try:
|
||||
for param in params[1:]:
|
||||
name, value = param.split("=", 1)
|
||||
if name not in self.paramvals:
|
||||
raise AnsibleAssertionError(f"{name} not in paramvals")
|
||||
self.paramvals[name] = value
|
||||
except (ValueError, AssertionError) as e:
|
||||
raise AnsibleError(e) from e
|
||||
# check and convert values
|
||||
try:
|
||||
for key in ["create", "returnall", "keep_trailing_newline", "overwrite", "backup", "nosymbols"]:
|
||||
if not isinstance(self.paramvals[key], bool):
|
||||
self.paramvals[key] = boolean(self.paramvals[key])
|
||||
except (ValueError, AssertionError) as e:
|
||||
raise AnsibleError(e) from e
|
||||
if self.paramvals["missing"] not in ["error", "warn", "create", "empty"]:
|
||||
raise AnsibleError(f"{self.paramvals['missing']} is not a valid option for missing")
|
||||
if not isinstance(self.paramvals["length"], int):
|
||||
if self.paramvals["length"].isdigit():
|
||||
self.paramvals["length"] = int(self.paramvals["length"])
|
||||
else:
|
||||
raise AnsibleError(f"{self.paramvals['length']} is not a correct value for length")
|
||||
|
||||
if self.paramvals["create"]:
|
||||
self.paramvals["missing"] = "create"
|
||||
|
||||
# Collect pass environment variables from the plugin's parameters.
|
||||
self.env = os.environ.copy()
|
||||
self.env["LANGUAGE"] = "C" # make sure to get errors in English as required by run_backend_cmd
|
||||
|
||||
if self.backend == "gopass":
|
||||
self.env["GOPASS_NO_REMINDER"] = "YES"
|
||||
elif os.path.isdir(self.paramvals["directory"]):
|
||||
# Set PASSWORD_STORE_DIR
|
||||
self.env["PASSWORD_STORE_DIR"] = self.paramvals["directory"]
|
||||
elif self.is_real_pass():
|
||||
raise AnsibleError(f"Passwordstore directory '{self.paramvals['directory']}' does not exist")
|
||||
|
||||
# Set PASSWORD_STORE_UMASK if umask is set
|
||||
if self.paramvals.get("umask") is not None:
|
||||
if len(self.paramvals["umask"]) != 3:
|
||||
raise AnsibleError("Passwordstore umask must have a length of 3.")
|
||||
elif int(self.paramvals["umask"][0]) > 3:
|
||||
raise AnsibleError("Passwordstore umask not allowed (password not user readable).")
|
||||
else:
|
||||
self.env["PASSWORD_STORE_UMASK"] = self.paramvals["umask"]
|
||||
|
||||
def check_pass(self):
|
||||
try:
|
||||
raw_output = to_text(
|
||||
run_backend_cmd([self.pass_cmd, "show"] + [self.passname], env=self.env), errors="surrogate_or_strict"
|
||||
)
|
||||
self.passoutput_had_trailing_newline = raw_output.endswith("\n")
|
||||
self.passoutput = raw_output.splitlines()
|
||||
self.password = self.passoutput[0]
|
||||
self.passdict = {}
|
||||
try:
|
||||
values = yaml.safe_load("\n".join(self.passoutput[1:]))
|
||||
for key, item in values.items():
|
||||
self.passdict[key] = item
|
||||
except (yaml.YAMLError, AttributeError):
|
||||
for line in self.passoutput[1:]:
|
||||
if ":" in line:
|
||||
name, value = line.split(":", 1)
|
||||
self.passdict[name.strip()] = value.strip()
|
||||
if self.backend == "gopass":
|
||||
if self.is_gopass_secret():
|
||||
return True
|
||||
elif (
|
||||
os.path.isfile(os.path.join(self.paramvals["directory"], f"{self.passname}.gpg"))
|
||||
or not self.is_real_pass()
|
||||
):
|
||||
# When using real pass, only accept password as found if there is a .gpg file for it (might be a tree node otherwise)
|
||||
return True
|
||||
except subprocess.CalledProcessError as e:
|
||||
# 'not in password store' is the expected error if a password wasn't found
|
||||
if "not in the password store" not in e.output:
|
||||
raise AnsibleError(f"exit code {e.returncode} while running {e.cmd}. Error output: {e.output}") from e
|
||||
|
||||
if self.paramvals["missing"] == "error":
|
||||
raise AnsibleError(f"passwordstore: passname {self.passname} not found and missing=error is set")
|
||||
elif self.paramvals["missing"] == "warn":
|
||||
display.warning(f"passwordstore: passname {self.passname} not found")
|
||||
|
||||
return False
|
||||
|
||||
def get_newpass(self):
|
||||
if self.paramvals["nosymbols"]:
|
||||
chars = C.DEFAULT_PASSWORD_CHARS[:62]
|
||||
else:
|
||||
chars = C.DEFAULT_PASSWORD_CHARS
|
||||
|
||||
if self.paramvals["userpass"]:
|
||||
newpass = self.paramvals["userpass"]
|
||||
else:
|
||||
newpass = random_password(length=self.paramvals["length"], chars=chars)
|
||||
return newpass
|
||||
|
||||
def update_password(self):
|
||||
# generate new password, insert old lines from current result and return new password
|
||||
# if the target is a subkey, only modify the subkey
|
||||
newpass = self.get_newpass()
|
||||
datetime = time.strftime("%d/%m/%Y %H:%M:%S")
|
||||
subkey = self.paramvals["subkey"]
|
||||
|
||||
if subkey != "password":
|
||||
msg_lines = []
|
||||
subkey_exists = False
|
||||
subkey_line = f"{subkey}: {newpass}"
|
||||
oldpass = None
|
||||
|
||||
for line in self.passoutput:
|
||||
if line.startswith(f"{subkey}: "):
|
||||
oldpass = self.passdict[subkey]
|
||||
line = subkey_line
|
||||
subkey_exists = True
|
||||
|
||||
msg_lines.append(line)
|
||||
|
||||
if not subkey_exists:
|
||||
msg_lines.insert(2, subkey_line)
|
||||
|
||||
if self.paramvals["timestamp"] and self.paramvals["backup"] and oldpass and oldpass != newpass:
|
||||
msg_lines.append(f"lookup_pass: old subkey '{subkey}' password was {oldpass} (Updated on {datetime})\n")
|
||||
|
||||
msg = os.linesep.join(msg_lines)
|
||||
|
||||
else:
|
||||
msg = newpass
|
||||
|
||||
if self.paramvals["preserve"] or self.paramvals["timestamp"]:
|
||||
msg += "\n"
|
||||
if self.paramvals["preserve"] and self.passoutput[1:]:
|
||||
msg += "\n".join(self.passoutput[1:])
|
||||
msg += "\n"
|
||||
if self.paramvals["timestamp"] and self.paramvals["backup"]:
|
||||
msg += f"lookup_pass: old password was {self.password} (Updated on {datetime})\n"
|
||||
|
||||
try:
|
||||
run_backend_cmd([self.pass_cmd, "insert", "-f", "-m", self.passname], input=msg, env=self.env)
|
||||
except subprocess.CalledProcessError as e:
|
||||
raise AnsibleError(f"exit code {e.returncode} while running {e.cmd}. Error output: {e.output}") from e
|
||||
return newpass
|
||||
|
||||
def generate_password(self):
|
||||
# generate new file and insert lookup_pass: Generated by Ansible on {date}
|
||||
# use pwgen to generate the password and insert values with pass -m
|
||||
newpass = self.get_newpass()
|
||||
datetime = time.strftime("%d/%m/%Y %H:%M:%S")
|
||||
subkey = self.paramvals["subkey"]
|
||||
|
||||
if subkey != "password":
|
||||
msg = f"\n\n{subkey}: {newpass}"
|
||||
else:
|
||||
msg = newpass
|
||||
|
||||
if self.paramvals["timestamp"]:
|
||||
msg += f"\nlookup_pass: First generated by ansible on {datetime}\n"
|
||||
|
||||
try:
|
||||
run_backend_cmd([self.pass_cmd, "insert", "-f", "-m", self.passname], input=msg, env=self.env)
|
||||
except subprocess.CalledProcessError as e:
|
||||
raise AnsibleError(f"exit code {e.returncode} while running {e.cmd}. Error output: {e.output}") from e
|
||||
|
||||
return newpass
|
||||
|
||||
def get_passresult(self):
|
||||
if self.paramvals["returnall"]:
|
||||
result = os.linesep.join(self.passoutput)
|
||||
if self.paramvals["keep_trailing_newline"] and self.passoutput_had_trailing_newline:
|
||||
result += os.linesep
|
||||
return result
|
||||
if self.paramvals["subkey"] == "password":
|
||||
return self.password
|
||||
else:
|
||||
if self.paramvals["subkey"] in self.passdict:
|
||||
return self.passdict[self.paramvals["subkey"]]
|
||||
else:
|
||||
if self.paramvals["missing_subkey"] == "error":
|
||||
raise AnsibleError(
|
||||
f"passwordstore: subkey {self.paramvals['subkey']} for passname {self.passname} not found and missing_subkey=error is set"
|
||||
)
|
||||
|
||||
if self.paramvals["missing_subkey"] == "warn":
|
||||
display.warning(
|
||||
f"passwordstore: subkey {self.paramvals['subkey']} for passname {self.passname} not found"
|
||||
)
|
||||
|
||||
return None
|
||||
|
||||
@contextmanager
|
||||
def opt_lock(self, type):
|
||||
if self.get_option("lock") == type:
|
||||
tmpdir = os.environ.get("TMPDIR", "/tmp")
|
||||
user = os.environ.get("USER")
|
||||
lockfile = os.path.join(tmpdir, f".{user}.passwordstore.lock")
|
||||
with FileLock().lock_file(lockfile, tmpdir, self.lock_timeout):
|
||||
self.locked = type
|
||||
yield
|
||||
self.locked = None
|
||||
else:
|
||||
yield
|
||||
|
||||
def setup(self, variables):
|
||||
self.backend = self.get_option("backend")
|
||||
self.pass_cmd = self.backend # pass and gopass are commands as well
|
||||
self.locked = None
|
||||
timeout = self.get_option("locktimeout")
|
||||
if not re.match("^[0-9]+[smh]$", timeout):
|
||||
raise AnsibleError(f"{timeout} is not a correct value for locktimeout")
|
||||
unit_to_seconds = {"s": 1, "m": 60, "h": 3600}
|
||||
self.lock_timeout = int(timeout[:-1]) * unit_to_seconds[timeout[-1]]
|
||||
|
||||
directory = self.get_option("directory")
|
||||
if directory is None:
|
||||
if self.backend == "gopass":
|
||||
try:
|
||||
with open(os.path.expanduser("~/.config/gopass/config.yml")) as f:
|
||||
directory = yaml.safe_load(f)["path"]
|
||||
except (FileNotFoundError, KeyError, yaml.YAMLError):
|
||||
directory = os.path.expanduser("~/.local/share/gopass/stores/root")
|
||||
else:
|
||||
directory = os.path.expanduser("~/.password-store")
|
||||
|
||||
self.paramvals = {
|
||||
"subkey": self.get_option("subkey"),
|
||||
"directory": directory,
|
||||
"create": self.get_option("create"),
|
||||
"returnall": self.get_option("returnall"),
|
||||
"keep_trailing_newline": self.get_option("keep_trailing_newline"),
|
||||
"overwrite": self.get_option("overwrite"),
|
||||
"nosymbols": self.get_option("nosymbols"),
|
||||
"userpass": self.get_option("userpass") or "",
|
||||
"length": self.get_option("length"),
|
||||
"backup": self.get_option("backup"),
|
||||
"missing": self.get_option("missing"),
|
||||
"umask": self.get_option("umask"),
|
||||
"timestamp": self.get_option("timestamp"),
|
||||
"preserve": self.get_option("preserve"),
|
||||
"missing_subkey": self.get_option("missing_subkey"),
|
||||
}
|
||||
|
||||
def run(self, terms, variables, **kwargs):
|
||||
self.set_options(var_options=variables, direct=kwargs)
|
||||
check_for_wrong_terms(self, direct=kwargs)
|
||||
self.setup(variables)
|
||||
result = []
|
||||
|
||||
for term in terms:
|
||||
self.parse_params(term) # parse the input into paramvals
|
||||
with self.opt_lock("readwrite"):
|
||||
if self.check_pass(): # password file exists
|
||||
if self.paramvals["overwrite"]: # if "overwrite", always update password
|
||||
with self.opt_lock("write"):
|
||||
result.append(self.update_password())
|
||||
elif (
|
||||
self.paramvals["subkey"] != "password"
|
||||
and not self.passdict.get(self.paramvals["subkey"])
|
||||
and self.paramvals["missing"] == "create"
|
||||
): # target is a subkey, this subkey is not in passdict BUT missing == create
|
||||
with self.opt_lock("write"):
|
||||
result.append(self.update_password())
|
||||
else:
|
||||
result.append(self.get_passresult())
|
||||
else: # password does not exist
|
||||
if self.paramvals["missing"] == "create":
|
||||
with self.opt_lock("write"):
|
||||
if (
|
||||
self.locked == "write" and self.check_pass()
|
||||
): # lookup password again if under write lock
|
||||
result.append(self.get_passresult())
|
||||
else:
|
||||
result.append(self.generate_password())
|
||||
else:
|
||||
result.append(None)
|
||||
|
||||
return result
|
||||
+631
@@ -0,0 +1,631 @@
|
||||
# Copyright (c) 2026, Jean Khawand (@jeankhawand)
|
||||
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
DOCUMENTATION = r"""
|
||||
name: proton_pass
|
||||
author:
|
||||
- Jean Khawand (@jeankhawand)
|
||||
version_added: "13.2.0"
|
||||
short_description: Fetch secrets from Proton Pass via the C(pass-cli) command-line tool.
|
||||
description:
|
||||
- Retrieves secrets stored in Proton Pass by calling the C(pass-cli) binary
|
||||
on the Ansible control machine.
|
||||
- When only one item title is given, returns a dictionary of all extra fields for
|
||||
that item so the caller can access individual secrets by key.
|
||||
- When a field name is also given, returns the field value as a string directly,
|
||||
without parsing JSON.
|
||||
- Every lookup invokes C(pass-cli) directly — no in-process caching — so each
|
||||
call always reflects the current vault state.
|
||||
requirements:
|
||||
- C(pass-cli) installed on the Ansible control machine
|
||||
(see U(https://github.com/protonpass/pass-cli))
|
||||
notes:
|
||||
- Two non-interactive authentication paths are available.
|
||||
- B(Agent tokens) (recommended for CI/CD) are scoped to specific vaults,
|
||||
carry an expiration date, and produce an encrypted audit log — create one
|
||||
with C(pass-cli agent create <NAME> --expiration 1m --vault <VAULT>), then
|
||||
supply the token via O(pat) / E(ANSIBLE_PROTON_PASS_PAT) and set
|
||||
O(agent_reason) / E(ANSIBLE_PROTON_PASS_AGENT_REASON) to a short description
|
||||
of why the automation is accessing the vault.
|
||||
- B(Personal Access Tokens) B(PAT) grant full account access and should be
|
||||
reserved for interactive or development use — generate one in the Proton
|
||||
Pass web app under B(Account > Security > Access and authentication >
|
||||
Personal Access Tokens). PAT format is C(pst_<token>::<key>).
|
||||
- Authenticate once interactively with C(pass-cli login) before running
|
||||
playbooks when neither an agent token nor a PAT is configured.
|
||||
- Set O(debug=true) on the lookup call to display the raw C(pass-cli) JSON via
|
||||
Ansible's warning output — useful for diagnosing field extraction failures
|
||||
across C(pass-cli) versions.
|
||||
- >-
|
||||
All Proton Pass item types are supported: B(Login), B(Note), B(Credit Card),
|
||||
B(Wi-Fi), B(Identity), B(SSH Key), B(Custom), and B(Alias). Standard fields
|
||||
for each type (for example C(username)/C(password) for Login, C(ssid)/C(password)
|
||||
for Wi-Fi, C(private_key)/C(public_key) for SSH Key) are included in the returned
|
||||
dictionary alongside any custom extra fields.
|
||||
- For B(Login) items the C(urls) field is returned as a list of strings.
|
||||
- In Proton Pass, create one item per host. Add every secret as an extra B(hidden)
|
||||
field whose name exactly matches the key your playbooks reference (for example
|
||||
C(api_token), C(gpg_keyphrase)).
|
||||
- Custom sections are supported — fields nested inside a section of a B(Custom),
|
||||
B(SSH Key), B(Wi-Fi), or B(Identity) item are merged into the same flat dict
|
||||
as top-level extra fields.
|
||||
options:
|
||||
_terms:
|
||||
description:
|
||||
- One or more Proton Pass item titles to look up.
|
||||
- If exactly two terms are given and O(field) is not set, the second term
|
||||
is interpreted as a field name and a plain string is returned instead of
|
||||
a dictionary.
|
||||
required: true
|
||||
type: list
|
||||
elements: str
|
||||
field:
|
||||
description:
|
||||
- Field name to retrieve. When set, the lookup returns a plain string
|
||||
instead of a dictionary, equivalent to passing the field as the second
|
||||
positional term.
|
||||
- When both a second positional term and O(field) are supplied, O(field)
|
||||
takes precedence.
|
||||
type: str
|
||||
default: ""
|
||||
vault:
|
||||
description:
|
||||
- Name of the Proton Pass vault to query.
|
||||
- When omitted, C(pass-cli) searches across all vaults accessible to
|
||||
the authenticated account; this may raise an error when the item title
|
||||
is not unique across vaults.
|
||||
type: str
|
||||
default: ""
|
||||
ini:
|
||||
- section: proton_pass_lookup
|
||||
key: vault
|
||||
env:
|
||||
- name: ANSIBLE_PROTON_PASS_VAULT
|
||||
vars:
|
||||
- name: ansible_proton_pass_vault
|
||||
pat:
|
||||
description:
|
||||
- Personal Access Token used for non-interactive authentication.
|
||||
- Format is C(pst_<token>::<key>).
|
||||
- When provided, the plugin runs C(pass-cli login) before the first item
|
||||
lookup if no active session is detected, passing the token through the
|
||||
E(PROTON_PASS_PERSONAL_ACCESS_TOKEN) environment variable.
|
||||
type: str
|
||||
default: ""
|
||||
ini:
|
||||
- section: proton_pass_lookup
|
||||
key: pat
|
||||
env:
|
||||
- name: ANSIBLE_PROTON_PASS_PAT
|
||||
vars:
|
||||
- name: ansible_proton_pass_pat
|
||||
secret: true
|
||||
agent_reason:
|
||||
description:
|
||||
- Human-readable reason string required by Proton Pass when authenticating
|
||||
with an B(agent token) (as opposed to a personal account PAT).
|
||||
- Maps to the C(PROTON_PASS_AGENT_REASON) environment variable consumed by
|
||||
C(pass-cli). Must be between 1 and 300 characters.
|
||||
- Agent tokens are the recommended authentication mechanism for CI/CD
|
||||
pipelines and automated processes — they are scoped to specific vaults,
|
||||
carry an expiration date, and produce an encrypted audit log.
|
||||
Create one with C(pass-cli agent create <NAME> --expiration 1m
|
||||
--vault <VAULT_NAME>).
|
||||
type: str
|
||||
default: ""
|
||||
ini:
|
||||
- section: proton_pass_lookup
|
||||
key: agent_reason
|
||||
env:
|
||||
- name: ANSIBLE_PROTON_PASS_AGENT_REASON
|
||||
vars:
|
||||
- name: ansible_proton_pass_agent_reason
|
||||
cli_path:
|
||||
description:
|
||||
- Path to the C(pass-cli) binary.
|
||||
- When not set, C(pass-cli) is resolved from E(PATH).
|
||||
type: str
|
||||
default: pass-cli
|
||||
ini:
|
||||
- section: proton_pass_lookup
|
||||
key: cli_path
|
||||
env:
|
||||
- name: ANSIBLE_PROTON_PASS_CLI_PATH
|
||||
vars:
|
||||
- name: ansible_proton_pass_cli_path
|
||||
timeout:
|
||||
description:
|
||||
- Timeout in seconds for each C(pass-cli) subprocess invocation.
|
||||
type: int
|
||||
default: 30
|
||||
ini:
|
||||
- section: proton_pass_lookup
|
||||
key: timeout
|
||||
env:
|
||||
- name: ANSIBLE_PROTON_PASS_TIMEOUT
|
||||
vars:
|
||||
- name: ansible_proton_pass_timeout
|
||||
debug:
|
||||
description:
|
||||
- When C(true), displays the raw C(pass-cli) JSON via Ansible's warning output.
|
||||
- Useful for diagnosing field extraction failures across C(pass-cli) versions.
|
||||
- >-
|
||||
B(Note) that this can show sensitive information. Use only when
|
||||
absolutely necessary and ensure the sensitive output is not logged.
|
||||
type: bool
|
||||
default: false
|
||||
"""
|
||||
|
||||
EXAMPLES = r"""
|
||||
# Prerequisites — authenticate once on the control machine:
|
||||
# pass-cli login --pat pst_<token>::<key>
|
||||
# Or export for non-interactive / CI use:
|
||||
# export ANSIBLE_PROTON_PASS_PAT='pst_<token>::<key>'
|
||||
# Or configure ansible.cfg (applies to all lookups in the project):
|
||||
# [proton_pass_lookup]
|
||||
# vault = myproject
|
||||
|
||||
# --- All-fields mode: returns a dict of all extra fields ---
|
||||
|
||||
- name: Load all secrets for the current host
|
||||
ansible.builtin.set_fact:
|
||||
host_secrets: "{{ lookup('community.general.proton_pass', inventory_hostname, vault='myproject') }}"
|
||||
|
||||
- name: Use a field from the loaded dict
|
||||
ansible.builtin.debug:
|
||||
msg: "Token: {{ host_secrets.api_token }}"
|
||||
|
||||
# --- Single-field mode: returns a plain string ---
|
||||
|
||||
- name: Fetch one field via second positional term
|
||||
ansible.builtin.debug:
|
||||
msg: "{{ lookup('community.general.proton_pass', 'my_host', 'api_token', vault='myproject') }}"
|
||||
|
||||
- name: Fetch one field via keyword argument
|
||||
ansible.builtin.debug:
|
||||
msg: "{{ lookup('community.general.proton_pass', 'my_host', field='api_token', vault='myproject') }}"
|
||||
|
||||
# --- Multiple items, same field ---
|
||||
|
||||
- name: Fetch gpg_keyphrase from two items
|
||||
ansible.builtin.debug:
|
||||
msg: "{{ lookup('community.general.proton_pass', 'host_a', 'host_b', field='gpg_keyphrase', vault='myproject') }}"
|
||||
|
||||
# --- Drop-in replacement for ansible-vault secrets ---
|
||||
# Place in group_vars/all/secrets.yaml (plain YAML, safe to commit):
|
||||
#
|
||||
# secrets:
|
||||
# host_a: "{{ lookup('community.general.proton_pass', 'host_a', vault='myproject') }}"
|
||||
# host_b: "{{ lookup('community.general.proton_pass', 'host_b', vault='myproject') }}"
|
||||
#
|
||||
# Existing role tasks continue to work without modification:
|
||||
# "{{ secrets[inventory_hostname].some_secret }}"
|
||||
|
||||
# --- Vault configured globally in ansible.cfg — no vault= kwarg needed ---
|
||||
- name: Lookup when ansible.cfg sets [proton_pass_lookup] vault
|
||||
ansible.builtin.debug:
|
||||
msg: "{{ lookup('community.general.proton_pass', 'my_host', 'api_token') }}"
|
||||
|
||||
# --- Agent token authentication (recommended for CI/CD) ---
|
||||
# Create the agent first (one-time setup):
|
||||
# pass-cli agent create ci-runner --expiration 1m --vault myproject
|
||||
# Then configure ansible.cfg:
|
||||
# [proton_pass_lookup]
|
||||
# vault = myproject
|
||||
# agent_reason = ansible playbook run
|
||||
# And set the token in the environment (or ansible.cfg):
|
||||
# export ANSIBLE_PROTON_PASS_PAT='<agent-token>'
|
||||
- name: Lookup using an agent token
|
||||
ansible.builtin.debug:
|
||||
msg: "{{ lookup('community.general.proton_pass', 'my_host', 'api_token',
|
||||
pat=lookup('env', 'ANSIBLE_PROTON_PASS_PAT'),
|
||||
agent_reason='nightly deployment pipeline') }}"
|
||||
"""
|
||||
|
||||
RETURN = r"""
|
||||
_raw:
|
||||
description:
|
||||
- A list with one element per input term.
|
||||
- In single-field mode (O(field) set or two-term shorthand), each element is
|
||||
the plain-text value of the requested field.
|
||||
- In all-fields mode, each element is a flat dictionary mapping standard
|
||||
item-type fields (C(username)/C(password) for login, C(ssid)/C(password) for
|
||||
wi-fi, C(private_key)/C(public_key) for ssh-key, etc.) and every custom extra
|
||||
field to its string value.
|
||||
type: list
|
||||
elements: raw
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
from subprocess import DEVNULL, PIPE, Popen, TimeoutExpired
|
||||
|
||||
from ansible.errors import AnsibleLookupError, AnsibleOptionsError
|
||||
from ansible.module_utils.common.text.converters import to_text
|
||||
from ansible.module_utils.parsing.convert_bool import boolean
|
||||
from ansible.plugins.lookup import LookupBase
|
||||
from ansible.utils.display import Display
|
||||
|
||||
from ansible_collections.community.general.plugins.plugin_utils._lookup import check_for_wrong_terms
|
||||
|
||||
display = Display()
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Item-type field registries — mirrors pass-cli item create <type> --get-template
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
_LOGIN_FIELDS = ("username", "email", "password", "totp_uri")
|
||||
_CREDIT_CARD_FIELDS = ("cardholder_name", "card_type", "number", "verification_number", "expiration_date", "pin")
|
||||
_WIFI_FIELDS = ("ssid", "password", "security")
|
||||
_SSH_KEY_FIELDS = ("private_key", "public_key", "fingerprint", "key_type")
|
||||
_IDENTITY_FIELDS = (
|
||||
"full_name",
|
||||
"email",
|
||||
"phone_number",
|
||||
"first_name",
|
||||
"middle_name",
|
||||
"last_name",
|
||||
"birthdate",
|
||||
"gender",
|
||||
"organization",
|
||||
"street_address",
|
||||
"zip_or_postal_code",
|
||||
"city",
|
||||
"state_or_province",
|
||||
"country_or_region",
|
||||
"floor",
|
||||
"county",
|
||||
"social_security_number",
|
||||
"passport_number",
|
||||
"license_number",
|
||||
"website",
|
||||
"x_handle",
|
||||
"second_phone_number",
|
||||
"linkedin",
|
||||
"reddit",
|
||||
"facebook",
|
||||
"yahoo",
|
||||
"instagram",
|
||||
"company",
|
||||
"job_title",
|
||||
"personal_website",
|
||||
"work_phone_number",
|
||||
"work_email",
|
||||
)
|
||||
|
||||
|
||||
class ProtonPassCLIError(AnsibleLookupError):
|
||||
"""Raised when the pass-cli subprocess fails in an unexpected way."""
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# CLI wrapper
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class ProtonPassClient:
|
||||
"""Thin wrapper around the pass-cli binary."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
cli_path: str,
|
||||
timeout: int,
|
||||
agent_reason: str,
|
||||
debug: bool = False,
|
||||
) -> None:
|
||||
self.cli_path = cli_path
|
||||
self.timeout = timeout
|
||||
self.agent_reason = agent_reason
|
||||
self.debug = debug
|
||||
self._session_ok = False
|
||||
|
||||
def _run(self, args: list[str], extra_env: dict[str, str] | None = None) -> tuple[int, str, str]:
|
||||
"""Run pass-cli with ``args`` and return (returncode, stdout, stderr).
|
||||
|
||||
When ``agent_reason`` is set, PROTON_PASS_AGENT_REASON is injected into
|
||||
the subprocess environment so that pass-cli records the reason in its
|
||||
encrypted audit log.
|
||||
|
||||
``extra_env`` is merged into the subprocess environment. Use it for
|
||||
secrets, which must never be passed in *args*.
|
||||
|
||||
Raises:
|
||||
ProtonPassCLIError: if the binary is not found or the call times out.
|
||||
"""
|
||||
command = [self.cli_path] + args
|
||||
display.vvv(f"proton_pass: running {command}")
|
||||
|
||||
env = os.environ.copy()
|
||||
if self.agent_reason:
|
||||
env["PROTON_PASS_AGENT_REASON"] = self.agent_reason
|
||||
if extra_env:
|
||||
env.update(extra_env)
|
||||
|
||||
try:
|
||||
proc = Popen(command, stdin=DEVNULL, stdout=PIPE, stderr=PIPE, env=env)
|
||||
out_bytes, err_bytes = proc.communicate(timeout=self.timeout)
|
||||
rc = proc.returncode
|
||||
except FileNotFoundError as e:
|
||||
raise ProtonPassCLIError(
|
||||
f"'{self.cli_path}' not found — install pass-cli or set "
|
||||
"ANSIBLE_PROTON_PASS_CLI_PATH / [proton_pass_lookup] cli_path "
|
||||
"in ansible.cfg"
|
||||
) from e
|
||||
except TimeoutExpired as e:
|
||||
proc.kill()
|
||||
raise ProtonPassCLIError(f"pass-cli timed out after {self.timeout}s") from e
|
||||
|
||||
return (
|
||||
rc,
|
||||
to_text(out_bytes, errors="surrogate_or_strict"),
|
||||
to_text(err_bytes, errors="surrogate_or_strict"),
|
||||
)
|
||||
|
||||
# --- authentication ----------------------------------------------------------
|
||||
|
||||
def test_session(self) -> bool:
|
||||
"""Return True when an active pass-cli session exists."""
|
||||
rc, *_ignored = self._run(["info"])
|
||||
return rc == 0
|
||||
|
||||
def login_with_pat(self, pat: str) -> None:
|
||||
"""Authenticate using a Personal Access Token (``pst_<token>::<key>``)."""
|
||||
# Passed via the environment so the token stays out of the process list and error messages.
|
||||
extra_env = {"PROTON_PASS_PERSONAL_ACCESS_TOKEN": pat} if pat else None
|
||||
rc, _out, err = self._run(["login"], extra_env=extra_env)
|
||||
if rc != 0:
|
||||
raise AnsibleLookupError(
|
||||
f"pass-cli login failed: {err.strip()} — verify the PAT format is pst_<token>::<key>"
|
||||
)
|
||||
|
||||
def ensure_authenticated(self, pat: str) -> None:
|
||||
"""Ensure there is an active session, logging in with PAT if necessary."""
|
||||
if self._session_ok:
|
||||
return
|
||||
if self.test_session():
|
||||
self._session_ok = True
|
||||
return
|
||||
if not pat:
|
||||
raise AnsibleLookupError(
|
||||
"No active pass-cli session and no PAT supplied. "
|
||||
"Run 'pass-cli login' on the control machine, or set "
|
||||
"ANSIBLE_PROTON_PASS_PAT."
|
||||
)
|
||||
self.login_with_pat(pat)
|
||||
self._session_ok = True
|
||||
|
||||
# --- single-field retrieval --------------------------------------------------
|
||||
|
||||
def fetch_all_fields(self, vault: str, title: str) -> dict[str, str | list[str]]:
|
||||
"""Return all fields for *title* as a flat ``{field_name: value}`` dict.
|
||||
|
||||
Always calls pass-cli — no caching, so callers always receive the
|
||||
current vault state.
|
||||
"""
|
||||
args = ["item", "view", "--item-title", title, "--output", "json"]
|
||||
if vault:
|
||||
args += ["--vault-name", vault]
|
||||
|
||||
rc, out, err = self._run(args)
|
||||
if rc != 0:
|
||||
_raise_item_error(title, vault, None, err)
|
||||
|
||||
if self.debug:
|
||||
display.warning(f"proton_pass DEBUG — raw JSON for '{title}':\n{out}")
|
||||
|
||||
try:
|
||||
raw = json.loads(out)
|
||||
except json.JSONDecodeError as e:
|
||||
raise AnsibleLookupError(
|
||||
f"pass-cli returned invalid JSON for item '{title}': {e}. "
|
||||
"Set the lookup option debug=true to inspect the raw output."
|
||||
) from e
|
||||
|
||||
return _parse_fields(raw, title)
|
||||
|
||||
def fetch_field(self, vault: str, title: str, field: str) -> str:
|
||||
"""Return a single field value for *title*.
|
||||
|
||||
Delegates to ``fetch_all_fields`` so that trashed-item detection,
|
||||
JSON parsing, and error messages are consistent regardless of whether
|
||||
the caller requests one field or all fields.
|
||||
"""
|
||||
all_fields = self.fetch_all_fields(vault=vault, title=title)
|
||||
if field not in all_fields:
|
||||
vault_hint = f" in vault '{vault}'" if vault else ""
|
||||
raise AnsibleLookupError(
|
||||
f"proton_pass: field '{field}' not found in item '{title}'{vault_hint}. "
|
||||
f"Available fields: {', '.join(sorted(all_fields)) or '(none)'}"
|
||||
)
|
||||
value = all_fields[field]
|
||||
return value if isinstance(value, str) else ", ".join(value)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Error helper
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _raise_item_error(title: str, vault: str, field: str | None, stderr: str) -> None:
|
||||
"""Translate pass-cli stderr into a descriptive AnsibleLookupError."""
|
||||
msg = stderr.strip()
|
||||
msg_lower = msg.lower()
|
||||
vault_hint = f" in vault '{vault}'" if vault else ""
|
||||
field_hint = f", field '{field}'" if field else ""
|
||||
|
||||
if "not found" in msg_lower or "no items found" in msg_lower:
|
||||
error_msg = (
|
||||
f"Item '{title}'{vault_hint} not found in Proton Pass{field_hint}. Verify the item title and vault name."
|
||||
)
|
||||
elif "unauthorized" in msg_lower or "unauthenticated" in msg_lower:
|
||||
error_msg = f"pass-cli authentication error: {msg}. Re-run 'pass-cli login' or refresh your PAT."
|
||||
else:
|
||||
error_msg = f"pass-cli failed for item '{title}'{vault_hint}{field_hint}: {msg}"
|
||||
raise AnsibleLookupError(error_msg)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# JSON parser
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _extract_scalar_fields(source: dict, keys: tuple) -> dict[str, str]:
|
||||
"""Return a dict of *keys* from *source*, skipping None and empty-string values."""
|
||||
return {key: str(val) for key in keys if (val := source.get(key)) is not None and val != ""}
|
||||
|
||||
|
||||
def _extract_typed_fields(type_key: str, type_data: dict) -> dict[str, str | list[str]]:
|
||||
"""Return type-specific standard fields extracted from *type_data*."""
|
||||
fields: dict[str, str | list[str]] = {}
|
||||
tk = type_key.lower()
|
||||
if tk == "login":
|
||||
fields.update(_extract_scalar_fields(type_data, _LOGIN_FIELDS))
|
||||
urls = type_data.get("urls")
|
||||
if urls:
|
||||
fields["urls"] = urls if isinstance(urls, list) else [urls]
|
||||
elif tk == "creditcard":
|
||||
fields.update(_extract_scalar_fields(type_data, _CREDIT_CARD_FIELDS))
|
||||
elif tk == "wifi":
|
||||
fields.update(_extract_scalar_fields(type_data, _WIFI_FIELDS))
|
||||
fields.update(_extract_section_fields(type_data.get("sections", [])))
|
||||
elif tk == "sshkey":
|
||||
fields.update(_extract_scalar_fields(type_data, _SSH_KEY_FIELDS))
|
||||
fields.update(_extract_section_fields(type_data.get("sections", [])))
|
||||
elif tk == "custom":
|
||||
fields.update(_extract_section_fields(type_data.get("sections", [])))
|
||||
elif tk == "identity":
|
||||
fields.update(_extract_scalar_fields(type_data, _IDENTITY_FIELDS))
|
||||
for sub_key in (
|
||||
"extra_personal_details",
|
||||
"extra_address_details",
|
||||
"extra_contact_details",
|
||||
"extra_work_details",
|
||||
):
|
||||
fields.update(_extract_extra_fields(type_data.get(sub_key, [])))
|
||||
fields.update(_extract_section_fields(type_data.get("extra_sections", [])))
|
||||
elif tk == "alias":
|
||||
for alias_key in ("aliased_email", "aliased_address"):
|
||||
val = type_data.get(alias_key)
|
||||
if val:
|
||||
fields["aliased_email"] = val
|
||||
break
|
||||
return fields
|
||||
|
||||
|
||||
def _parse_fields(raw: dict, title: str) -> dict[str, str | list[str]]:
|
||||
"""Extract a flat ``{field_name: value}`` dict from a pass-cli JSON response."""
|
||||
fields: dict[str, str | list[str]] = {}
|
||||
|
||||
item_obj = raw.get("item", raw)
|
||||
state = item_obj.get("state", "")
|
||||
if state.lower() == "trashed":
|
||||
raise AnsibleLookupError(
|
||||
f"proton_pass: item '{title}' is in the Proton Pass trash and cannot be "
|
||||
"used. Restore it or permanently delete it."
|
||||
)
|
||||
|
||||
content_wrapper = item_obj.get("content", {})
|
||||
note = content_wrapper.get("note")
|
||||
if note:
|
||||
fields["note"] = str(note)
|
||||
|
||||
type_dict = content_wrapper.get("content")
|
||||
if isinstance(type_dict, dict):
|
||||
for type_key, type_data in type_dict.items():
|
||||
if isinstance(type_data, dict):
|
||||
fields.update(_extract_typed_fields(type_key, type_data))
|
||||
|
||||
fields.update(_extract_extra_fields(content_wrapper.get("extra_fields", [])))
|
||||
for section in content_wrapper.get("extra_sections", []):
|
||||
fields.update(_extract_extra_fields(section.get("extra_fields", [])))
|
||||
|
||||
if not fields:
|
||||
raise AnsibleLookupError(
|
||||
f"proton_pass: no fields extracted from item '{title}'. "
|
||||
"Ensure the item has a note, standard fields, or at least one extra "
|
||||
"hidden field. Set the lookup option debug=true to inspect the raw JSON."
|
||||
)
|
||||
|
||||
return fields
|
||||
|
||||
|
||||
def _extract_extra_fields(extra_fields: list[dict]) -> dict[str, str]:
|
||||
"""Return a flat ``{field_name: value}`` dict from a pass-cli extra_fields list.
|
||||
|
||||
Each entry has the shape::
|
||||
|
||||
{"name": "key", "content": {"Hidden"|"Text"|"Totp"|"Timestamp": value}}
|
||||
|
||||
The type wrapper key varies; the actual value is always the first dict value.
|
||||
Non-string values (for example ``Timestamp`` integers) are converted to strings.
|
||||
"""
|
||||
result: dict[str, str] = {}
|
||||
for extra in extra_fields:
|
||||
name = extra.get("name", "")
|
||||
if not name:
|
||||
continue
|
||||
content = extra.get("content")
|
||||
if isinstance(content, dict):
|
||||
raw_value = next((v for v in content.values() if v is not None), "")
|
||||
result[name] = str(raw_value)
|
||||
return result
|
||||
|
||||
|
||||
def _extract_section_fields(sections: list[dict]) -> dict[str, str]:
|
||||
result: dict[str, str] = {}
|
||||
for section in sections:
|
||||
result.update(_extract_extra_fields(section.get("section_fields", [])))
|
||||
return result
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Lookup module
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class LookupModule(LookupBase):
|
||||
def run(self, terms: list[str], variables: dict | None = None, **kwargs) -> list:
|
||||
self.set_options(var_options=variables, direct=kwargs)
|
||||
check_for_wrong_terms(self, direct=kwargs)
|
||||
vault = self.get_option("vault") or ""
|
||||
pat = self.get_option("pat") or ""
|
||||
agent_reason = self.get_option("agent_reason") or ""
|
||||
cli_path = self.get_option("cli_path") or "pass-cli"
|
||||
timeout = int(self.get_option("timeout"))
|
||||
debug = boolean(self.get_option("debug"))
|
||||
field_opt = self.get_option("field") or ""
|
||||
|
||||
if not terms:
|
||||
raise AnsibleLookupError(
|
||||
"community.general.proton_pass requires at least one positional argument (item title)"
|
||||
)
|
||||
|
||||
# Two-term shorthand: lookup('proton_pass', 'item_title', 'field_name')
|
||||
if len(terms) == 2:
|
||||
item_titles = [terms[0]]
|
||||
field = field_opt or terms[1]
|
||||
else:
|
||||
item_titles = list(terms)
|
||||
field = field_opt
|
||||
|
||||
if len(item_titles) > 1 and not field:
|
||||
raise AnsibleOptionsError(
|
||||
"community.general.proton_pass: fetching all fields for multiple "
|
||||
"items in one call is not supported. Specify 'field' or look up "
|
||||
"one item at a time."
|
||||
)
|
||||
|
||||
client = ProtonPassClient(cli_path=cli_path, timeout=timeout, agent_reason=agent_reason, debug=debug)
|
||||
client.ensure_authenticated(pat)
|
||||
|
||||
results: list[str | dict[str, str | list[str]]] = []
|
||||
for title in item_titles:
|
||||
if field:
|
||||
results.append(client.fetch_field(vault=vault, title=title, field=field))
|
||||
else:
|
||||
results.append(client.fetch_all_fields(vault=vault, title=title))
|
||||
|
||||
return results
|
||||
+97
@@ -0,0 +1,97 @@
|
||||
# Copyright (c) 2021, Abhijeet Kasurde <akasurde@redhat.com>
|
||||
# Copyright (c) 2018, Ansible Project
|
||||
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
DOCUMENTATION = r"""
|
||||
name: random_pet
|
||||
author:
|
||||
- Abhijeet Kasurde (@Akasurde)
|
||||
short_description: Generates random pet names
|
||||
version_added: '3.1.0'
|
||||
requirements:
|
||||
- petname U(https://github.com/dustinkirkland/python-petname)
|
||||
description:
|
||||
- Generates random pet names that can be used as unique identifiers for the resources.
|
||||
options:
|
||||
words:
|
||||
description:
|
||||
- The number of words in the pet name.
|
||||
default: 2
|
||||
type: int
|
||||
length:
|
||||
description:
|
||||
- The maximal length of every component of the pet name.
|
||||
- Values below V(3) are set to V(3) by petname.
|
||||
default: 6
|
||||
type: int
|
||||
prefix:
|
||||
description: A string to prefix with the name.
|
||||
type: str
|
||||
separator:
|
||||
description: The character to separate words in the pet name.
|
||||
default: "-"
|
||||
type: str
|
||||
"""
|
||||
|
||||
EXAMPLES = r"""
|
||||
- name: Generate pet name
|
||||
ansible.builtin.debug:
|
||||
var: lookup('community.general.random_pet')
|
||||
# Example result: 'loving-raptor'
|
||||
|
||||
- name: Generate pet name with 3 words
|
||||
ansible.builtin.debug:
|
||||
var: lookup('community.general.random_pet', words=3)
|
||||
# Example result: 'fully-fresh-macaw'
|
||||
|
||||
- name: Generate pet name with separator
|
||||
ansible.builtin.debug:
|
||||
var: lookup('community.general.random_pet', separator="_")
|
||||
# Example result: 'causal_snipe'
|
||||
|
||||
- name: Generate pet name with length
|
||||
ansible.builtin.debug:
|
||||
var: lookup('community.general.random_pet', length=7)
|
||||
# Example result: 'natural-peacock'
|
||||
"""
|
||||
|
||||
RETURN = r"""
|
||||
_raw:
|
||||
description: A one-element list containing a random pet name.
|
||||
type: list
|
||||
elements: str
|
||||
"""
|
||||
|
||||
try:
|
||||
import petname
|
||||
|
||||
HAS_PETNAME = True
|
||||
except ImportError:
|
||||
HAS_PETNAME = False
|
||||
|
||||
from ansible.errors import AnsibleError
|
||||
from ansible.plugins.lookup import LookupBase
|
||||
|
||||
from ansible_collections.community.general.plugins.plugin_utils._lookup import check_for_no_terms
|
||||
|
||||
|
||||
class LookupModule(LookupBase):
|
||||
def run(self, terms, variables=None, **kwargs):
|
||||
if not HAS_PETNAME:
|
||||
raise AnsibleError('Python petname library is required. Please install using "pip install petname"')
|
||||
|
||||
self.set_options(var_options=variables, direct=kwargs)
|
||||
check_for_no_terms(self, terms=terms, direct=kwargs)
|
||||
words = self.get_option("words")
|
||||
length = self.get_option("length")
|
||||
prefix = self.get_option("prefix")
|
||||
separator = self.get_option("separator")
|
||||
|
||||
values = petname.Generate(words=words, separator=separator, letters=length)
|
||||
if prefix:
|
||||
values = f"{prefix}{separator}{values}"
|
||||
|
||||
return [values]
|
||||
+265
@@ -0,0 +1,265 @@
|
||||
# Copyright (c) 2021, Abhijeet Kasurde <akasurde@redhat.com>
|
||||
# Copyright (c) 2018, Ansible Project
|
||||
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
DOCUMENTATION = r"""
|
||||
name: random_string
|
||||
author:
|
||||
- Abhijeet Kasurde (@Akasurde)
|
||||
short_description: Generates random string
|
||||
version_added: '3.2.0'
|
||||
description:
|
||||
- Generates random string based upon the given constraints.
|
||||
- Uses L(secrets.SystemRandom,https://docs.python.org/3/library/secrets.html#secrets.SystemRandom), so should be strong enough
|
||||
for cryptographic purposes.
|
||||
options:
|
||||
length:
|
||||
description: The length of the string.
|
||||
default: 8
|
||||
type: int
|
||||
upper:
|
||||
description:
|
||||
- Possibly include uppercase letters in the string.
|
||||
- To ensure atleast one uppercase letter, set O(min_upper) to V(1).
|
||||
default: true
|
||||
type: bool
|
||||
lower:
|
||||
description:
|
||||
- Possibly include lowercase letters in the string.
|
||||
- To ensure atleast one lowercase letter, set O(min_lower) to V(1).
|
||||
default: true
|
||||
type: bool
|
||||
numbers:
|
||||
description:
|
||||
- Possibly include numbers in the string.
|
||||
- To ensure atleast one numeric character, set O(min_numeric) to V(1).
|
||||
default: true
|
||||
type: bool
|
||||
special:
|
||||
description:
|
||||
- Possibly include special characters in the string.
|
||||
- Special characters are taken from Python standard library C(string). See L(the documentation of
|
||||
string.punctuation,https://docs.python.org/3/library/string.html#string.punctuation)
|
||||
for which characters are used.
|
||||
- The choice of special characters can be changed to setting O(override_special).
|
||||
- To ensure atleast one special character, set O(min_special) to V(1).
|
||||
default: true
|
||||
type: bool
|
||||
min_numeric:
|
||||
description:
|
||||
- Minimum number of numeric characters in the string.
|
||||
- If set, overrides O(numbers=false).
|
||||
default: 0
|
||||
type: int
|
||||
min_upper:
|
||||
description:
|
||||
- Minimum number of uppercase alphabets in the string.
|
||||
- If set, overrides O(upper=false).
|
||||
default: 0
|
||||
type: int
|
||||
min_lower:
|
||||
description:
|
||||
- Minimum number of lowercase alphabets in the string.
|
||||
- If set, overrides O(lower=false).
|
||||
default: 0
|
||||
type: int
|
||||
min_special:
|
||||
description:
|
||||
- Minimum number of special character in the string.
|
||||
default: 0
|
||||
type: int
|
||||
override_special:
|
||||
description:
|
||||
- Override a list of special characters to use in the string.
|
||||
- If set O(min_special) should be set to a non-default value.
|
||||
type: str
|
||||
override_all:
|
||||
description:
|
||||
- Override all values of O(numbers), O(upper), O(lower), and O(special) with the given list of characters.
|
||||
type: str
|
||||
ignore_similar_chars:
|
||||
description:
|
||||
- Ignore similar characters, such as V(l) and V(1), or V(O) and V(0).
|
||||
- These characters can be configured in O(similar_chars).
|
||||
default: false
|
||||
type: bool
|
||||
version_added: 7.5.0
|
||||
similar_chars:
|
||||
description:
|
||||
- Override a list of characters not to be use in the string.
|
||||
default: "il1LoO0"
|
||||
type: str
|
||||
version_added: 7.5.0
|
||||
base64:
|
||||
description:
|
||||
- Returns base64 encoded string.
|
||||
type: bool
|
||||
default: false
|
||||
seed:
|
||||
description:
|
||||
- Seed for random string generator.
|
||||
- B(Note) that this drastically reduces the security of this plugin. First, when O(seed) is provided, a non-cryptographic random number generator is used.
|
||||
Second, if the seed does not contain enough entropy, the generated string is weak.
|
||||
B(Do not use the generated string as a password or a secure token when using this option!)
|
||||
type: str
|
||||
version_added: 11.3.0
|
||||
"""
|
||||
|
||||
EXAMPLES = r"""
|
||||
- name: Generate random string
|
||||
ansible.builtin.debug:
|
||||
var: lookup('community.general.random_string')
|
||||
# Example result: 'DeadBeeF'
|
||||
|
||||
- name: Generate random string with seed
|
||||
ansible.builtin.debug:
|
||||
var: lookup('community.general.random_string', seed=12345)
|
||||
# Example result: '6[~(2q5O'
|
||||
# NOTE: Do **not** use this string as a password or a secure token,
|
||||
# unless you know exactly what you are doing!
|
||||
# Specifying seed uses a non-secure random number generator.
|
||||
|
||||
- name: Generate random string with length 12
|
||||
ansible.builtin.debug:
|
||||
var: lookup('community.general.random_string', length=12)
|
||||
# Example result: 'Uan0hUiX5kVG'
|
||||
|
||||
- name: Generate base64 encoded random string
|
||||
ansible.builtin.debug:
|
||||
var: lookup('community.general.random_string', base64=True)
|
||||
# Example result: 'NHZ6eWN5Qk0='
|
||||
|
||||
- name: Generate a random string with 1 lower, 1 upper, 1 number and 1 special char (at least)
|
||||
ansible.builtin.debug:
|
||||
var: lookup('community.general.random_string', min_lower=1, min_upper=1, min_special=1, min_numeric=1)
|
||||
# Example result: '&Qw2|E[-'
|
||||
|
||||
- name: Generate a random string with all lower case characters
|
||||
ansible.builtin.debug:
|
||||
var: query('community.general.random_string', upper=false, numbers=false, special=false)
|
||||
# Example result: ['exolxzyz']
|
||||
|
||||
- name: Generate random hexadecimal string
|
||||
ansible.builtin.debug:
|
||||
var: query('community.general.random_string', upper=false, lower=false, override_special=hex_chars, numbers=false)
|
||||
vars:
|
||||
hex_chars: '0123456789ABCDEF'
|
||||
# Example result: ['D2A40737']
|
||||
|
||||
- name: Generate random hexadecimal string with override_all
|
||||
ansible.builtin.debug:
|
||||
var: query('community.general.random_string', override_all=hex_chars)
|
||||
vars:
|
||||
hex_chars: '0123456789ABCDEF'
|
||||
# Example result: ['D2A40737']
|
||||
"""
|
||||
|
||||
RETURN = r"""
|
||||
_raw:
|
||||
description: A one-element list containing a random string.
|
||||
type: list
|
||||
elements: str
|
||||
"""
|
||||
|
||||
import base64
|
||||
import random
|
||||
import secrets
|
||||
import string
|
||||
|
||||
from ansible.errors import AnsibleLookupError
|
||||
from ansible.module_utils.common.text.converters import to_bytes, to_text
|
||||
from ansible.plugins.lookup import LookupBase
|
||||
|
||||
from ansible_collections.community.general.plugins.plugin_utils._lookup import check_for_no_terms
|
||||
|
||||
|
||||
class LookupModule(LookupBase):
|
||||
@staticmethod
|
||||
def get_random(random_generator, chars, length):
|
||||
if not chars:
|
||||
raise AnsibleLookupError("Available characters cannot be None, please change constraints")
|
||||
return "".join(random_generator.choice(chars) for dummy in range(length))
|
||||
|
||||
@staticmethod
|
||||
def b64encode(string_value, encoding="utf-8"):
|
||||
return to_text(base64.b64encode(to_bytes(string_value, encoding=encoding, errors="surrogate_or_strict")))
|
||||
|
||||
def run(self, terms, variables=None, **kwargs):
|
||||
number_chars = string.digits
|
||||
lower_chars = string.ascii_lowercase
|
||||
upper_chars = string.ascii_uppercase
|
||||
special_chars = string.punctuation
|
||||
|
||||
self.set_options(var_options=variables, direct=kwargs)
|
||||
check_for_no_terms(self, terms=terms, direct=kwargs)
|
||||
|
||||
length = self.get_option("length")
|
||||
base64_flag = self.get_option("base64")
|
||||
override_all = self.get_option("override_all")
|
||||
ignore_similar_chars = self.get_option("ignore_similar_chars")
|
||||
similar_chars = self.get_option("similar_chars")
|
||||
seed = self.get_option("seed")
|
||||
|
||||
if seed is None:
|
||||
random_generator = secrets.SystemRandom()
|
||||
else:
|
||||
random_generator = random.Random(seed)
|
||||
|
||||
values = ""
|
||||
available_chars_set = ""
|
||||
|
||||
if ignore_similar_chars:
|
||||
number_chars = "".join([sc for sc in number_chars if sc not in similar_chars])
|
||||
lower_chars = "".join([sc for sc in lower_chars if sc not in similar_chars])
|
||||
upper_chars = "".join([sc for sc in upper_chars if sc not in similar_chars])
|
||||
special_chars = "".join([sc for sc in special_chars if sc not in similar_chars])
|
||||
|
||||
if override_all:
|
||||
# Override all the values
|
||||
available_chars_set = override_all
|
||||
else:
|
||||
upper = self.get_option("upper")
|
||||
lower = self.get_option("lower")
|
||||
numbers = self.get_option("numbers")
|
||||
special = self.get_option("special")
|
||||
override_special = self.get_option("override_special")
|
||||
|
||||
if override_special:
|
||||
special_chars = override_special
|
||||
|
||||
if upper:
|
||||
available_chars_set += upper_chars
|
||||
if lower:
|
||||
available_chars_set += lower_chars
|
||||
if numbers:
|
||||
available_chars_set += number_chars
|
||||
if special:
|
||||
available_chars_set += special_chars
|
||||
|
||||
mapping = {
|
||||
"min_numeric": number_chars,
|
||||
"min_lower": lower_chars,
|
||||
"min_upper": upper_chars,
|
||||
"min_special": special_chars,
|
||||
}
|
||||
|
||||
for m in mapping:
|
||||
if self.get_option(m):
|
||||
values += self.get_random(random_generator, mapping[m], self.get_option(m))
|
||||
|
||||
remaining_pass_len = length - len(values)
|
||||
values += self.get_random(random_generator, available_chars_set, remaining_pass_len)
|
||||
|
||||
shuffled_values = list(values)
|
||||
if seed is None:
|
||||
# Get pseudo randomization
|
||||
# Randomize the order
|
||||
random.shuffle(shuffled_values)
|
||||
|
||||
if base64_flag:
|
||||
return [self.b64encode("".join(shuffled_values))]
|
||||
|
||||
return ["".join(shuffled_values)]
|
||||
+112
@@ -0,0 +1,112 @@
|
||||
# Copyright (c) Ansible project
|
||||
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
"""The community.general.random_words Ansible lookup plugin."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
DOCUMENTATION = r"""
|
||||
name: random_words
|
||||
author:
|
||||
- Thomas Sjögren (@konstruktoid)
|
||||
short_description: Return a number of random words
|
||||
version_added: "4.0.0"
|
||||
requirements:
|
||||
- xkcdpass U(https://github.com/redacted/XKCD-password-generator)
|
||||
description:
|
||||
- Returns a number of random words. The output can for example be used for passwords.
|
||||
- See U(https://xkcd.com/936/) for background.
|
||||
options:
|
||||
numwords:
|
||||
description:
|
||||
- The number of words.
|
||||
default: 6
|
||||
type: int
|
||||
min_length:
|
||||
description:
|
||||
- Minimum length of words to make password.
|
||||
default: 5
|
||||
type: int
|
||||
max_length:
|
||||
description:
|
||||
- Maximum length of words to make password.
|
||||
default: 9
|
||||
type: int
|
||||
delimiter:
|
||||
description:
|
||||
- The delimiter character between words.
|
||||
default: " "
|
||||
type: str
|
||||
case:
|
||||
description:
|
||||
- The method for setting the case of each word in the passphrase.
|
||||
choices: ["alternating", "upper", "lower", "random", "capitalize"]
|
||||
default: "lower"
|
||||
type: str
|
||||
"""
|
||||
|
||||
EXAMPLES = r"""
|
||||
- name: Generate password with default settings
|
||||
ansible.builtin.debug:
|
||||
var: lookup('community.general.random_words')
|
||||
# Example result: 'traitor gigabyte cesarean unless aspect clear'
|
||||
|
||||
- name: Generate password with six, five character, words
|
||||
ansible.builtin.debug:
|
||||
var: lookup('community.general.random_words', min_length=5, max_length=5)
|
||||
# Example result: 'brink banjo getup staff trump comfy'
|
||||
|
||||
- name: Generate password with three capitalized words and the '-' delimiter
|
||||
ansible.builtin.debug:
|
||||
var: lookup('community.general.random_words', numwords=3, delimiter='-', case='capitalize')
|
||||
# Example result: 'Overlabor-Faucet-Coastline'
|
||||
|
||||
- name: Generate password with three words without any delimiter
|
||||
ansible.builtin.debug:
|
||||
var: lookup('community.general.random_words', numwords=3, delimiter='')
|
||||
# Example result: 'deskworkmonopolystriking'
|
||||
# https://www.ncsc.gov.uk/blog-post/the-logic-behind-three-random-words
|
||||
"""
|
||||
|
||||
RETURN = r"""
|
||||
_raw:
|
||||
description: A single-element list containing random words.
|
||||
type: list
|
||||
elements: str
|
||||
"""
|
||||
|
||||
from ansible.errors import AnsibleLookupError
|
||||
from ansible.plugins.lookup import LookupBase
|
||||
|
||||
from ansible_collections.community.general.plugins.plugin_utils._lookup import check_for_no_terms
|
||||
|
||||
try:
|
||||
from xkcdpass import xkcd_password as xp
|
||||
|
||||
HAS_XKCDPASS = True
|
||||
except ImportError:
|
||||
HAS_XKCDPASS = False
|
||||
|
||||
|
||||
class LookupModule(LookupBase):
|
||||
"""The random_words Ansible lookup class."""
|
||||
|
||||
def run(self, terms, variables=None, **kwargs):
|
||||
if not HAS_XKCDPASS:
|
||||
raise AnsibleLookupError('Python xkcdpass library is required. Please install using "pip install xkcdpass"')
|
||||
|
||||
self.set_options(var_options=variables, direct=kwargs)
|
||||
check_for_no_terms(self, terms=terms, direct=kwargs)
|
||||
method = self.get_option("case")
|
||||
delimiter = self.get_option("delimiter")
|
||||
max_length = self.get_option("max_length")
|
||||
min_length = self.get_option("min_length")
|
||||
numwords = self.get_option("numwords")
|
||||
|
||||
words = xp.locate_wordfile()
|
||||
wordlist = xp.generate_wordlist(max_length=max_length, min_length=min_length, wordfile=words)
|
||||
|
||||
values = xp.generate_xkcdpassword(wordlist, case=method, delimiter=delimiter, numwords=numwords)
|
||||
|
||||
return [values]
|
||||
@@ -0,0 +1,119 @@
|
||||
# Copyright (c) 2012, Jan-Piet Mens <jpmens(at)gmail.com>
|
||||
# Copyright (c) 2017 Ansible Project
|
||||
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
from __future__ import annotations
|
||||
|
||||
DOCUMENTATION = r"""
|
||||
name: redis
|
||||
author:
|
||||
- Jan-Piet Mens (@jpmens) <jpmens(at)gmail.com>
|
||||
- Ansible Core Team
|
||||
short_description: Fetch data from Redis
|
||||
description:
|
||||
- This lookup returns a list of results from a Redis DB corresponding to a list of items given to it.
|
||||
requirements:
|
||||
- redis (python library https://github.com/andymccurdy/redis-py/)
|
||||
options:
|
||||
_terms:
|
||||
description: List of keys to query.
|
||||
type: list
|
||||
elements: string
|
||||
host:
|
||||
description: Location of Redis host.
|
||||
type: string
|
||||
default: '127.0.0.1'
|
||||
env:
|
||||
- name: ANSIBLE_REDIS_HOST
|
||||
ini:
|
||||
- section: lookup_redis
|
||||
key: host
|
||||
port:
|
||||
description: Port on which Redis is listening on.
|
||||
default: 6379
|
||||
type: int
|
||||
env:
|
||||
- name: ANSIBLE_REDIS_PORT
|
||||
ini:
|
||||
- section: lookup_redis
|
||||
key: port
|
||||
socket:
|
||||
description: Path to socket on which to query Redis, this option overrides host and port options when set.
|
||||
type: path
|
||||
env:
|
||||
- name: ANSIBLE_REDIS_SOCKET
|
||||
ini:
|
||||
- section: lookup_redis
|
||||
key: socket
|
||||
"""
|
||||
|
||||
EXAMPLES = r"""
|
||||
- name: query redis for somekey (default or configured settings used)
|
||||
ansible.builtin.debug:
|
||||
msg: "{{ lookup('community.general.redis', 'somekey') }}"
|
||||
|
||||
- name: query redis for list of keys and non-default host and port
|
||||
ansible.builtin.debug:
|
||||
msg: "{{ lookup('community.general.redis', item, host='myredis.internal.com', port=2121) }}"
|
||||
loop: '{{list_of_redis_keys}}'
|
||||
|
||||
- name: use list directly
|
||||
ansible.builtin.debug:
|
||||
msg: "{{ lookup('community.general.redis', 'key1', 'key2', 'key3') }}"
|
||||
|
||||
- name: use list directly with a socket
|
||||
ansible.builtin.debug:
|
||||
msg: "{{ lookup('community.general.redis', 'key1', 'key2', socket='/var/tmp/redis.sock') }}"
|
||||
"""
|
||||
|
||||
RETURN = r"""
|
||||
_raw:
|
||||
description: Value(s) stored in Redis.
|
||||
type: list
|
||||
elements: str
|
||||
"""
|
||||
|
||||
HAVE_REDIS = False
|
||||
try:
|
||||
import redis
|
||||
|
||||
HAVE_REDIS = True
|
||||
except ImportError:
|
||||
pass
|
||||
|
||||
from ansible.errors import AnsibleError
|
||||
from ansible.module_utils.common.text.converters import to_text
|
||||
from ansible.plugins.lookup import LookupBase
|
||||
|
||||
from ansible_collections.community.general.plugins.plugin_utils._lookup import check_for_wrong_terms
|
||||
|
||||
|
||||
class LookupModule(LookupBase):
|
||||
def run(self, terms, variables, **kwargs):
|
||||
if not HAVE_REDIS:
|
||||
raise AnsibleError("Can't LOOKUP(redis_kv): module redis is not installed")
|
||||
|
||||
# get options
|
||||
self.set_options(direct=kwargs)
|
||||
check_for_wrong_terms(self, direct=kwargs)
|
||||
|
||||
# setup connection
|
||||
host = self.get_option("host")
|
||||
port = self.get_option("port")
|
||||
socket = self.get_option("socket")
|
||||
if socket is None:
|
||||
conn = redis.Redis(host=host, port=port)
|
||||
else:
|
||||
conn = redis.Redis(unix_socket_path=socket)
|
||||
|
||||
ret = []
|
||||
for term in terms:
|
||||
try:
|
||||
res = conn.get(term)
|
||||
if res is None:
|
||||
res = ""
|
||||
ret.append(to_text(res))
|
||||
except Exception as e:
|
||||
# connection failed or key not found
|
||||
raise AnsibleError(f"Encountered exception while fetching {term}: {e}") from e
|
||||
return ret
|
||||
+105
@@ -0,0 +1,105 @@
|
||||
# Copyright (c) 2021, RevBits <info@revbits.com>
|
||||
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
from __future__ import annotations
|
||||
|
||||
DOCUMENTATION = r"""
|
||||
name: revbitspss
|
||||
author: RevBits (@RevBits) <info@revbits.com>
|
||||
short_description: Get secrets from RevBits PAM server
|
||||
version_added: 4.1.0
|
||||
description:
|
||||
- Uses the revbits_ansible Python SDK to get Secrets from RevBits PAM Server using API key authentication with the REST
|
||||
API.
|
||||
requirements:
|
||||
- revbits_ansible - U(https://pypi.org/project/revbits_ansible/)
|
||||
options:
|
||||
_terms:
|
||||
description:
|
||||
- This is an array of keys for secrets which you want to fetch from RevBits PAM.
|
||||
required: true
|
||||
type: list
|
||||
elements: string
|
||||
base_url:
|
||||
description:
|
||||
- This is the base URL of the server, for example V(https://server-url-here).
|
||||
required: true
|
||||
type: string
|
||||
api_key:
|
||||
description:
|
||||
- This is the API key for authentication. You can get it from the RevBits PAM secret manager module.
|
||||
required: true
|
||||
type: string
|
||||
secret: true
|
||||
"""
|
||||
|
||||
RETURN = r"""
|
||||
_list:
|
||||
description:
|
||||
- The JSON responses which you can access with defined keys.
|
||||
- If you are fetching secrets named as UUID, PASSWORD it returns the dict of all secrets.
|
||||
type: list
|
||||
elements: dict
|
||||
"""
|
||||
|
||||
EXAMPLES = r"""
|
||||
---
|
||||
- hosts: localhost
|
||||
vars:
|
||||
secret: >-
|
||||
{{
|
||||
lookup(
|
||||
'community.general.revbitspss',
|
||||
'UUIDPAM', 'DB_PASS',
|
||||
base_url='https://server-url-here',
|
||||
api_key='API_KEY_GOES_HERE'
|
||||
)
|
||||
}}
|
||||
tasks:
|
||||
- ansible.builtin.debug:
|
||||
msg: >-
|
||||
UUIDPAM is {{ (secret['UUIDPAM']) }} and DB_PASS is {{ (secret['DB_PASS']) }}
|
||||
"""
|
||||
|
||||
from ansible.errors import AnsibleError
|
||||
from ansible.plugins.lookup import LookupBase
|
||||
from ansible.utils.display import Display
|
||||
|
||||
from ansible_collections.community.general.plugins.plugin_utils._lookup import check_for_wrong_terms
|
||||
|
||||
ANOTHER_LIBRARY_IMPORT_ERROR: ImportError | None
|
||||
try:
|
||||
from pam.revbits_ansible.server import SecretServer
|
||||
except ImportError as imp_exc:
|
||||
ANOTHER_LIBRARY_IMPORT_ERROR = imp_exc
|
||||
else:
|
||||
ANOTHER_LIBRARY_IMPORT_ERROR = None
|
||||
|
||||
|
||||
display = Display()
|
||||
|
||||
|
||||
class LookupModule(LookupBase):
|
||||
@staticmethod
|
||||
def Client(server_parameters):
|
||||
return SecretServer(**server_parameters)
|
||||
|
||||
def run(self, terms, variables, **kwargs):
|
||||
if ANOTHER_LIBRARY_IMPORT_ERROR:
|
||||
raise AnsibleError("revbits_ansible must be installed to use this plugin") from ANOTHER_LIBRARY_IMPORT_ERROR
|
||||
self.set_options(var_options=variables, direct=kwargs)
|
||||
check_for_wrong_terms(self, direct=kwargs)
|
||||
secret_server = LookupModule.Client(
|
||||
{
|
||||
"base_url": self.get_option("base_url"),
|
||||
"api_key": self.get_option("api_key"),
|
||||
}
|
||||
)
|
||||
result = []
|
||||
for term in terms:
|
||||
try:
|
||||
display.vvv(f"Secret Server lookup of Secret with ID {term}")
|
||||
result.append({term: secret_server.get_pam_secret(term)})
|
||||
except Exception as error:
|
||||
raise AnsibleError(f"Secret Server lookup failure: {error.message}") from error
|
||||
return result
|
||||
+99
@@ -0,0 +1,99 @@
|
||||
# Copyright (c) 2015, Alejandro Guirao <lekumberri@gmail.com>
|
||||
# Copyright (c) 2012-17 Ansible Project
|
||||
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
from __future__ import annotations
|
||||
|
||||
DOCUMENTATION = r"""
|
||||
name: shelvefile
|
||||
author: Alejandro Guirao (!UNKNOWN) <lekumberri@gmail.com>
|
||||
short_description: Read keys from Python shelve file
|
||||
description:
|
||||
- Read keys from Python shelve file.
|
||||
options:
|
||||
_terms:
|
||||
description: Sets of key value pairs of parameters.
|
||||
type: list
|
||||
elements: str
|
||||
key:
|
||||
description: Key to query.
|
||||
type: str
|
||||
required: true
|
||||
file:
|
||||
description: Path to shelve file.
|
||||
type: path
|
||||
required: true
|
||||
"""
|
||||
|
||||
EXAMPLES = r"""
|
||||
---
|
||||
- name: Retrieve a string value corresponding to a key inside a Python shelve file
|
||||
ansible.builtin.debug:
|
||||
msg: "{{ lookup('community.general.shelvefile', 'file=path_to_some_shelve_file.db key=key_to_retrieve') }}"
|
||||
"""
|
||||
|
||||
RETURN = r"""
|
||||
_list:
|
||||
description: Value(s) of key(s) in shelve file(s).
|
||||
type: list
|
||||
elements: str
|
||||
"""
|
||||
import shelve
|
||||
|
||||
from ansible.errors import AnsibleAssertionError, AnsibleError
|
||||
from ansible.module_utils.common.text.converters import to_bytes, to_text
|
||||
from ansible.plugins.lookup import LookupBase
|
||||
|
||||
from ansible_collections.community.general.plugins.plugin_utils._lookup import check_for_wrong_terms
|
||||
|
||||
|
||||
class LookupModule(LookupBase):
|
||||
def read_shelve(self, shelve_filename, key):
|
||||
"""
|
||||
Read the value of "key" from a shelve file
|
||||
"""
|
||||
d = shelve.open(to_bytes(shelve_filename))
|
||||
res = d.get(key, None)
|
||||
d.close()
|
||||
return res
|
||||
|
||||
def run(self, terms, variables=None, **kwargs):
|
||||
# TODO: use new-style option parsing
|
||||
if not isinstance(terms, list):
|
||||
terms = [terms]
|
||||
|
||||
check_for_wrong_terms(self, direct=kwargs)
|
||||
|
||||
ret = []
|
||||
|
||||
for term in terms:
|
||||
paramvals = {"file": None, "key": None}
|
||||
params = term.split()
|
||||
|
||||
try:
|
||||
for param in params:
|
||||
name, value = param.split("=")
|
||||
if name not in paramvals:
|
||||
raise AnsibleAssertionError(f"{name} not in paramvals")
|
||||
paramvals[name] = value
|
||||
|
||||
except (ValueError, AssertionError) as e:
|
||||
# In case "file" or "key" are not present
|
||||
raise AnsibleError(e) from e
|
||||
|
||||
key = paramvals["key"]
|
||||
|
||||
# Search also in the role/files directory and in the playbook directory
|
||||
shelvefile = self.find_file_in_search_path(variables, "files", paramvals["file"])
|
||||
|
||||
if shelvefile:
|
||||
res = self.read_shelve(shelvefile, key)
|
||||
if res is None:
|
||||
raise AnsibleError(f"Key {key} not found in shelve file {shelvefile}")
|
||||
# Convert the value read to string
|
||||
ret.append(to_text(res))
|
||||
break
|
||||
else:
|
||||
raise AnsibleError(f"Could not locate shelve file in lookup: {paramvals['file']}")
|
||||
|
||||
return ret
|
||||
@@ -0,0 +1,616 @@
|
||||
# Copyright (c) 2020, Adam Migus <adam@migus.org>
|
||||
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
from __future__ import annotations
|
||||
|
||||
DOCUMENTATION = r"""
|
||||
name: tss
|
||||
author: Adam Migus (@amigus) <adam@migus.org>
|
||||
short_description: Get secrets from Delinea Secret Server
|
||||
version_added: 1.0.0
|
||||
description:
|
||||
- Uses the Thycotic Secret Server Python SDK to get Secrets from Secret Server using token authentication with O(username)
|
||||
and O(password) on the REST API at O(base_url).
|
||||
- When using self-signed certificates the environment variable E(REQUESTS_CA_BUNDLE) can be set to a file containing the
|
||||
trusted certificates (in C(.pem) format).
|
||||
- For example, C(export REQUESTS_CA_BUNDLE='/etc/ssl/certs/ca-bundle.trust.crt').
|
||||
requirements:
|
||||
- python-tss-sdk - https://pypi.org/project/python-tss-sdk/
|
||||
options:
|
||||
_terms:
|
||||
description: The integer ID of the secret.
|
||||
required: true
|
||||
type: list
|
||||
elements: int
|
||||
secret_path:
|
||||
description: Indicate a full path of secret including folder and secret name when the secret ID is set to 0.
|
||||
required: false
|
||||
type: str
|
||||
version_added: 7.2.0
|
||||
fetch_secret_ids_from_folder:
|
||||
description:
|
||||
- Boolean flag which indicates whether secret IDs are in a folder is fetched by folder ID or not.
|
||||
- V(true) then the terms are considered as a folder IDs. Otherwise (default), they are considered as secret IDs.
|
||||
required: false
|
||||
type: bool
|
||||
version_added: 7.1.0
|
||||
fetch_attachments:
|
||||
description:
|
||||
- Boolean flag which indicates whether attached files are downloaded or not.
|
||||
- The download only happens if O(file_download_path) has been provided.
|
||||
required: false
|
||||
type: bool
|
||||
version_added: 7.0.0
|
||||
file_download_path:
|
||||
description: Indicate the file attachment download location.
|
||||
required: false
|
||||
type: path
|
||||
version_added: 7.0.0
|
||||
base_url:
|
||||
description: The base URL of the server, for example V(https://localhost/SecretServer).
|
||||
type: string
|
||||
env:
|
||||
- name: TSS_BASE_URL
|
||||
ini:
|
||||
- section: tss_lookup
|
||||
key: base_url
|
||||
required: true
|
||||
username:
|
||||
description: The username with which to request the OAuth2 Access Grant.
|
||||
type: string
|
||||
env:
|
||||
- name: TSS_USERNAME
|
||||
ini:
|
||||
- section: tss_lookup
|
||||
key: username
|
||||
password:
|
||||
description:
|
||||
- The password associated with the supplied username.
|
||||
- Required when O(token) is not provided.
|
||||
type: string
|
||||
env:
|
||||
- name: TSS_PASSWORD
|
||||
ini:
|
||||
- section: tss_lookup
|
||||
key: password
|
||||
secret: true
|
||||
domain:
|
||||
default: ""
|
||||
description:
|
||||
- The domain with which to request the OAuth2 Access Grant.
|
||||
- Optional when O(token) is not provided.
|
||||
- Requires C(python-tss-sdk) version 1.0.0 or greater.
|
||||
type: string
|
||||
env:
|
||||
- name: TSS_DOMAIN
|
||||
ini:
|
||||
- section: tss_lookup
|
||||
key: domain
|
||||
required: false
|
||||
version_added: 3.6.0
|
||||
token:
|
||||
description:
|
||||
- Existing token for Thycotic authorizer.
|
||||
- If provided, O(username) and O(password) are not needed.
|
||||
- Requires C(python-tss-sdk) version 1.0.0 or greater.
|
||||
type: string
|
||||
env:
|
||||
- name: TSS_TOKEN
|
||||
ini:
|
||||
- section: tss_lookup
|
||||
key: token
|
||||
version_added: 3.7.0
|
||||
secret: true
|
||||
api_path_uri:
|
||||
default: /api/v1
|
||||
description: The path to append to the base URL to form a valid REST API request.
|
||||
type: string
|
||||
env:
|
||||
- name: TSS_API_PATH_URI
|
||||
required: false
|
||||
token_path_uri:
|
||||
default: /oauth2/token
|
||||
description:
|
||||
- The path to append to the base URL to form a valid OAuth2 Access Grant request.
|
||||
- Used when O(token_path_source=token_path_uri) (the default). To let C(python-tss-sdk) auto-detect the token endpoint
|
||||
instead (for example for Delinea Platform authentication), set O(token_path_source=auto).
|
||||
type: string
|
||||
env:
|
||||
- name: TSS_TOKEN_PATH_URI
|
||||
ini:
|
||||
- section: tss_lookup
|
||||
key: token_path_uri
|
||||
version_added: 13.2.0
|
||||
required: false
|
||||
token_path_source:
|
||||
description:
|
||||
- How to determine the OAuth2 token endpoint path.
|
||||
- V(token_path_uri) uses the O(token_path_uri) option as given.
|
||||
- V(auto) ignores O(token_path_uri) and lets C(python-tss-sdk) auto-detect the token endpoint from O(base_url), selecting
|
||||
the correct path for Secret Server or the Delinea Platform.
|
||||
type: string
|
||||
choices:
|
||||
- token_path_uri
|
||||
- auto
|
||||
default: token_path_uri
|
||||
env:
|
||||
- name: TSS_TOKEN_PATH_SOURCE
|
||||
ini:
|
||||
- section: tss_lookup
|
||||
key: token_path_source
|
||||
required: false
|
||||
version_added: 13.2.0
|
||||
"""
|
||||
|
||||
RETURN = r"""
|
||||
_list:
|
||||
description:
|
||||
- The JSON responses to C(GET /secrets/{id}) and C(GET /secrets/{path}).
|
||||
- See U(https://updates.thycotic.net/secretserver/restapiguide/TokenAuth/#operation--secrets--id--get).
|
||||
type: list
|
||||
elements: dict
|
||||
"""
|
||||
|
||||
EXAMPLES = r"""
|
||||
# Using Secret Server Authentication
|
||||
- name: Lookup secret using Secret Server user credentials
|
||||
hosts: localhost
|
||||
vars:
|
||||
secret: >-
|
||||
{{
|
||||
lookup(
|
||||
'community.general.tss',
|
||||
102,
|
||||
base_url='https://secretserver.domain.com/SecretServer/',
|
||||
username='user.name',
|
||||
password='password'
|
||||
)
|
||||
}}
|
||||
tasks:
|
||||
- ansible.builtin.debug:
|
||||
msg: >
|
||||
the password is {{
|
||||
(secret['items']
|
||||
| items2dict(key_name='slug',
|
||||
value_name='itemValue'))['password']
|
||||
}}
|
||||
|
||||
- name: Lookup secret with domain user
|
||||
hosts: localhost
|
||||
vars:
|
||||
secret: >-
|
||||
{{
|
||||
lookup(
|
||||
'community.general.tss',
|
||||
102,
|
||||
base_url='https://secretserver.domain.com/SecretServer/',
|
||||
username='user.name',
|
||||
password='password',
|
||||
domain='domain'
|
||||
)
|
||||
}}
|
||||
tasks:
|
||||
- ansible.builtin.debug:
|
||||
msg: >
|
||||
the password is {{
|
||||
(secret['items']
|
||||
| items2dict(key_name='slug',
|
||||
value_name='itemValue'))['password']
|
||||
}}
|
||||
|
||||
- name: Lookup secret using Secret Server token
|
||||
hosts: localhost
|
||||
vars:
|
||||
secret_password: >-
|
||||
{{
|
||||
((lookup(
|
||||
'community.general.tss',
|
||||
102,
|
||||
base_url='https://secretserver.domain.com/SecretServer/',
|
||||
token='thycotic_access_token',
|
||||
) | from_json).get('items') | items2dict(key_name='slug', value_name='itemValue'))['password']
|
||||
}}
|
||||
tasks:
|
||||
- ansible.builtin.debug:
|
||||
msg: the password is {{ secret_password }}
|
||||
|
||||
# Private key stores into certificate file which is attached with secret.
|
||||
# If fetch_attachments=True then private key file will be download on specified path
|
||||
# and file content will display in debug message.
|
||||
- name: Lookup secret and fetch attachments using Secret Server token
|
||||
hosts: localhost
|
||||
vars:
|
||||
secret: >-
|
||||
{{
|
||||
lookup(
|
||||
'community.general.tss',
|
||||
102,
|
||||
fetch_attachments=True,
|
||||
file_download_path='/home/certs',
|
||||
base_url='https://secretserver.domain.com/SecretServer/',
|
||||
token='thycotic_access_token'
|
||||
)
|
||||
}}
|
||||
tasks:
|
||||
- ansible.builtin.debug:
|
||||
msg: >
|
||||
the private key is {{
|
||||
(secret['items']
|
||||
| items2dict(key_name='slug',
|
||||
value_name='itemValue'))['private-key']
|
||||
}}
|
||||
|
||||
# If fetch_secret_ids_from_folder=true then secret IDs are in a folder is fetched based on folder ID
|
||||
- name: Lookup secret IDs by folder ID using Secret Server token
|
||||
hosts: localhost
|
||||
vars:
|
||||
secret: >-
|
||||
{{
|
||||
lookup(
|
||||
'community.general.tss',
|
||||
102,
|
||||
fetch_secret_ids_from_folder=true,
|
||||
base_url='https://secretserver.domain.com/SecretServer/',
|
||||
token='thycotic_access_token'
|
||||
)
|
||||
}}
|
||||
tasks:
|
||||
- ansible.builtin.debug:
|
||||
msg: >
|
||||
the secret id's are {{
|
||||
secret
|
||||
}}
|
||||
|
||||
# If secret ID is 0 and secret_path has value then secret is fetched by secret path
|
||||
- name: Lookup secret by secret path using Secret Server user credentials
|
||||
hosts: localhost
|
||||
vars:
|
||||
secret: >-
|
||||
{{
|
||||
lookup(
|
||||
'community.general.tss',
|
||||
0,
|
||||
secret_path='\folderName\secretName'
|
||||
base_url='https://secretserver.domain.com/SecretServer/',
|
||||
username='user.name',
|
||||
password='password'
|
||||
)
|
||||
}}
|
||||
tasks:
|
||||
- ansible.builtin.debug:
|
||||
msg: >-
|
||||
the password is {{
|
||||
(secret['items']
|
||||
| items2dict(key_name='slug',
|
||||
value_name='itemValue'))['password']
|
||||
}}
|
||||
|
||||
# Using Platform Authentication
|
||||
- name: Lookup secret using Platform service user credentials
|
||||
hosts: localhost
|
||||
vars:
|
||||
secret: >-
|
||||
{{
|
||||
lookup(
|
||||
'community.general.tss',
|
||||
102,
|
||||
base_url='https://platform.delinea.app/',
|
||||
username='platform_service_username',
|
||||
password='platform_service_user_password',
|
||||
token_path_source='auto'
|
||||
)
|
||||
}}
|
||||
tasks:
|
||||
- ansible.builtin.debug:
|
||||
msg: >
|
||||
the password is {{
|
||||
(secret['items']
|
||||
| items2dict(key_name='slug',
|
||||
value_name='itemValue'))['password']
|
||||
}}
|
||||
|
||||
- name: Lookup secret using platform token
|
||||
hosts: localhost
|
||||
vars:
|
||||
secret_password: >-
|
||||
{{
|
||||
((lookup(
|
||||
'community.general.tss',
|
||||
102,
|
||||
base_url='https://platform.delinea.app/',
|
||||
token='delinea_platform_access_token',
|
||||
) | from_json).get('items') | items2dict(key_name='slug', value_name='itemValue'))['password']
|
||||
}}
|
||||
tasks:
|
||||
- ansible.builtin.debug:
|
||||
msg: the password is {{ secret_password }}
|
||||
"""
|
||||
|
||||
import abc
|
||||
import os
|
||||
import typing as t
|
||||
|
||||
from ansible.errors import AnsibleError, AnsibleOptionsError
|
||||
from ansible.plugins.lookup import LookupBase
|
||||
from ansible.utils.display import Display
|
||||
|
||||
from ansible_collections.community.general.plugins.plugin_utils._lookup import check_for_wrong_terms
|
||||
|
||||
try:
|
||||
from delinea.secrets.server import (
|
||||
AccessTokenAuthorizer,
|
||||
DomainPasswordGrantAuthorizer,
|
||||
PasswordGrantAuthorizer,
|
||||
SecretServer,
|
||||
SecretServerError,
|
||||
)
|
||||
|
||||
HAS_TSS_SDK = True
|
||||
HAS_DELINEA_SS_SDK = True
|
||||
HAS_TSS_AUTHORIZER = True
|
||||
except ImportError:
|
||||
try:
|
||||
from thycotic.secrets.server import (
|
||||
AccessTokenAuthorizer,
|
||||
DomainPasswordGrantAuthorizer,
|
||||
PasswordGrantAuthorizer,
|
||||
SecretServer,
|
||||
SecretServerError,
|
||||
)
|
||||
|
||||
HAS_TSS_SDK = True
|
||||
HAS_DELINEA_SS_SDK = False
|
||||
HAS_TSS_AUTHORIZER = True
|
||||
except ImportError:
|
||||
SecretServer = None
|
||||
SecretServerError = None
|
||||
HAS_TSS_SDK = False
|
||||
HAS_DELINEA_SS_SDK = False
|
||||
PasswordGrantAuthorizer = None
|
||||
DomainPasswordGrantAuthorizer = None
|
||||
AccessTokenAuthorizer = None
|
||||
HAS_TSS_AUTHORIZER = False
|
||||
|
||||
|
||||
# SecretServerClientError (4xx) is exported by newer python-tss-sdk builds. When
|
||||
# present it lets us distinguish auth/permission failures from 5xx service errors
|
||||
# so a stale cached client can be invalidated and the lookup retried once. On
|
||||
# older SDKs the import is absent and the retry is simply skipped.
|
||||
try:
|
||||
from delinea.secrets.server import SecretServerClientError
|
||||
|
||||
HAS_SS_CLIENT_ERROR = True
|
||||
except ImportError:
|
||||
try:
|
||||
from thycotic.secrets.server import SecretServerClientError
|
||||
|
||||
HAS_SS_CLIENT_ERROR = True
|
||||
except ImportError:
|
||||
SecretServerClientError = None
|
||||
HAS_SS_CLIENT_ERROR = False
|
||||
|
||||
|
||||
if t.TYPE_CHECKING:
|
||||
CacheKey = tuple[str | None, str | None, str | None, str | None, str | None]
|
||||
|
||||
|
||||
display = Display()
|
||||
|
||||
|
||||
class TSSClient(metaclass=abc.ABCMeta): # noqa: B024
|
||||
def __init__(self):
|
||||
self._client = None
|
||||
|
||||
@staticmethod
|
||||
def from_params(**server_parameters):
|
||||
if HAS_TSS_AUTHORIZER:
|
||||
return TSSClientV1(**server_parameters)
|
||||
else:
|
||||
return TSSClientV0(**server_parameters)
|
||||
|
||||
def get_secret(self, term, secret_path, fetch_file_attachments, file_download_path):
|
||||
display.debug(f"tss_lookup term: {term}")
|
||||
secret_id = self._term_to_secret_id(term)
|
||||
if secret_id == 0 and secret_path:
|
||||
fetch_secret_by_path = True
|
||||
display.vvv(f"Secret Server lookup of Secret with path {secret_path}")
|
||||
else:
|
||||
fetch_secret_by_path = False
|
||||
display.vvv(f"Secret Server lookup of Secret with ID {secret_id}")
|
||||
|
||||
if fetch_file_attachments:
|
||||
if fetch_secret_by_path:
|
||||
obj = self._client.get_secret_by_path(secret_path, fetch_file_attachments)
|
||||
else:
|
||||
obj = self._client.get_secret(secret_id, fetch_file_attachments)
|
||||
for i in obj["items"]:
|
||||
if file_download_path and os.path.isdir(file_download_path):
|
||||
if i["isFile"]:
|
||||
try:
|
||||
file_content = i["itemValue"].content
|
||||
with open(os.path.join(file_download_path, f"{obj['id']}_{i['slug']}"), "wb") as f:
|
||||
f.write(file_content)
|
||||
except ValueError as e:
|
||||
raise AnsibleOptionsError(f"Failed to download {i['slug']}") from e
|
||||
except AttributeError:
|
||||
display.warning(f"Could not read file content for {i['slug']}")
|
||||
finally:
|
||||
i["itemValue"] = "*** Not Valid For Display ***"
|
||||
else:
|
||||
raise AnsibleOptionsError("File download path does not exist")
|
||||
return obj
|
||||
else:
|
||||
if fetch_secret_by_path:
|
||||
return self._client.get_secret_by_path(secret_path, False)
|
||||
else:
|
||||
return self._client.get_secret_json(secret_id)
|
||||
|
||||
def get_secret_ids_by_folderid(self, term):
|
||||
display.debug(f"tss_lookup term: {term}")
|
||||
folder_id = self._term_to_folder_id(term)
|
||||
display.vvv(f"Secret Server lookup of Secret id's with Folder ID {folder_id}")
|
||||
|
||||
return self._client.get_secret_ids_by_folderid(folder_id)
|
||||
|
||||
@staticmethod
|
||||
def _term_to_secret_id(term):
|
||||
try:
|
||||
return int(term)
|
||||
except ValueError as e:
|
||||
raise AnsibleOptionsError("Secret ID must be an integer") from e
|
||||
|
||||
@staticmethod
|
||||
def _term_to_folder_id(term):
|
||||
try:
|
||||
return int(term)
|
||||
except ValueError as e:
|
||||
raise AnsibleOptionsError("Folder ID must be an integer") from e
|
||||
|
||||
|
||||
class TSSClientV0(TSSClient):
|
||||
def __init__(self, **server_parameters):
|
||||
super().__init__()
|
||||
|
||||
if server_parameters.get("domain"):
|
||||
raise AnsibleError("The 'domain' option requires 'python-tss-sdk' version 1.0.0 or greater")
|
||||
|
||||
self._client = SecretServer(
|
||||
server_parameters["base_url"],
|
||||
server_parameters["username"],
|
||||
server_parameters["password"],
|
||||
server_parameters["api_path_uri"],
|
||||
server_parameters["token_path_uri"],
|
||||
)
|
||||
|
||||
|
||||
class TSSClientV1(TSSClient):
|
||||
def __init__(self, **server_parameters):
|
||||
super().__init__()
|
||||
|
||||
authorizer = self._get_authorizer(**server_parameters)
|
||||
self._client = SecretServer(server_parameters["base_url"], authorizer, server_parameters["api_path_uri"])
|
||||
|
||||
@staticmethod
|
||||
def _get_authorizer(**server_parameters):
|
||||
if server_parameters.get("token"):
|
||||
return AccessTokenAuthorizer(server_parameters["token"], server_parameters["base_url"])
|
||||
|
||||
if server_parameters.get("domain"):
|
||||
return DomainPasswordGrantAuthorizer(
|
||||
server_parameters["base_url"],
|
||||
server_parameters["username"],
|
||||
server_parameters["domain"],
|
||||
server_parameters["password"],
|
||||
server_parameters["token_path_uri"],
|
||||
)
|
||||
|
||||
return PasswordGrantAuthorizer(
|
||||
server_parameters["base_url"],
|
||||
server_parameters["username"],
|
||||
server_parameters["password"],
|
||||
server_parameters["token_path_uri"],
|
||||
)
|
||||
|
||||
|
||||
# Module-scope cache of TSSClient instances, keyed on credential identity. Each
|
||||
# TSSClient holds an authorizer whose internal token cache is only useful if the
|
||||
# client is reused; without this, every lookup() call mints a fresh OAuth2 token
|
||||
# grant, which can overload the token endpoint on lookup-heavy playbooks.
|
||||
_client_cache: dict[CacheKey, TSSClient] = {}
|
||||
|
||||
|
||||
def _credential_key(server_parameters: dict[str, str | None]) -> CacheKey | None:
|
||||
# Token-based auth makes no token-endpoint call, so caching adds nothing.
|
||||
if server_parameters.get("token"):
|
||||
return None
|
||||
# password is intentionally excluded from the key: the cached client holds
|
||||
# the password on its authorizer, so a second lookup with the same username
|
||||
# but a different password would not be "fixed" by keying separately - it
|
||||
# would just split the cache while the first authorizer's password is what
|
||||
# actually gets used.
|
||||
return (
|
||||
server_parameters.get("base_url"),
|
||||
server_parameters.get("username"),
|
||||
server_parameters.get("domain"),
|
||||
server_parameters.get("api_path_uri"),
|
||||
server_parameters.get("token_path_uri"),
|
||||
)
|
||||
|
||||
|
||||
def _get_or_build_client(server_parameters: dict[str, str | None]) -> TSSClient:
|
||||
key = _credential_key(server_parameters)
|
||||
if key is None:
|
||||
return TSSClient.from_params(**server_parameters)
|
||||
# On a cache miss, build the client (from_params makes the token-endpoint
|
||||
# network call) and setdefault to insert it. setdefault resolves the case
|
||||
# where two builds for the same key happen concurrently: the first insert
|
||||
# wins and the later client is discarded.
|
||||
tss = _client_cache.get(key)
|
||||
if tss is not None:
|
||||
return tss
|
||||
new_tss = TSSClient.from_params(**server_parameters)
|
||||
return _client_cache.setdefault(key, new_tss)
|
||||
|
||||
|
||||
def _drop_cached_client(server_parameters: dict[str, str | None]) -> None:
|
||||
key = _credential_key(server_parameters)
|
||||
if key is None:
|
||||
return
|
||||
_client_cache.pop(key, None)
|
||||
|
||||
|
||||
class LookupModule(LookupBase):
|
||||
def run(self, terms, variables, **kwargs):
|
||||
if not HAS_TSS_SDK:
|
||||
raise AnsibleError("python-tss-sdk must be installed to use this plugin")
|
||||
|
||||
self.set_options(var_options=variables, direct=kwargs)
|
||||
check_for_wrong_terms(self, direct=kwargs)
|
||||
|
||||
# token_path_source selects how the OAuth2 token endpoint is resolved:
|
||||
# "auto" passes an empty path so python-tss-sdk auto-detects the endpoint
|
||||
# from base_url; the default uses token_path_uri as given.
|
||||
token_path_uri = self.get_option("token_path_uri")
|
||||
if self.get_option("token_path_source") == "auto":
|
||||
token_path_uri = ""
|
||||
|
||||
params = {
|
||||
"base_url": self.get_option("base_url"),
|
||||
"username": self.get_option("username"),
|
||||
"password": self.get_option("password"),
|
||||
"domain": self.get_option("domain"),
|
||||
"token": self.get_option("token"),
|
||||
"api_path_uri": self.get_option("api_path_uri"),
|
||||
"token_path_uri": token_path_uri,
|
||||
}
|
||||
|
||||
try:
|
||||
return self._lookup(terms, _get_or_build_client(params))
|
||||
except SecretServerError as error:
|
||||
# A 4xx is often a stale cached token: drop the cached client so the
|
||||
# rebuild mints a fresh grant, then retry once. 5xx and anything else
|
||||
# propagate unchanged. The retry re-runs the lookup for all terms,
|
||||
# not just the one that raised; reads are idempotent so that is safe,
|
||||
# though it can produce duplicate reads in the Secret Server audit log.
|
||||
if HAS_SS_CLIENT_ERROR and isinstance(error, SecretServerClientError):
|
||||
_drop_cached_client(params)
|
||||
try:
|
||||
return self._lookup(terms, _get_or_build_client(params))
|
||||
except SecretServerError as retry_error:
|
||||
raise AnsibleError(f"Secret Server lookup failure: {retry_error.message}") from retry_error
|
||||
raise AnsibleError(f"Secret Server lookup failure: {error.message}") from error
|
||||
|
||||
def _lookup(self, terms, tss):
|
||||
if self.get_option("fetch_secret_ids_from_folder"):
|
||||
if HAS_DELINEA_SS_SDK:
|
||||
return [tss.get_secret_ids_by_folderid(term) for term in terms]
|
||||
raise AnsibleError("latest python-tss-sdk must be installed to use this plugin")
|
||||
return [
|
||||
tss.get_secret(
|
||||
term,
|
||||
self.get_option("secret_path"),
|
||||
self.get_option("fetch_attachments"),
|
||||
self.get_option("file_download_path"),
|
||||
)
|
||||
for term in terms
|
||||
]
|
||||
Reference in New Issue
Block a user