Debian Codegraph @

ansible_collections/community/general/plugins/lookup/bitwarden_secrets_manager.py

raw
1 # Copyright (c) 2023, jantari (https://github.com/jantari)
2 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
3 # SPDX-License-Identifier: GPL-3.0-or-later
4 from __future__ import annotations
5
6 DOCUMENTATION = r"""
7 name: bitwarden_secrets_manager
8 author:
9 - jantari (@jantari)
10 requirements:
11 - bws (command line utility)
12 short_description: Retrieve secrets from Bitwarden Secrets Manager
13 version_added: 7.2.0
14 description:
15 - Retrieve secrets from Bitwarden Secrets Manager.
16 options:
17 _terms:
18 description: Secret ID(s) to fetch values for.
19 required: true
20 type: list
21 elements: str
22 bws_access_token:
23 description: The BWS access token to use for this lookup.
24 env:
25 - name: BWS_ACCESS_TOKEN
26 required: true
27 type: str
28 """
29
30 EXAMPLES = r"""
31 - name: Get a secret relying on the BWS_ACCESS_TOKEN environment variable for authentication
32 ansible.builtin.debug:
33 msg: >-
34 {{ lookup("community.general.bitwarden_secrets_manager", "2bc23e48-4932-40de-a047-5524b7ddc972") }}
35
36 - name: Get a secret passing an explicit access token for authentication
37 ansible.builtin.debug:
38 msg: >-
39 {{
40 lookup(
41 "community.general.bitwarden_secrets_manager",
42 "2bc23e48-4932-40de-a047-5524b7ddc972",
43 bws_access_token="9.4f570d14-4b54-42f5-bc07-60f4450b1db5.YmluYXJ5LXNvbWV0aGluZy0xMjMK:d2h5IGhlbGxvIHRoZXJlCg=="
44 )
45 }}
46
47 - name: Get two different secrets each using a different access token for authentication
48 ansible.builtin.debug:
49 msg:
50 - '{{ lookup("community.general.bitwarden_secrets_manager", "2bc23e48-4932-40de-a047-5524b7ddc972", bws_access_token=token1) }}'
51 - '{{ lookup("community.general.bitwarden_secrets_manager", "9d89af4c-eb5d-41f5-bb0f-4ae81215c768", bws_access_token=token2) }}'
52 vars:
53 token1: "9.4f570d14-4b54-42f5-bc07-60f4450b1db5.YmluYXJ5LXNvbWV0aGluZy0xMjMK:d2h5IGhlbGxvIHRoZXJlCg=="
54 token2: "1.69b72797-6ea9-4687-a11e-848e41a30ae6.YW5zaWJsZSBpcyBncmVhdD8K:YW5zaWJsZSBpcyBncmVhdAo="
55
56 - name: Get just the value of a secret
57 ansible.builtin.debug:
58 msg: >-
59 {{ lookup("community.general.bitwarden_secrets_manager", "2bc23e48-4932-40de-a047-5524b7ddc972").value }}
60 """
61
62 RETURN = r"""
63 _raw:
64 description: List containing one or more secrets.
65 type: list
66 elements: dict
67 """
68
69 from subprocess import PIPE, Popen
70 from time import sleep
71
72 from ansible.errors import AnsibleLookupError
73 from ansible.module_utils.common.text.converters import to_text
74 from ansible.parsing.ajson import AnsibleJSONDecoder
75 from ansible.plugins.lookup import LookupBase
76
77 from ansible_collections.community.general.plugins.module_utils._version import LooseVersion
78 from ansible_collections.community.general.plugins.plugin_utils._lookup import check_for_wrong_terms
79
80
81 class BitwardenSecretsManagerException(AnsibleLookupError):
82 pass
83
84
85 class BitwardenSecretsManager:
86 def __init__(self, path="bws"):
87 self._cli_path = path
88 self._max_retries = 3
89 self._retry_delay = 1
90
91 @property
92 def cli_path(self):
93 return self._cli_path
94
95 def _run_with_retry(self, args, stdin=None, retries=0):
96 out, err, rc = self._run(args, stdin)
97
98 if rc != 0:
99 if retries >= self._max_retries:
100 raise BitwardenSecretsManagerException("Max retries exceeded. Unable to retrieve secret.")
101
102 if "Too many requests" in err:
103 delay = self._retry_delay * (2**retries)
104 sleep(delay)
105 return self._run_with_retry(args, stdin, retries + 1)
106 else:
107 raise BitwardenSecretsManagerException(f"Command failed with return code {rc}: {err}")
108
109 return out, err, rc
110
111 def _run(self, args, stdin=None):
112 p = Popen([self.cli_path] + args, stdout=PIPE, stderr=PIPE, stdin=PIPE)
113 out, err = p.communicate(stdin)
114 rc = p.wait()
115 return to_text(out, errors="surrogate_or_strict"), to_text(err, errors="surrogate_or_strict"), rc
116
117 def get_bws_version(self):
118 """Get the version of the Bitwarden Secrets Manager CLI."""
119 out, err, rc = self._run(["--version"])
120 if rc != 0:
121 raise BitwardenSecretsManagerException(to_text(err))
122 # strip the prefix and grab the last segment, the version number
123 return out.split()[-1]
124
125 def get_secret(self, secret_id, bws_access_token):
126 """Get and return the secret with the given secret_id."""
127
128 # Prepare set of params for Bitwarden Secrets Manager CLI
129 # Color output was not always disabled correctly with the default 'auto' setting so explicitly disable it.
130 params = ["--color", "no", "--access-token", bws_access_token]
131
132 # bws version 0.3.0 introduced a breaking change in the command line syntax:
133 # pre-0.3.0: verb noun
134 # 0.3.0 and later: noun verb
135 bws_version = self.get_bws_version()
136 if LooseVersion(bws_version) < LooseVersion("0.3.0"):
137 params.extend(["get", "secret", secret_id])
138 else:
139 params.extend(["secret", "get", secret_id])
140
141 out, err, rc = self._run_with_retry(params)
142 if rc != 0:
143 raise BitwardenSecretsManagerException(to_text(err))
144
145 return AnsibleJSONDecoder().raw_decode(out)[0]
146
147
148 class LookupModule(LookupBase):
149 def run(self, terms, variables=None, **kwargs):
150 self.set_options(var_options=variables, direct=kwargs)
151 check_for_wrong_terms(self, direct=kwargs)
152 bws_access_token = self.get_option("bws_access_token")
153
154 return [_bitwarden_secrets_manager.get_secret(term, bws_access_token) for term in terms]
155
156
157 _bitwarden_secrets_manager = BitwardenSecretsManager()