Debian Codegraph @

ansible_collections/amazon/aws/plugins/lookup/ssm_parameter.py

raw
1 # -*- coding: utf-8 -*-
2
3 # (c) 2016, Bill Wang <ozbillwang(at)gmail.com>
4 # (c) 2017, Marat Bakeev <hawara(at)gmail.com>
5 # (c) 2018, Michael De La Rue <siblemitcom.mddlr(at)spamgourmet.com>
6 # (c) 2017 Ansible Project
7 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
8
9 DOCUMENTATION = r"""
10 name: ssm_parameter
11 author:
12 - Bill Wang (!UNKNOWN) <ozbillwang(at)gmail.com>
13 - Marat Bakeev (!UNKNOWN) <hawara(at)gmail.com>
14 - Michael De La Rue (!UNKNOWN) <[email protected]>
15 short_description: gets the value for a SSM parameter or all parameters under a path
16 description:
17 - Get the value for an Amazon Simple Systems Manager parameter or a hierarchy of parameters.
18 The first argument you pass the lookup can either be a parameter name or a hierarchy of
19 parameters. Hierarchies start with a forward slash and end with the parameter name. Up to
20 5 layers may be specified.
21 - If looking up an explicitly listed parameter by name which does not exist then the lookup
22 will generate an error. You can use the C(default) filter to give a default value in
23 this case but must set the O(on_missing) parameter to V(skip) or V(warn). You must
24 also set the second parameter of the C(default) filter to C(true) (see examples below).
25 - When looking up a path for parameters under it a dictionary will be returned for each path.
26 If there is no parameter under that path then the lookup will generate an error.
27 - If the lookup fails due to lack of permissions or due to an AWS client error then the aws_ssm
28 will generate an error. If you want to continue in this case then you will have to set up
29 two ansible tasks, one which sets a variable and ignores failures and one which uses the value
30 of that variable with a default. See the examples below.
31 - Prior to release 6.0.0 this module was known as C(aws_ssm), the usage remains the same.
32
33 options:
34 decrypt:
35 description: A boolean to indicate whether to decrypt the parameter.
36 default: true
37 type: bool
38 bypath:
39 description: A boolean to indicate whether the parameter is provided as a hierarchy.
40 default: false
41 type: bool
42 recursive:
43 description: A boolean to indicate whether to retrieve all parameters within a hierarchy.
44 default: false
45 type: bool
46 shortnames:
47 description:
48 - Indicates whether to return the name only without path if using a parameter hierarchy.
49 - The O(shortnames) and O(droppath) options are mutually exclusive.
50 default: false
51 type: bool
52 droppath:
53 description:
54 - Indicates whether to return the parameter name with the searched parameter heirarchy removed.
55 - The O(shortnames) and O(droppath) options are mutually exclusive.
56 default: false
57 type: bool
58 version_added: 8.2.0
59 on_missing:
60 description:
61 - Action to take if the SSM parameter is missing.
62 - V(error) will raise a fatal error when the SSM parameter is missing.
63 - V(skip) will silently ignore the missing SSM parameter.
64 - V(warn) will skip over the missing SSM parameter but issue a warning.
65 default: "error"
66 type: str
67 choices: ["error", "skip", "warn"]
68 version_added: 2.0.0
69 on_denied:
70 description:
71 - Action to take if access to the SSM parameter is denied.
72 - v(error) will raise a fatal error when access to the SSM parameter is denied.
73 - v(skip) will silently ignore the denied SSM parameter.
74 - v(warn) will skip over the denied SSM parameter but issue a warning.
75 default: "error"
76 type: string
77 choices: ["error", "skip", "warn"]
78 version_added: 2.0.0
79 extends_documentation_fragment:
80 - amazon.aws.boto3
81 - amazon.aws.common.plugins
82 - amazon.aws.region.plugins
83 """
84
85 EXAMPLES = r"""
86 # lookup sample:
87 - name: Lookup ssm parameter store in the current region
88 ansible.builtin.debug: msg="{{ lookup('amazon.aws.aws_ssm', 'Hello' ) }}"
89
90 - name: Lookup ssm parameter store in specified region
91 ansible.builtin.debug: msg="{{ lookup('amazon.aws.aws_ssm', 'Hello', region='us-east-2' ) }}"
92
93 - name: Lookup ssm parameter store without decryption
94 ansible.builtin.debug: msg="{{ lookup('amazon.aws.aws_ssm', 'Hello', decrypt=False ) }}"
95
96 - name: Lookup ssm parameter store using a specified aws profile
97 ansible.builtin.debug: msg="{{ lookup('amazon.aws.aws_ssm', 'Hello', profile='myprofile' ) }}"
98
99 - name: Lookup ssm parameter store using explicit aws credentials
100 ansible.builtin.debug:
101 msg: >-
102 {{ lookup('amazon.aws.aws_ssm', 'Hello', access_key=my_aws_access_key, secret_key=my_aws_secret_key, session_token=my_session_token ) }}"
103
104 - name: Lookup ssm parameter store with all options
105 ansible.builtin.debug: msg="{{ lookup('amazon.aws.aws_ssm', 'Hello', decrypt=false, region='us-east-2', profile='myprofile') }}"
106
107 - name: Lookup ssm parameter and fail if missing
108 ansible.builtin.debug: msg="{{ lookup('amazon.aws.aws_ssm', 'missing-parameter') }}"
109
110 - name: Lookup a key which doesn't exist, returning a default ('root')
111 ansible.builtin.debug: msg="{{ lookup('amazon.aws.aws_ssm', 'AdminID', on_missing="skip") | default('root', true) }}"
112
113 - name: Lookup a key which doesn't exist failing to store it in a fact
114 ansible.builtin.set_fact:
115 temp_secret: "{{ lookup('amazon.aws.aws_ssm', '/NoAccess/hiddensecret') }}"
116 ignore_errors: true
117
118 - name: Show fact default to "access failed" if we don't have access
119 ansible.builtin.debug: msg="{{ 'the secret was:' ~ temp_secret | default('could not access secret') }}"
120
121 - name: Return a dictionary of ssm parameters from a hierarchy path
122 ansible.builtin.debug: msg="{{ lookup('amazon.aws.aws_ssm', '/PATH/to/params', region='ap-southeast-2', bypath=true, recursive=true ) }}"
123
124 - name: Return a dictionary of ssm parameters from a hierarchy path with shortened names (param instead of /PATH/to/params/foo/bar/param)
125 ansible.builtin.debug: msg="{{ lookup('amazon.aws.aws_ssm', '/PATH/to/params', region='ap-southeast-2', shortnames=true, bypath=true, recursive=true ) }}"
126
127 - name: Return a dictionary of ssm parameters from a hierarchy path with the heirarchy path dropped (foo/bar/param instead of /PATH/to/params/foo/bar/param)
128 ansible.builtin.debug: msg="{{ lookup('amazon.aws.aws_ssm', '/PATH/to/params', region='ap-southeast-2', droppath=true, bypath=true, recursive=true ) }}"
129
130 - name: Iterate over a parameter hierarchy (one iteration per parameter)
131 ansible.builtin.debug: msg='Key contains {{ item.key }} , with value {{ item.value }}'
132 loop: "{{ lookup('amazon.aws.aws_ssm', '/demo/', region='ap-southeast-2', bypath=True) | dict2items }}"
133
134 - name: Iterate over multiple paths as dictionaries (one iteration per path)
135 ansible.builtin.debug: msg='Path contains {{ item }}'
136 loop: "{{ lookup('amazon.aws.aws_ssm', '/demo/', '/demo1/', bypath=True)}}"
137
138 - name: Lookup ssm parameter warn if access is denied
139 ansible.builtin.debug: msg="{{ lookup('amazon.aws.aws_ssm', 'missing-parameter', on_denied="warn" ) }}"
140 """
141
142 try:
143 import botocore
144 except ImportError:
145 pass # Handled by AWSLookupBase
146
147 from ansible.errors import AnsibleLookupError
148 from ansible.module_utils.common.text.converters import to_native
149 from ansible.utils.display import Display
150
151 from ansible_collections.amazon.aws.plugins.module_utils.botocore import is_boto3_error_code
152 from ansible_collections.amazon.aws.plugins.module_utils.retries import AWSRetry
153 from ansible_collections.amazon.aws.plugins.module_utils.tagging import boto3_tag_list_to_ansible_dict
154 from ansible_collections.amazon.aws.plugins.plugin_utils.lookup import AWSLookupBase
155
156 display = Display()
157
158
159 class LookupModule(AWSLookupBase):
160 def run(self, terms, variables, **kwargs):
161 """
162 :arg terms: a list of lookups to run.
163 e.g. ['parameter_name', 'parameter_name_too' ]
164 :kwarg variables: ansible variables active at the time of the lookup
165 :returns: A list of parameter values or a list of dictionaries if bypath=True.
166 """
167
168 super().run(terms, variables, **kwargs)
169
170 on_missing = self.get_option("on_missing")
171 on_denied = self.get_option("on_denied")
172
173 # validate arguments 'on_missing' and 'on_denied'
174 if on_missing is not None and (
175 not isinstance(on_missing, str) or on_missing.lower() not in ["error", "warn", "skip"]
176 ):
177 raise AnsibleLookupError(
178 f'"on_missing" must be a string and one of "error", "warn" or "skip", not {on_missing}'
179 )
180 if on_denied is not None and (
181 not isinstance(on_denied, str) or on_denied.lower() not in ["error", "warn", "skip"]
182 ):
183 raise AnsibleLookupError(
184 f'"on_denied" must be a string and one of "error", "warn" or "skip", not {on_denied}'
185 )
186
187 if self.get_option("shortnames") and self.get_option("droppath"):
188 raise AnsibleLookupError("shortnames and droppath are mutually exclusive. They cannot both be set to true.")
189
190 ret = []
191 ssm_dict = {}
192
193 client = self.client("ssm", AWSRetry.jittered_backoff())
194
195 ssm_dict["WithDecryption"] = self.get_option("decrypt")
196
197 # Lookup by path
198 if self.get_option("bypath"):
199 ssm_dict["Recursive"] = self.get_option("recursive")
200 for term in terms:
201 display.vvv(f"AWS_ssm path lookup term: {term} in region: {self.region}")
202
203 paramlist = self.get_path_parameters(client, ssm_dict, term, on_missing.lower(), on_denied.lower())
204 # Shorten parameter names. Yes, this will return
205 # duplicate names with different values.
206 if self.get_option("shortnames"):
207 for x in paramlist:
208 x["Name"] = x["Name"][x["Name"].rfind("/") + 1:] # fmt: skip
209
210 if self.get_option("droppath"):
211 for x in paramlist:
212 x["Name"] = x["Name"].replace(ssm_dict["Path"], "")
213
214 display.vvvv(f"aws_ssm path lookup returned: {to_native(paramlist)}")
215
216 ret.append(
217 boto3_tag_list_to_ansible_dict(paramlist, tag_name_key_name="Name", tag_value_key_name="Value")
218 )
219 # Lookup by parameter name - always returns a list with one or
220 # no entry.
221 else:
222 display.vvv(f"aws_ssm name lookup term: {terms}")
223 for term in terms:
224 ret.append(self.get_parameter_value(client, ssm_dict, term, on_missing.lower(), on_denied.lower()))
225 display.vvvv(f"aws_ssm path lookup returning: {to_native(ret)} ")
226 return ret
227
228 def get_path_parameters(self, client, ssm_dict, term, on_missing, on_denied):
229 ssm_dict["Path"] = term
230 paginator = client.get_paginator("get_parameters_by_path")
231 try:
232 paramlist = paginator.paginate(**ssm_dict).build_full_result()["Parameters"]
233 except is_boto3_error_code("AccessDeniedException"):
234 if on_denied == "error":
235 raise AnsibleLookupError(f"Failed to access SSM parameter path {term} (AccessDenied)")
236 elif on_denied == "warn":
237 self.warn(f"Skipping, access denied for SSM parameter path {term}")
238 paramlist = [{}]
239 elif on_denied == "skip":
240 paramlist = [{}]
241 except botocore.exceptions.ClientError as e: # pylint: disable=duplicate-except
242 raise AnsibleLookupError(f"SSM lookup exception: {to_native(e)}")
243
244 if not len(paramlist):
245 if on_missing == "error":
246 raise AnsibleLookupError(f"Failed to find SSM parameter path {term} (ResourceNotFound)")
247 elif on_missing == "warn":
248 self.warn(f"Skipping, did not find SSM parameter path {term}")
249
250 return paramlist
251
252 def get_parameter_value(self, client, ssm_dict, term, on_missing, on_denied):
253 ssm_dict["Name"] = term
254 try:
255 response = client.get_parameter(aws_retry=True, **ssm_dict)
256 return response["Parameter"]["Value"]
257 except is_boto3_error_code("ParameterNotFound"):
258 if on_missing == "error":
259 raise AnsibleLookupError(f"Failed to find SSM parameter {term} (ResourceNotFound)")
260 elif on_missing == "warn":
261 self.warn(f"Skipping, did not find SSM parameter {term}")
262 except is_boto3_error_code("AccessDeniedException"): # pylint: disable=duplicate-except
263 if on_denied == "error":
264 raise AnsibleLookupError(f"Failed to access SSM parameter {term} (AccessDenied)")
265 elif on_denied == "warn":
266 self.warn(f"Skipping, access denied for SSM parameter {term}")
267 except botocore.exceptions.ClientError as e: # pylint: disable=duplicate-except
268 raise AnsibleLookupError(f"SSM lookup exception: {to_native(e)}")
269 return None