| 1 |
# -*- coding: utf-8 -*- |
| 2 |
|
| 3 |
# Copyright: (c) 2018, Aaron Smith <[email protected]> |
| 4 |
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 5 |
|
| 6 |
DOCUMENTATION = r""" |
| 7 |
name: secretsmanager_secret |
| 8 |
author: |
| 9 |
- Aaron Smith (!UNKNOWN) <[email protected]> |
| 10 |
|
| 11 |
short_description: Look up secrets stored in AWS Secrets Manager |
| 12 |
description: |
| 13 |
- Look up secrets stored in AWS Secrets Manager provided the caller |
| 14 |
has the appropriate permissions to read the secret. |
| 15 |
- Lookup is based on the secret's I(Name) value. |
| 16 |
- Optional parameters can be passed into this lookup; O(version_id) and O(version_stage). |
| 17 |
- Prior to release 6.0.0 this module was known as C(aws_ssm), the usage remains the same. |
| 18 |
|
| 19 |
options: |
| 20 |
_terms: |
| 21 |
description: Name of the secret to look up in AWS Secrets Manager. |
| 22 |
required: true |
| 23 |
bypath: |
| 24 |
description: A boolean to indicate whether the parameter is provided as a hierarchy. |
| 25 |
default: false |
| 26 |
type: bool |
| 27 |
version_added: 1.4.0 |
| 28 |
nested: |
| 29 |
description: A boolean to indicate the secret contains nested values. |
| 30 |
type: bool |
| 31 |
default: false |
| 32 |
version_added: 1.4.0 |
| 33 |
version_id: |
| 34 |
description: Version of the secret(s). |
| 35 |
required: false |
| 36 |
version_stage: |
| 37 |
description: Stage of the secret version. |
| 38 |
required: false |
| 39 |
join: |
| 40 |
description: |
| 41 |
- Join two or more entries to form an extended secret. |
| 42 |
- This is useful for overcoming the 4096 character limit imposed by AWS. |
| 43 |
- No effect when used with O(bypath). |
| 44 |
type: bool |
| 45 |
default: false |
| 46 |
on_deleted: |
| 47 |
description: |
| 48 |
- Action to take if the secret has been marked for deletion. |
| 49 |
- V(error) will raise a fatal error when the secret has been marked for deletion. |
| 50 |
- V(skip) will silently ignore the deleted secret. |
| 51 |
- V(warn) will skip over the deleted secret but issue a warning. |
| 52 |
default: "error" |
| 53 |
type: str |
| 54 |
choices: ["error", "skip", "warn"] |
| 55 |
version_added: 2.0.0 |
| 56 |
on_missing: |
| 57 |
description: |
| 58 |
- Action to take if the secret is missing. |
| 59 |
- C(error) will raise a fatal error when the secret is missing. |
| 60 |
- C(skip) will silently ignore the missing secret. |
| 61 |
- C(warn) will skip over the missing secret but issue a warning. |
| 62 |
default: "error" |
| 63 |
type: str |
| 64 |
choices: ["error", "skip", "warn"] |
| 65 |
on_denied: |
| 66 |
description: |
| 67 |
- Action to take if access to the secret is denied. |
| 68 |
- C(error) will raise a fatal error when access to the secret is denied. |
| 69 |
- C(skip) will silently ignore the denied secret. |
| 70 |
- C(warn) will skip over the denied secret but issue a warning. |
| 71 |
default: "error" |
| 72 |
type: str |
| 73 |
choices: ["error", "skip", "warn"] |
| 74 |
extends_documentation_fragment: |
| 75 |
- amazon.aws.boto3 |
| 76 |
- amazon.aws.common.plugins |
| 77 |
- amazon.aws.region.plugins |
| 78 |
""" |
| 79 |
|
| 80 |
EXAMPLES = r""" |
| 81 |
- name: Lookup secretsmanager secret in the current region |
| 82 |
ansible.builtin.debug: msg="{{ lookup('amazon.aws.aws_secret', '/path/to/secrets', bypath=true) }}" |
| 83 |
|
| 84 |
- name: Create RDS instance with aws_secret lookup for password param |
| 85 |
amazon.aws.rds_instance: |
| 86 |
state: present |
| 87 |
db_instance_identifier: app-db |
| 88 |
engine: mysql |
| 89 |
instance_type: db.m1.small |
| 90 |
username: dbadmin |
| 91 |
password: "{{ lookup('amazon.aws.aws_secret', 'DbSecret') }}" |
| 92 |
tags: |
| 93 |
Environment: staging |
| 94 |
|
| 95 |
- name: Skip if secret does not exist |
| 96 |
ansible.builtin.debug: msg="{{ lookup('amazon.aws.aws_secret', 'secret-not-exist', on_missing='skip')}}" |
| 97 |
|
| 98 |
- name: Warn if access to the secret is denied |
| 99 |
ansible.builtin.debug: msg="{{ lookup('amazon.aws.aws_secret', 'secret-denied', on_denied='warn')}}" |
| 100 |
|
| 101 |
- name: Lookup secretsmanager secret in the current region using the nested feature |
| 102 |
ansible.builtin.debug: msg="{{ lookup('amazon.aws.aws_secret', 'secrets.environments.production.password', nested=true) }}" |
| 103 |
# The secret can be queried using the following syntax: `aws_secret_object_name.key1.key2.key3`. |
| 104 |
# If an object is of the form `{"key1":{"key2":{"key3":1}}}` the query would return the value `1`. |
| 105 |
- name: Lookup secretsmanager secret in a specific region using specified region and aws profile using nested feature |
| 106 |
ansible.builtin.debug: > |
| 107 |
msg="{{ lookup('amazon.aws.aws_secret', 'secrets.environments.production.password', region=region, profile=aws_profile, |
| 108 |
access_key=aws_access_key, secret_key=aws_secret_key, nested=true) }}" |
| 109 |
# The secret can be queried using the following syntax: `aws_secret_object_name.key1.key2.key3`. |
| 110 |
# If an object is of the form `{"key1":{"key2":{"key3":1}}}` the query would return the value `1`. |
| 111 |
# Region is the AWS region where the AWS secret is stored. |
| 112 |
# AWS_profile is the aws profile to use, that has access to the AWS secret. |
| 113 |
""" |
| 114 |
|
| 115 |
RETURN = r""" |
| 116 |
_raw: |
| 117 |
description: Returns the value of the secret stored in AWS Secrets Manager. |
| 118 |
""" |
| 119 |
|
| 120 |
import json |
| 121 |
|
| 122 |
try: |
| 123 |
import botocore |
| 124 |
except ImportError: |
| 125 |
pass # Handled by AWSLookupBase |
| 126 |
|
| 127 |
from ansible.errors import AnsibleLookupError |
| 128 |
from ansible.module_utils.common.text.converters import to_native |
| 129 |
|
| 130 |
from ansible_collections.amazon.aws.plugins.module_utils.botocore import is_boto3_error_code |
| 131 |
from ansible_collections.amazon.aws.plugins.module_utils.botocore import is_boto3_error_message |
| 132 |
from ansible_collections.amazon.aws.plugins.module_utils.retries import AWSRetry |
| 133 |
from ansible_collections.amazon.aws.plugins.plugin_utils.lookup import AWSLookupBase |
| 134 |
|
| 135 |
|
| 136 |
def _list_secrets(client, term): |
| 137 |
paginator = client.get_paginator("list_secrets") |
| 138 |
return paginator.paginate(Filters=[{"Key": "name", "Values": [term]}]) |
| 139 |
|
| 140 |
|
| 141 |
class LookupModule(AWSLookupBase): |
| 142 |
def run(self, terms, variables, **kwargs): |
| 143 |
""" |
| 144 |
:arg terms: a list of lookups to run. |
| 145 |
e.g. ['example_secret_name', 'example_secret_too' ] |
| 146 |
:variables: ansible variables active at the time of the lookup |
| 147 |
:returns: A list of parameter values or a list of dictionaries if bypath=True. |
| 148 |
""" |
| 149 |
|
| 150 |
super().run(terms, variables, **kwargs) |
| 151 |
|
| 152 |
on_missing = self.get_option("on_missing") |
| 153 |
on_denied = self.get_option("on_denied") |
| 154 |
on_deleted = self.get_option("on_deleted") |
| 155 |
|
| 156 |
# validate arguments 'on_missing' and 'on_denied' |
| 157 |
if on_missing is not None and ( |
| 158 |
not isinstance(on_missing, str) or on_missing.lower() not in ["error", "warn", "skip"] |
| 159 |
): |
| 160 |
raise AnsibleLookupError( |
| 161 |
f'"on_missing" must be a string and one of "error", "warn" or "skip", not {on_missing}' |
| 162 |
) |
| 163 |
if on_denied is not None and ( |
| 164 |
not isinstance(on_denied, str) or on_denied.lower() not in ["error", "warn", "skip"] |
| 165 |
): |
| 166 |
raise AnsibleLookupError( |
| 167 |
f'"on_denied" must be a string and one of "error", "warn" or "skip", not {on_denied}' |
| 168 |
) |
| 169 |
if on_deleted is not None and ( |
| 170 |
not isinstance(on_deleted, str) or on_deleted.lower() not in ["error", "warn", "skip"] |
| 171 |
): |
| 172 |
raise AnsibleLookupError( |
| 173 |
f'"on_deleted" must be a string and one of "error", "warn" or "skip", not {on_deleted}' |
| 174 |
) |
| 175 |
|
| 176 |
client = self.client("secretsmanager", AWSRetry.jittered_backoff()) |
| 177 |
|
| 178 |
if self.get_option("bypath"): |
| 179 |
secrets = {} |
| 180 |
for term in terms: |
| 181 |
try: |
| 182 |
for secret_wrapper in _list_secrets(client, term): |
| 183 |
if "SecretList" in secret_wrapper: |
| 184 |
for secret_obj in secret_wrapper["SecretList"]: |
| 185 |
secrets.update( |
| 186 |
{ |
| 187 |
secret_obj["Name"]: self.get_secret_value( |
| 188 |
secret_obj["Name"], client, on_missing=on_missing, on_denied=on_denied |
| 189 |
) |
| 190 |
} |
| 191 |
) |
| 192 |
secrets = [secrets] |
| 193 |
|
| 194 |
except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: |
| 195 |
raise AnsibleLookupError(f"Failed to retrieve secret: {to_native(e)}") |
| 196 |
else: |
| 197 |
secrets = [] |
| 198 |
for term in terms: |
| 199 |
value = self.get_secret_value( |
| 200 |
term, |
| 201 |
client, |
| 202 |
version_stage=self.get_option("version_stage"), |
| 203 |
version_id=self.get_option("version_id"), |
| 204 |
on_missing=on_missing, |
| 205 |
on_denied=on_denied, |
| 206 |
on_deleted=on_deleted, |
| 207 |
nested=self.get_option("nested"), |
| 208 |
) |
| 209 |
if value: |
| 210 |
secrets.append(value) |
| 211 |
if self.get_option("join"): |
| 212 |
joined_secret = [] |
| 213 |
joined_secret.append("".join(secrets)) |
| 214 |
return joined_secret |
| 215 |
|
| 216 |
return secrets |
| 217 |
|
| 218 |
def get_secret_value( |
| 219 |
self, |
| 220 |
term, |
| 221 |
client, |
| 222 |
version_stage=None, |
| 223 |
version_id=None, |
| 224 |
on_missing=None, |
| 225 |
on_denied=None, |
| 226 |
on_deleted=None, |
| 227 |
nested=False, |
| 228 |
): |
| 229 |
params = {} |
| 230 |
params["SecretId"] = term |
| 231 |
if version_id: |
| 232 |
params["VersionId"] = version_id |
| 233 |
if version_stage: |
| 234 |
params["VersionStage"] = version_stage |
| 235 |
if nested: |
| 236 |
if len(term.split(".")) < 2: |
| 237 |
raise AnsibleLookupError( |
| 238 |
"Nested query must use the following syntax: `aws_secret_name.<key_name>.<key_name>" |
| 239 |
) |
| 240 |
secret_name = term.split(".")[0] |
| 241 |
params["SecretId"] = secret_name |
| 242 |
|
| 243 |
try: |
| 244 |
response = client.get_secret_value(aws_retry=True, **params) |
| 245 |
if "SecretBinary" in response: |
| 246 |
return response["SecretBinary"] |
| 247 |
if "SecretString" in response: |
| 248 |
if nested: |
| 249 |
query = term.split(".")[1:] |
| 250 |
path = None |
| 251 |
secret_string = json.loads(response["SecretString"]) |
| 252 |
ret_val = secret_string |
| 253 |
while query: |
| 254 |
key = query.pop(0) |
| 255 |
path = key if not path else path + "." + key |
| 256 |
if key in ret_val: |
| 257 |
ret_val = ret_val[key] |
| 258 |
elif on_missing == "warn": |
| 259 |
self._display.warning( |
| 260 |
f"Skipping, Successfully retrieved secret but there exists no key {path} in the secret" |
| 261 |
) |
| 262 |
return None |
| 263 |
elif on_missing == "error": |
| 264 |
raise AnsibleLookupError( |
| 265 |
f"Successfully retrieved secret but there exists no key {path} in the secret" |
| 266 |
) |
| 267 |
return str(ret_val) |
| 268 |
else: |
| 269 |
return response["SecretString"] |
| 270 |
except is_boto3_error_message("marked for deletion"): |
| 271 |
if on_deleted == "error": |
| 272 |
raise AnsibleLookupError(f"Failed to find secret {term} (marked for deletion)") |
| 273 |
elif on_deleted == "warn": |
| 274 |
self._display.warning(f"Skipping, did not find secret (marked for deletion) {term}") |
| 275 |
except is_boto3_error_code("ResourceNotFoundException"): # pylint: disable=duplicate-except |
| 276 |
if on_missing == "error": |
| 277 |
raise AnsibleLookupError(f"Failed to find secret {term} (ResourceNotFound)") |
| 278 |
elif on_missing == "warn": |
| 279 |
self._display.warning(f"Skipping, did not find secret {term}") |
| 280 |
except is_boto3_error_code("AccessDeniedException"): # pylint: disable=duplicate-except |
| 281 |
if on_denied == "error": |
| 282 |
raise AnsibleLookupError(f"Failed to access secret {term} (AccessDenied)") |
| 283 |
elif on_denied == "warn": |
| 284 |
self._display.warning(f"Skipping, access denied for secret {term}") |
| 285 |
except ( |
| 286 |
botocore.exceptions.ClientError, |
| 287 |
botocore.exceptions.BotoCoreError, |
| 288 |
) as e: # pylint: disable=duplicate-except |
| 289 |
raise AnsibleLookupError(f"Failed to retrieve secret: {to_native(e)}") |
| 290 |
|
| 291 |
return None |