| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
from __future__ import (absolute_import, division, print_function) |
| 5 |
__metaclass__ = type |
| 6 |
|
| 7 |
DOCUMENTATION = ''' |
| 8 |
author: Google Inc. (@googlecloudplatform) |
| 9 |
name: gcp_secret_manager |
| 10 |
short_description: Get Secrets from Google Cloud as a Lookup plugin |
| 11 |
description: |
| 12 |
- retrieve secret keys in Secret Manager for use in playbooks |
| 13 |
- see https://cloud.google.com/iam/docs/service-account-creds for details on creating |
| 14 |
credentials for Google Cloud and the format of such credentials |
| 15 |
- once a secret value is retreived, it is returned decoded. It is up to the developer |
| 16 |
to maintain secrecy of this value once returned. |
| 17 |
- if location option is defined, then it deals with the regional secrets of the |
| 18 |
location |
| 19 |
requirements: |
| 20 |
- python >= 2.6 |
| 21 |
- requests >= 2.18.4 |
| 22 |
- google-auth >= 1.3.0 |
| 23 |
|
| 24 |
options: |
| 25 |
key: |
| 26 |
description: |
| 27 |
- the name of the secret to look up in Secret Manager |
| 28 |
type: str |
| 29 |
required: True |
| 30 |
aliases: |
| 31 |
- name |
| 32 |
- secret |
| 33 |
- secret_id |
| 34 |
project: |
| 35 |
description: |
| 36 |
- The name of the google cloud project |
| 37 |
- defaults to OS env variable GCP_PROJECT if not present |
| 38 |
type: str |
| 39 |
location: |
| 40 |
description: |
| 41 |
- If provided, it defines the location of the regional secret. |
| 42 |
type: str |
| 43 |
auth_kind: |
| 44 |
description: |
| 45 |
- the type of authentication to use with Google Cloud (i.e. serviceaccount or machineaccount) |
| 46 |
- defaults to OS env variable GCP_AUTH_KIND if not present |
| 47 |
type: str |
| 48 |
version: |
| 49 |
description: |
| 50 |
- the version name of your secret to retrieve |
| 51 |
type: str |
| 52 |
default: latest |
| 53 |
required: False |
| 54 |
service_account_email: |
| 55 |
description: |
| 56 |
- email associated with the service account |
| 57 |
- defaults to OS env variable GCP_SERVICE_ACCOUNT_EMAIL if not present |
| 58 |
type: str |
| 59 |
required: False |
| 60 |
service_account_file: |
| 61 |
description: |
| 62 |
- JSON Credential file obtained from Google Cloud |
| 63 |
- defaults to OS env variable GCP_SERVICE_ACCOUNT_FILE if not present |
| 64 |
- see https://cloud.google.com/iam/docs/service-account-creds for details |
| 65 |
type: str |
| 66 |
required: False |
| 67 |
service_account_contents: |
| 68 |
description: |
| 69 |
- JSON Object representing the contents of a service_account_file obtained from Google Cloud |
| 70 |
- defaults to OS env variable GCP_SERVICE_ACCOUNT_CONTENTS if not present |
| 71 |
aliases: |
| 72 |
- service_account_info |
| 73 |
type: str |
| 74 |
required: False |
| 75 |
access_token: |
| 76 |
description: |
| 77 |
- support for GCP Access Token |
| 78 |
- defaults to OS env variable GCP_ACCESS_TOKEN if not present |
| 79 |
type: str |
| 80 |
required: False |
| 81 |
on_error: |
| 82 |
description: |
| 83 |
- how to handle errors |
| 84 |
- strict means raise an exception |
| 85 |
- warn means warn, and return none |
| 86 |
- ignore means just return none |
| 87 |
type: str |
| 88 |
required: False |
| 89 |
choices: |
| 90 |
- 'strict' |
| 91 |
- 'warn' |
| 92 |
- 'ignore' |
| 93 |
default: 'strict' |
| 94 |
scopes: |
| 95 |
description: |
| 96 |
- Authenticaiton scopes for Google Secret Manager |
| 97 |
type: list |
| 98 |
elements: str |
| 99 |
default: ["https://www.googleapis.com/auth/cloud-platform"] |
| 100 |
''' |
| 101 |
|
| 102 |
EXAMPLES = ''' |
| 103 |
- name: Test secret using env variables for credentials |
| 104 |
ansible.builtin.debug: |
| 105 |
msg: "{{ lookup('google.cloud.gcp_secret_manager', key='secret_key') }}" |
| 106 |
|
| 107 |
- name: Test secret using explicit credentials |
| 108 |
ansible.builtin.debug: |
| 109 |
msg: "{{ lookup('google.cloud.gcp_secret_manager', key='secret_key', project='project', auth_kind='serviceaccount', service_account_file='file.json') }}" |
| 110 |
|
| 111 |
- name: Test getting specific version of a secret (old version) |
| 112 |
ansible.builtin.debug: |
| 113 |
msg: "{{ lookup('google.cloud.gcp_secret_manager', key='secret_key', version='1') }}" |
| 114 |
|
| 115 |
- name: Test getting specific version of a secret (new version) |
| 116 |
ansible.builtin.debug: |
| 117 |
msg: "{{ lookup('google.cloud.gcp_secret_manager', key='secret_key', version='2') }}" |
| 118 |
|
| 119 |
- name: Test regional secret using env variables for credentials |
| 120 |
ansible.builtin.debug: |
| 121 |
msg: "{{ lookup('google.cloud.gcp_secret_manager', key='secret_key', location='us-central1') }}" |
| 122 |
|
| 123 |
- name: Test regional secret using explicit credentials |
| 124 |
ansible.builtin.debug: |
| 125 |
msg: "{{ lookup('google.cloud.gcp_secret_manager', key='secret_key', location='us-central1', project='project', auth_kind='serviceaccount', |
| 126 |
service_account_file='file.json') }}" |
| 127 |
|
| 128 |
- name: Test getting specific version of a regional secret (old version) |
| 129 |
ansible.builtin.debug: |
| 130 |
msg: "{{ lookup('google.cloud.gcp_secret_manager', key='secret_key', location='us-central1', version='1') }}" |
| 131 |
|
| 132 |
- name: Test getting specific version of a regional secret (new version) |
| 133 |
ansible.builtin.debug: |
| 134 |
msg: "{{ lookup('google.cloud.gcp_secret_manager', key='secret_key', location='us-central1', version='2') }}" |
| 135 |
''' |
| 136 |
|
| 137 |
RETURN = ''' |
| 138 |
_raw: |
| 139 |
description: the contents of the secret requested (please use "no_log" to not expose this secret) |
| 140 |
type: list |
| 141 |
elements: str |
| 142 |
''' |
| 143 |
|
| 144 |
|
| 145 |
|
| 146 |
|
| 147 |
|
| 148 |
import os |
| 149 |
import base64 |
| 150 |
|
| 151 |
from ansible.plugins.lookup import LookupBase |
| 152 |
from ansible.errors import AnsibleError |
| 153 |
from ansible.utils.display import Display |
| 154 |
|
| 155 |
try: |
| 156 |
import requests |
| 157 |
HAS_REQUESTS = True |
| 158 |
except ImportError: |
| 159 |
HAS_REQUESTS = False |
| 160 |
|
| 161 |
try: |
| 162 |
from ansible_collections.google.cloud.plugins.module_utils.gcp_utils import ( |
| 163 |
GcpSession, |
| 164 |
) |
| 165 |
HAS_GOOGLE_CLOUD_COLLECTION = True |
| 166 |
except ImportError: |
| 167 |
HAS_GOOGLE_CLOUD_COLLECTION = False |
| 168 |
|
| 169 |
|
| 170 |
class GcpLookupException(Exception): |
| 171 |
pass |
| 172 |
|
| 173 |
|
| 174 |
class GcpMockModule(object): |
| 175 |
def __init__(self, params): |
| 176 |
self.params = params |
| 177 |
|
| 178 |
def fail_json(self, *args, **kwargs): |
| 179 |
raise AnsibleError(kwargs["msg"]) |
| 180 |
|
| 181 |
def raise_for_status(self, response): |
| 182 |
try: |
| 183 |
response.raise_for_status() |
| 184 |
except getattr(requests.exceptions, "RequestException"): |
| 185 |
self.fail_json(msg="GCP returned error: %s" % response.json()) |
| 186 |
|
| 187 |
|
| 188 |
class LookupModule(LookupBase): |
| 189 |
def run(self, terms=None, variables=None, **kwargs): |
| 190 |
self._display = Display() |
| 191 |
if not HAS_GOOGLE_CLOUD_COLLECTION: |
| 192 |
raise AnsibleError( |
| 193 |
"""gcp_secret lookup needs a supported version of the google.cloud |
| 194 |
collection installed. Use `ansible-galaxy collection install google.cloud` |
| 195 |
to install it""" |
| 196 |
) |
| 197 |
self.set_options(var_options=variables, direct=kwargs) |
| 198 |
params = { |
| 199 |
"key": self.get_option("key"), |
| 200 |
"location": self.get_option("location"), |
| 201 |
"version": self.get_option("version"), |
| 202 |
"access_token": self.get_option("access_token"), |
| 203 |
"scopes": self.get_option("scopes"), |
| 204 |
"on_error": self.get_option("on_error") |
| 205 |
} |
| 206 |
|
| 207 |
params['name'] = params['key'] |
| 208 |
|
| 209 |
|
| 210 |
for param in ["project", "auth_kind", "service_account_file", "service_account_contents", "service_account_email", "access_token"]: |
| 211 |
params[param] = self.fallback_from_env(param) |
| 212 |
|
| 213 |
self._display.vvv(msg=f"Module Parameters: {params}") |
| 214 |
fake_module = GcpMockModule(params) |
| 215 |
result = self.get_secret(fake_module) |
| 216 |
return [base64.b64decode(result).decode("utf-8")] |
| 217 |
|
| 218 |
def fallback_from_env(self, arg): |
| 219 |
if self.get_option(arg): |
| 220 |
return self.get_option(arg) |
| 221 |
else: |
| 222 |
env_name = f"GCP_{arg.upper()}" |
| 223 |
if env_name in os.environ: |
| 224 |
self.set_option(arg, os.environ[env_name]) |
| 225 |
return self.get_option(arg) |
| 226 |
|
| 227 |
|
| 228 |
|
| 229 |
|
| 230 |
|
| 231 |
def get_latest_version(self, module, auth): |
| 232 |
url = (self.make_url_prefix(module) + "secrets/{name}/versions?filter=state:ENABLED").format( |
| 233 |
**module.params |
| 234 |
) |
| 235 |
response = auth.get(url) |
| 236 |
self._display.vvv(msg=f"List Version Response: {response.status_code} for {response.request.url}: {response.json()}") |
| 237 |
if response.status_code >= 500: |
| 238 |
self.raise_error( |
| 239 |
module, |
| 240 |
f"server error encountered while looking for secret '{module.params['name']}', code: {response.status_code}" |
| 241 |
) |
| 242 |
elif response.status_code >= 400: |
| 243 |
self.raise_error( |
| 244 |
module, |
| 245 |
f"client error encountered while looking for secret '{module.params['name']}', code: {response.status_code}" |
| 246 |
) |
| 247 |
elif response.status_code >= 300: |
| 248 |
self.raise_error( |
| 249 |
module, |
| 250 |
f"unable to list versions for secret '{module.params['name']}', code: {response.status_code}" |
| 251 |
) |
| 252 |
else: |
| 253 |
pass |
| 254 |
version_list = response.json() |
| 255 |
if "versions" in version_list: |
| 256 |
versions_numbers = [] |
| 257 |
for version in version_list['versions']: |
| 258 |
versions_numbers.append(version['name'].split('/')[-1]) |
| 259 |
return sorted(versions_numbers, key=int)[-1] |
| 260 |
else: |
| 261 |
self.raise_error(module, f"Unable to list secret versions via {response.request.url}: {response.json()}") |
| 262 |
|
| 263 |
def raise_error(self, module, msg): |
| 264 |
if module.params['on_error'] == 'strict': |
| 265 |
raise GcpLookupException(msg) |
| 266 |
elif module.params['on_error'] == 'warn': |
| 267 |
self._display.warning(msg) |
| 268 |
|
| 269 |
return None |
| 270 |
|
| 271 |
def get_secret(self, module): |
| 272 |
auth = GcpSession(module, "secretmanager") |
| 273 |
if module.params['version'] == "latest": |
| 274 |
module.params['calc_version'] = self.get_latest_version(module, auth) |
| 275 |
else: |
| 276 |
module.params['calc_version'] = module.params['version'] |
| 277 |
|
| 278 |
|
| 279 |
if module.params['calc_version'] is None: |
| 280 |
return '' |
| 281 |
|
| 282 |
url = (self.make_url_prefix(module) + "secrets/{name}/versions/{calc_version}:access").format( |
| 283 |
**module.params |
| 284 |
) |
| 285 |
response = auth.get(url) |
| 286 |
self._display.vvv(msg=f"Response: {response.status_code} for {response.request.url}: {response.json()}") |
| 287 |
if response.status_code != 200: |
| 288 |
self.raise_error(module, f"Failed to lookup secret value via {response.request.url} {response.status_code}") |
| 289 |
return '' |
| 290 |
|
| 291 |
return response.json()['payload']['data'] |
| 292 |
|
| 293 |
def make_url_prefix(self, module): |
| 294 |
if module.params['location']: |
| 295 |
return "https://secretmanager.{location}.rep.googleapis.com/v1/projects/{project}/locations/{location}/" |
| 296 |
return "https://secretmanager.googleapis.com/v1/projects/{project}/" |