| 1 |
# (c) 2020, Brian Scholer (@briantist) |
| 2 |
# (c) 2015, Julie Davila (@juliedavila) <julie(at)davila.io> |
| 3 |
# (c) 2017 Ansible Project |
| 4 |
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 5 |
# SPDX-License-Identifier: GPL-3.0-or-later |
| 6 |
|
| 7 |
from __future__ import (absolute_import, division, print_function) |
| 8 |
__metaclass__ = type |
| 9 |
|
| 10 |
DOCUMENTATION = """ |
| 11 |
name: hashi_vault |
| 12 |
author: |
| 13 |
- Julie Davila (@juliedavila) <julie(at)davila.io> |
| 14 |
- Brian Scholer (@briantist) |
| 15 |
short_description: Retrieve secrets from HashiCorp's Vault |
| 16 |
requirements: |
| 17 |
- C(hvac) (L(Python library,https://hvac.readthedocs.io/en/stable/overview.html)) |
| 18 |
- For detailed requirements, see R(the collection requirements page,ansible_collections.community.hashi_vault.docsite.user_guide.requirements). |
| 19 |
description: |
| 20 |
- Retrieve secrets from HashiCorp's Vault. |
| 21 |
- Consider R(migrating to other plugins in the collection,ansible_collections.community.hashi_vault.docsite.migration_hashi_vault_lookup). |
| 22 |
seealso: |
| 23 |
- ref: community.hashi_vault.hashi_vault Migration Guide <ansible_collections.community.hashi_vault.docsite.migration_hashi_vault_lookup> |
| 24 |
description: Migrating from the C(hashi_vault) lookup. |
| 25 |
- ref: About the community.hashi_vault.hashi_vault lookup <ansible_collections.community.hashi_vault.docsite.about_hashi_vault_lookup> |
| 26 |
description: The past, present, and future of the C(hashi_vault) lookup. |
| 27 |
- ref: community.hashi_vault.vault_read lookup <ansible_collections.community.hashi_vault.vault_read_lookup> |
| 28 |
description: The official documentation for the C(community.hashi_vault.vault_read) lookup plugin. |
| 29 |
- module: community.hashi_vault.vault_read |
| 30 |
- ref: community.hashi_vault.vault_kv2_get lookup <ansible_collections.community.hashi_vault.vault_kv2_get_lookup> |
| 31 |
description: The official documentation for the C(community.hashi_vault.vault_kv2_get) lookup plugin. |
| 32 |
- module: community.hashi_vault.vault_kv2_get |
| 33 |
- ref: community.hashi_vault.vault_kv1_get lookup <ansible_collections.community.hashi_vault.vault_kv1_get_lookup> |
| 34 |
description: The official documentation for the C(community.hashi_vault.vault_kv1_get) lookup plugin. |
| 35 |
- module: community.hashi_vault.vault_kv1_get |
| 36 |
- ref: community.hashi_vault Lookup Guide <ansible_collections.community.hashi_vault.docsite.lookup_guide> |
| 37 |
description: Guidance on using lookups in C(community.hashi_vault). |
| 38 |
notes: |
| 39 |
- Due to a current limitation in the HVAC library there won't necessarily be an error if a bad endpoint is specified. |
| 40 |
- As of community.hashi_vault 0.1.0, only the latest version of a secret is returned when specifying a KV v2 path. |
| 41 |
- As of community.hashi_vault 0.1.0, all options can be supplied via term string (space delimited key=value pairs) or by parameters (see examples). |
| 42 |
- As of community.hashi_vault 0.1.0, when I(secret) is the first option in the term string, C(secret=) is not required (see examples). |
| 43 |
extends_documentation_fragment: |
| 44 |
- community.hashi_vault.connection |
| 45 |
- community.hashi_vault.connection.plugins |
| 46 |
- community.hashi_vault.auth |
| 47 |
- community.hashi_vault.auth.plugins |
| 48 |
options: |
| 49 |
secret: |
| 50 |
description: Vault path to the secret being requested in the format C(path[:field]). |
| 51 |
required: True |
| 52 |
return_format: |
| 53 |
description: |
| 54 |
- Controls how multiple key/value pairs in a path are treated on return. |
| 55 |
- C(dict) returns a single dict containing the key/value pairs. |
| 56 |
- C(values) returns a list of all the values only. Use when you don't care about the keys. |
| 57 |
- C(raw) returns the actual API result (deserialized), which includes metadata and may have the data nested in other keys. |
| 58 |
choices: |
| 59 |
- dict |
| 60 |
- values |
| 61 |
- raw |
| 62 |
default: dict |
| 63 |
aliases: [ as ] |
| 64 |
""" |
| 65 |
|
| 66 |
EXAMPLES = """ |
| 67 |
- ansible.builtin.debug: |
| 68 |
msg: "{{ lookup('community.hashi_vault.hashi_vault', 'secret=secret/hello:value token=c975b780-d1be-8016-866b-01d0f9b688a5 url=http://myvault:8200') }}" |
| 69 |
|
| 70 |
- name: Return all secrets from a path |
| 71 |
ansible.builtin.debug: |
| 72 |
msg: "{{ lookup('community.hashi_vault.hashi_vault', 'secret=secret/hello token=c975b780-d1be-8016-866b-01d0f9b688a5 url=http://myvault:8200') }}" |
| 73 |
|
| 74 |
- name: Vault that requires authentication via LDAP |
| 75 |
ansible.builtin.debug: |
| 76 |
msg: "{{ lookup('community.hashi_vault.hashi_vault', 'secret/hello:value auth_method=ldap mount_point=ldap username=myuser password=mypas') }}" |
| 77 |
|
| 78 |
- name: Vault that requires authentication via username and password |
| 79 |
ansible.builtin.debug: |
| 80 |
msg: "{{ lookup('community.hashi_vault.hashi_vault', 'secret=secret/hola:val auth_method=userpass username=myuser password=psw url=http://vault:8200') }}" |
| 81 |
|
| 82 |
- name: Connect to Vault using TLS |
| 83 |
ansible.builtin.debug: |
| 84 |
msg: "{{ lookup('community.hashi_vault.hashi_vault', 'secret=secret/hola:value token=c975b780-d1be-8016-866b-01d0f9b688a5 validate_certs=False') }}" |
| 85 |
|
| 86 |
- name: using certificate auth |
| 87 |
ansible.builtin.debug: |
| 88 |
msg: "{{ lookup('community.hashi_vault.hashi_vault', 'secret/hi:val token=xxxx url=https://vault:8200 validate_certs=True cacert=/cacert/path/ca.pem') }}" |
| 89 |
|
| 90 |
- name: Authenticate with a Vault app role |
| 91 |
ansible.builtin.debug: |
| 92 |
msg: "{{ lookup('community.hashi_vault.hashi_vault', 'secret=secret/hello:value auth_method=approle role_id=myroleid secret_id=mysecretid') }}" |
| 93 |
|
| 94 |
- name: Return all secrets from a path in a namespace |
| 95 |
ansible.builtin.debug: |
| 96 |
msg: "{{ lookup('community.hashi_vault.hashi_vault', 'secret=secret/hello token=c975b780-d1be-8016-866b-01d0f9b688a5 namespace=teama/admins') }}" |
| 97 |
|
| 98 |
# When using KV v2 the PATH should include "data" between the secret engine mount and path (e.g. "secret/data/:path") |
| 99 |
# see: https://www.vaultproject.io/api/secret/kv/kv-v2.html#read-secret-version |
| 100 |
- name: Return latest KV v2 secret from path |
| 101 |
ansible.builtin.debug: |
| 102 |
msg: "{{ lookup('community.hashi_vault.hashi_vault', 'secret=secret/data/hello token=my_vault_token url=http://myvault_url:8200') }}" |
| 103 |
|
| 104 |
# The following examples show more modern syntax, with parameters specified separately from the term string. |
| 105 |
|
| 106 |
- name: secret= is not required if secret is first |
| 107 |
ansible.builtin.debug: |
| 108 |
msg: "{{ lookup('community.hashi_vault.hashi_vault', 'secret/data/hello token=<token> url=http://myvault_url:8200') }}" |
| 109 |
|
| 110 |
- name: options can be specified as parameters rather than put in term string |
| 111 |
ansible.builtin.debug: |
| 112 |
msg: "{{ lookup('community.hashi_vault.hashi_vault', 'secret/data/hello', token=my_token_var, url='http://myvault_url:8200') }}" |
| 113 |
|
| 114 |
# return_format (or its alias 'as') can control how secrets are returned to you |
| 115 |
- name: return secrets as a dict (default) |
| 116 |
ansible.builtin.set_fact: |
| 117 |
my_secrets: "{{ lookup('community.hashi_vault.hashi_vault', 'secret/data/manysecrets', token=my_token_var, url='http://myvault_url:8200') }}" |
| 118 |
- ansible.builtin.debug: |
| 119 |
msg: "{{ my_secrets['secret_key'] }}" |
| 120 |
- ansible.builtin.debug: |
| 121 |
msg: "Secret '{{ item.key }}' has value '{{ item.value }}'" |
| 122 |
loop: "{{ my_secrets | dict2items }}" |
| 123 |
|
| 124 |
- name: return secrets as values only |
| 125 |
ansible.builtin.debug: |
| 126 |
msg: "A secret value: {{ item }}" |
| 127 |
loop: "{{ query('community.hashi_vault.hashi_vault', 'secret/data/manysecrets', token=my_token_var, url='http://vault_url:8200', return_format='values') }}" |
| 128 |
|
| 129 |
- name: return raw secret from API, including metadata |
| 130 |
ansible.builtin.set_fact: |
| 131 |
my_secret: "{{ lookup('community.hashi_vault.hashi_vault', 'secret/data/hello:value', token=my_token_var, url='http://myvault_url:8200', as='raw') }}" |
| 132 |
- ansible.builtin.debug: |
| 133 |
msg: "This is version {{ my_secret['metadata']['version'] }} of hello:value. The secret data is {{ my_secret['data']['data']['value'] }}" |
| 134 |
|
| 135 |
# AWS IAM authentication method |
| 136 |
# uses Ansible standard AWS options |
| 137 |
|
| 138 |
- name: authenticate with aws_iam |
| 139 |
ansible.builtin.debug: |
| 140 |
msg: "{{ lookup('community.hashi_vault.hashi_vault', 'secret/hello:value', auth_method='aws_iam', role_id='myroleid', profile=my_boto_profile) }}" |
| 141 |
|
| 142 |
# JWT auth |
| 143 |
|
| 144 |
- name: Authenticate with a JWT |
| 145 |
ansible.builtin.debug: |
| 146 |
msg: "{{ lookup('community.hashi_vault.hashi_vault', 'secret/hola:val', auth_method='jwt', role_id='myroleid', jwt='myjwt', url='https://vault:8200') }}" |
| 147 |
|
| 148 |
#GCP auth |
| 149 |
|
| 150 |
- name: Authenticate with GCP |
| 151 |
ansible.builtin.debug: |
| 152 |
msg: "{{ lookup('community.hashi_vault.hashi_vault', 'secret/hola:val', auth_method='gcp', role_id='myroleid', jwt='myjwt', url='https://vault:8200') }}" |
| 153 |
|
| 154 |
# Disabling Token Validation |
| 155 |
# Use this when your token does not have the lookup-self capability. Usually this is applied to all tokens via the default policy. |
| 156 |
# However you can choose to create tokens without applying the default policy, or you can modify your default policy not to include it. |
| 157 |
# When disabled, your invalid or expired token will be indistinguishable from insufficent permissions. |
| 158 |
|
| 159 |
- name: authenticate without token validation |
| 160 |
ansible.builtin.debug: |
| 161 |
msg: "{{ lookup('community.hashi_vault.hashi_vault', 'secret/hello:value', token=my_token, token_validate=False) }}" |
| 162 |
|
| 163 |
# "none" auth method does no authentication and does not send a token to the Vault address. |
| 164 |
# One example of where this could be used is with a Vault agent where the agent will handle authentication to Vault. |
| 165 |
# https://www.vaultproject.io/docs/agent |
| 166 |
|
| 167 |
- name: authenticate with vault agent |
| 168 |
ansible.builtin.debug: |
| 169 |
msg: "{{ lookup('community.hashi_vault.hashi_vault', 'secret/hello:value', auth_method='none', url='http://127.0.0.1:8100') }}" |
| 170 |
|
| 171 |
# Use a proxy |
| 172 |
|
| 173 |
- name: use a proxy with login/password |
| 174 |
ansible.builtin.debug: |
| 175 |
msg: "{{ lookup('community.hashi_vault.hashi_vault', 'secret=... token=... url=https://... proxies=https://user:pass@myproxy:8080') }}" |
| 176 |
|
| 177 |
- name: 'use a socks proxy (need some additional dependencies, see: https://requests.readthedocs.io/en/master/user/advanced/#socks )' |
| 178 |
ansible.builtin.debug: |
| 179 |
msg: "{{ lookup('community.hashi_vault.hashi_vault', 'secret=... token=... url=https://... proxies=socks5://myproxy:1080') }}" |
| 180 |
|
| 181 |
- name: use proxies with a dict (as param) |
| 182 |
ansible.builtin.debug: |
| 183 |
msg: "{{ lookup('community.hashi_vault.hashi_vault', '...', proxies={'http': 'http://myproxy1', 'https': 'http://myproxy2'}) }}" |
| 184 |
|
| 185 |
- name: use proxies with a dict (as param, pre-defined var) |
| 186 |
vars: |
| 187 |
prox: |
| 188 |
http: http://myproxy1 |
| 189 |
https: https://myproxy2 |
| 190 |
ansible.builtin.debug: |
| 191 |
msg: "{{ lookup('community.hashi_vault.hashi_vault', '...', proxies=prox }}" |
| 192 |
|
| 193 |
- name: use proxies with a dict (as direct ansible var) |
| 194 |
vars: |
| 195 |
ansible_hashi_vault_proxies: |
| 196 |
http: http://myproxy1 |
| 197 |
https: https://myproxy2 |
| 198 |
ansible.builtin.debug: |
| 199 |
msg: "{{ lookup('community.hashi_vault.hashi_vault', '...' }}" |
| 200 |
|
| 201 |
- name: use proxies with a dict (in the term string, JSON syntax) |
| 202 |
ansible.builtin.debug: |
| 203 |
msg: "{{ lookup('community.hashi_vault.hashi_vault', '... proxies={\\"http\\":\\"http://myproxy1\\",\\"https\\":\\"http://myproxy2\\"}') }}" |
| 204 |
|
| 205 |
- name: use ansible vars to supply some options |
| 206 |
vars: |
| 207 |
ansible_hashi_vault_url: 'https://myvault:8282' |
| 208 |
ansible_hashi_vault_auth_method: token |
| 209 |
set_fact: |
| 210 |
secret1: "{{ lookup('community.hashi_vault.hashi_vault', 'secret/data/secret1') }}" |
| 211 |
secret2: "{{ lookup('community.hashi_vault.hashi_vault', 'secret/data/secret2') }}" |
| 212 |
|
| 213 |
- name: use a custom timeout |
| 214 |
debug: |
| 215 |
msg: "{{ lookup('community.hashi_vault.hashi_vault', 'secret/data/secret1', timeout=120) }}" |
| 216 |
|
| 217 |
- name: use a custom timeout and retry on failure 3 times (with collection retry defaults) |
| 218 |
vars: |
| 219 |
ansible_hashi_vault_timeout: 5 |
| 220 |
ansible_hashi_vault_retries: 3 |
| 221 |
debug: |
| 222 |
msg: "{{ lookup('community.hashi_vault.hashi_vault', 'secret/data/secret1') }}" |
| 223 |
|
| 224 |
- name: retry on failure (with custom retry settings and no warnings) |
| 225 |
vars: |
| 226 |
ansible_hashi_vault_retries: |
| 227 |
total: 6 |
| 228 |
backoff_factor: 0.9 |
| 229 |
status_forcelist: [500, 502] |
| 230 |
allowed_methods: |
| 231 |
- GET |
| 232 |
- PUT |
| 233 |
debug: |
| 234 |
msg: "{{ lookup('community.hashi_vault.hashi_vault', 'secret/data/secret1', retry_action='warn') }}" |
| 235 |
""" |
| 236 |
|
| 237 |
RETURN = """ |
| 238 |
_raw: |
| 239 |
description: |
| 240 |
- secrets(s) requested |
| 241 |
type: list |
| 242 |
elements: dict |
| 243 |
""" |
| 244 |
|
| 245 |
from ansible.errors import AnsibleError |
| 246 |
from ansible.utils.display import Display |
| 247 |
|
| 248 |
from ansible_collections.community.hashi_vault.plugins.plugin_utils._hashi_vault_lookup_base import HashiVaultLookupBase |
| 249 |
from ansible_collections.community.hashi_vault.plugins.module_utils._hashi_vault_common import HashiVaultValueError |
| 250 |
|
| 251 |
display = Display() |
| 252 |
|
| 253 |
|
| 254 |
class LookupModule(HashiVaultLookupBase): |
| 255 |
def run(self, terms, variables=None, **kwargs): |
| 256 |
|
| 257 |
ret = [] |
| 258 |
|
| 259 |
for term in terms: |
| 260 |
opts = kwargs.copy() |
| 261 |
opts.update(self.parse_kev_term(term, first_unqualified='secret', plugin_name='hashi_vault')) |
| 262 |
self.set_options(direct=opts, var_options=variables) |
| 263 |
# TODO: remove process_deprecations() if backported fix is available (see method definition) |
| 264 |
self.process_deprecations() |
| 265 |
self.process_options() |
| 266 |
|
| 267 |
client_args = self.connection_options.get_hvac_connection_options() |
| 268 |
self.client = self.helper.get_vault_client(**client_args) |
| 269 |
|
| 270 |
try: |
| 271 |
self.authenticator.authenticate(self.client) |
| 272 |
except (NotImplementedError, HashiVaultValueError) as e: |
| 273 |
raise AnsibleError(e) |
| 274 |
|
| 275 |
ret.extend(self.get()) |
| 276 |
|
| 277 |
return ret |
| 278 |
|
| 279 |
def process_options(self): |
| 280 |
'''performs deep validation and value loading for options''' |
| 281 |
|
| 282 |
# process connection options |
| 283 |
self.connection_options.process_connection_options() |
| 284 |
|
| 285 |
try: |
| 286 |
self.authenticator.validate() |
| 287 |
except (NotImplementedError, HashiVaultValueError) as e: |
| 288 |
raise AnsibleError(e) |
| 289 |
|
| 290 |
# secret field splitter |
| 291 |
self.field_ops() |
| 292 |
|
| 293 |
# begin options processing methods |
| 294 |
|
| 295 |
def field_ops(self): |
| 296 |
# split secret and field |
| 297 |
secret = self.get_option('secret') |
| 298 |
|
| 299 |
s_f = secret.rsplit(':', 1) |
| 300 |
self.set_option('secret', s_f[0]) |
| 301 |
if len(s_f) >= 2: |
| 302 |
field = s_f[1] |
| 303 |
else: |
| 304 |
field = None |
| 305 |
|
| 306 |
self._secret_field = field |
| 307 |
|
| 308 |
def get(self): |
| 309 |
'''gets a secret. should always return a list''' |
| 310 |
|
| 311 |
field = self._secret_field |
| 312 |
secret = self.get_option('secret') |
| 313 |
return_as = self.get_option('return_format') |
| 314 |
hvac_exceptions = self.helper.get_hvac().exceptions |
| 315 |
|
| 316 |
try: |
| 317 |
data = self.client.read(secret) |
| 318 |
except hvac_exceptions.Forbidden: |
| 319 |
raise AnsibleError("Forbidden: Permission Denied to secret '%s'." % secret) |
| 320 |
|
| 321 |
if data is None: |
| 322 |
raise AnsibleError("The secret '%s' doesn't seem to exist." % secret) |
| 323 |
|
| 324 |
if return_as == 'raw': |
| 325 |
return [data] |
| 326 |
|
| 327 |
# Check response for KV v2 fields and flatten nested secret data. |
| 328 |
# https://vaultproject.io/api/secret/kv/kv-v2.html#sample-response-1 |
| 329 |
try: |
| 330 |
# sentinel field checks |
| 331 |
check_dd = data['data']['data'] |
| 332 |
check_md = data['data']['metadata'] |
| 333 |
# unwrap nested data |
| 334 |
data = data['data'] |
| 335 |
except KeyError: |
| 336 |
pass |
| 337 |
|
| 338 |
if return_as == 'values': |
| 339 |
return list(data['data'].values()) |
| 340 |
|
| 341 |
# everything after here implements return_as == 'dict' |
| 342 |
if not field: |
| 343 |
return [data['data']] |
| 344 |
|
| 345 |
if field not in data['data']: |
| 346 |
raise AnsibleError("The secret %s does not contain the field '%s'. for hashi_vault lookup" % (secret, field)) |
| 347 |
|
| 348 |
return [data['data'][field]] |