Debian Codegraph @

ansible_collections/amazon/aws/plugins/modules/lambda_policy.py

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright (c) 2016, Pierre Jodouin <[email protected]>
5 # Copyright (c) 2017 Ansible Project
6 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
7
8 DOCUMENTATION = r"""
9 ---
10 module: lambda_policy
11 version_added: 5.0.0
12 short_description: Creates, updates or deletes AWS Lambda policy statements.
13 description:
14 - This module allows the management of AWS Lambda policy statements.
15 - It is idempotent and supports "Check" mode.
16 - Use module M(amazon.aws.lambda) to manage the lambda function itself, M(amazon.aws.lambda_alias) to manage function aliases,
17 M(amazon.aws.lambda_event) to manage event source mappings such as Kinesis streams, M(community.aws.execute_lambda) to execute a
18 lambda function and M(amazon.aws.lambda_info) to gather information relating to one or more lambda functions.
19 - This module was originally added to C(community.aws) in release 1.0.0.
20 author:
21 - Pierre Jodouin (@pjodouin)
22 - Michael De La Rue (@mikedlr)
23 options:
24 function_name:
25 description:
26 - "Name of the Lambda function whose resource policy you are updating by adding a new permission."
27 - "You can specify a function name (for example, Thumbnail ) or you can specify Amazon Resource Name (ARN) of the"
28 - "function (for example, V(arn:aws:lambda:us-west-2:account-id:function:ThumbNail) ). AWS Lambda also allows you to"
29 - "specify partial ARN (for example, V(account-id:Thumbnail) ). Note that the length constraint applies only to the"
30 - "ARN. If you specify only the function name, it is limited to 64 character in length."
31 required: true
32 aliases: ['lambda_function_arn', 'function_arn']
33 type: str
34 state:
35 description:
36 - Describes the desired state.
37 default: "present"
38 choices: ["present", "absent"]
39 type: str
40 alias:
41 description:
42 - Name of the function alias. Mutually exclusive with O(version).
43 type: str
44 version:
45 description:
46 - Version of the Lambda function. Mutually exclusive with O(alias).
47 type: int
48 statement_id:
49 description:
50 - A unique statement identifier.
51 required: true
52 aliases: ['sid']
53 type: str
54 action:
55 description:
56 - "The AWS Lambda action you want to allow in this statement. Each Lambda action is a string starting with
57 lambda: followed by the API name (see Operations ). For example, V(lambda:CreateFunction) . You can use wildcard
58 (V(lambda:*)) to grant permission for all AWS Lambda actions."
59 required: true
60 type: str
61 principal:
62 description:
63 - "The principal who is getting this permission. It can be Amazon S3 service Principal (s3.amazonaws.com ) if
64 you want Amazon S3 to invoke the function, an AWS account ID if you are granting cross-account permission, or
65 any valid AWS service principal such as sns.amazonaws.com. For example, you might want to allow a custom
66 application in another AWS account to push events to AWS Lambda by invoking your function."
67 required: true
68 type: str
69 source_arn:
70 description:
71 - This is optional; however, when granting Amazon S3 permission to invoke your function, you should specify this
72 field with the bucket Amazon Resource Name (ARN) as its value. This ensures that only events generated from
73 the specified bucket can invoke the function.
74 type: str
75 source_account:
76 description:
77 - The AWS account ID (without a hyphen) of the source owner. For example, if O(source_arn) identifies a bucket,
78 then this is the bucket owner's account ID. You can use this additional condition to ensure the bucket you
79 specify is owned by a specific account (it is possible the bucket owner deleted the bucket and some other AWS
80 account created the bucket). You can also use this condition to specify all sources (that is, you don't
81 specify the O(source_arn)) owned by a specific account.
82 type: str
83 event_source_token:
84 description:
85 - Token string representing source ARN or account. Mutually exclusive with O(source_arn) or O(source_account).
86 type: str
87 extends_documentation_fragment:
88 - amazon.aws.common.modules
89 - amazon.aws.region.modules
90 - amazon.aws.boto3
91 """
92
93 EXAMPLES = r"""
94
95 - name: Lambda S3 event notification
96 amazon.aws.lambda_policy:
97 state: present
98 function_name: functionName
99 alias: Dev
100 statement_id: lambda-s3-myBucket-create-data-log
101 action: lambda:InvokeFunction
102 principal: s3.amazonaws.com
103 source_arn: arn:aws:s3:eu-central-1:123456789012:bucketName
104 source_account: 123456789012
105 register: lambda_policy_action
106
107 - name: show results
108 ansible.builtin.debug:
109 var: lambda_policy_action
110 """
111
112 RETURN = r"""
113 ---
114 lambda_policy_action:
115 description: Describes what action was taken.
116 returned: success
117 type: str
118 sample: "added"
119 """
120
121 import json
122 import re
123
124 try:
125 import botocore
126 except ImportError:
127 pass # caught by AnsibleAWSModule
128
129 from ansible.module_utils.common.text.converters import to_native
130
131 from ansible_collections.amazon.aws.plugins.module_utils.botocore import is_boto3_error_code
132 from ansible_collections.amazon.aws.plugins.module_utils.modules import AnsibleAWSModule
133
134
135 def pc(key):
136 """
137 Changes python key into Pascal case equivalent. For example, 'this_function_name' becomes 'ThisFunctionName'.
138
139 :param key:
140 :return:
141 """
142
143 return "".join([token.capitalize() for token in key.split("_")])
144
145
146 def policy_equal(module, current_statement):
147 for param in ("action", "principal", "source_arn", "source_account", "event_source_token"):
148 if module.params.get(param) != current_statement.get(param):
149 return False
150
151 return True
152
153
154 def set_api_params(module, module_params):
155 """
156 Sets module parameters to those expected by the boto3 API.
157
158 :param module:
159 :param module_params:
160 :return:
161 """
162
163 api_params = dict()
164
165 for param in module_params:
166 module_param = module.params.get(param)
167 if module_param is not None:
168 api_params[pc(param)] = module_param
169
170 return api_params
171
172
173 def validate_params(module):
174 """
175 Performs parameter validation beyond the module framework's validation.
176
177 :param module:
178 :return:
179 """
180
181 function_name = module.params["function_name"]
182
183 # validate function name
184 if function_name.startswith("arn:"):
185 if not re.search(r"^[\w\-:]+$", function_name):
186 module.fail_json(
187 msg=f"ARN {function_name} is invalid. ARNs must contain only alphanumeric characters, hyphens and colons.",
188 )
189 if len(function_name) > 140:
190 module.fail_json(msg=f'ARN name "{function_name}" exceeds 140 character limit')
191 else:
192 if not re.search(r"^[\w\-]+$", function_name):
193 module.fail_json(
194 msg=f"Function name {function_name} is invalid. Names must contain only alphanumeric characters and hyphens.",
195 )
196 if len(function_name) > 64:
197 module.fail_json(msg=f'Function name "{function_name}" exceeds 64 character limit')
198
199
200 def get_qualifier(module):
201 """
202 Returns the function qualifier as a version or alias or None.
203
204 :param module:
205 :return:
206 """
207
208 if module.params.get("version") is not None:
209 return to_native(module.params["version"])
210 elif module.params["alias"]:
211 return to_native(module.params["alias"])
212
213 return None
214
215
216 def extract_statement(policy, sid):
217 """return flattened single policy statement from a policy
218
219 If a policy statement is present in the policy extract it and
220 return it in a flattened form. Otherwise return an empty
221 dictionary.
222 """
223 if "Statement" not in policy:
224 return {}
225 policy_statement = {}
226 # Now that we have the policy, check if required permission statement is present and flatten to
227 # simple dictionary if found.
228 for statement in policy["Statement"]:
229 if statement["Sid"] == sid:
230 policy_statement["action"] = statement["Action"]
231 try:
232 policy_statement["principal"] = statement["Principal"]["Service"]
233 except KeyError:
234 pass
235 try:
236 policy_statement["principal"] = statement["Principal"]["AWS"]
237 except KeyError:
238 pass
239 try:
240 policy_statement["source_arn"] = statement["Condition"]["ArnLike"]["AWS:SourceArn"]
241 except KeyError:
242 pass
243 try:
244 policy_statement["source_account"] = statement["Condition"]["StringEquals"]["AWS:SourceAccount"]
245 except KeyError:
246 pass
247 try:
248 policy_statement["event_source_token"] = statement["Condition"]["StringEquals"][
249 "lambda:EventSourceToken"
250 ]
251 except KeyError:
252 pass
253 break
254
255 return policy_statement
256
257
258 def get_policy_statement(module, client):
259 """Checks that policy exists and if so, that statement ID is present or absent.
260
261 :param module:
262 :param client:
263 :return:
264 """
265 sid = module.params["statement_id"]
266
267 # set API parameters
268 api_params = set_api_params(module, ("function_name",))
269 qualifier = get_qualifier(module)
270 if qualifier:
271 api_params.update(Qualifier=qualifier)
272
273 policy_results = None
274 # check if function policy exists
275 try:
276 policy_results = client.get_policy(**api_params)
277 except is_boto3_error_code("ResourceNotFoundException"):
278 return {}
279 except (
280 botocore.exceptions.ClientError,
281 botocore.exceptions.BotoCoreError,
282 ) as e: # pylint: disable=duplicate-except
283 module.fail_json_aws(e, msg="retrieving function policy")
284
285 # get_policy returns a JSON string so must convert to dict before reassigning to its key
286 policy = json.loads(policy_results.get("Policy", "{}"))
287 return extract_statement(policy, sid)
288
289
290 def add_policy_permission(module, client):
291 """
292 Adds a permission statement to the policy.
293
294 :param module:
295 :param aws:
296 :return:
297 """
298
299 changed = False
300
301 # set API parameters
302 params = (
303 "function_name",
304 "statement_id",
305 "action",
306 "principal",
307 "source_arn",
308 "source_account",
309 "event_source_token",
310 )
311 api_params = set_api_params(module, params)
312 qualifier = get_qualifier(module)
313 if qualifier:
314 api_params.update(Qualifier=qualifier)
315
316 if not module.check_mode:
317 try:
318 client.add_permission(**api_params)
319 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
320 module.fail_json_aws(e, msg="adding permission to policy")
321 changed = True
322
323 return changed
324
325
326 def remove_policy_permission(module, client):
327 """
328 Removed a permission statement from the policy.
329
330 :param module:
331 :param aws:
332 :return:
333 """
334
335 changed = False
336
337 # set API parameters
338 api_params = set_api_params(module, ("function_name", "statement_id"))
339 qualifier = get_qualifier(module)
340 if qualifier:
341 api_params.update(Qualifier=qualifier)
342
343 try:
344 if not module.check_mode:
345 client.remove_permission(**api_params)
346 changed = True
347 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
348 module.fail_json_aws(e, msg="removing permission from policy")
349
350 return changed
351
352
353 def manage_state(module, lambda_client):
354 changed = False
355 current_state = "absent"
356 state = module.params["state"]
357 action_taken = "none"
358
359 # check if the policy exists
360 current_policy_statement = get_policy_statement(module, lambda_client)
361 if current_policy_statement:
362 current_state = "present"
363
364 if state == "present":
365 if current_state == "present" and not policy_equal(module, current_policy_statement):
366 remove_policy_permission(module, lambda_client)
367 changed = add_policy_permission(module, lambda_client)
368 action_taken = "updated"
369 if not current_state == "present":
370 changed = add_policy_permission(module, lambda_client)
371 action_taken = "added"
372 elif current_state == "present":
373 # remove the policy statement
374 changed = remove_policy_permission(module, lambda_client)
375 action_taken = "deleted"
376
377 return dict(changed=changed, ansible_facts=dict(lambda_policy_action=action_taken))
378
379
380 def setup_module_object():
381 argument_spec = dict(
382 state=dict(default="present", choices=["present", "absent"]),
383 function_name=dict(required=True, aliases=["lambda_function_arn", "function_arn"]),
384 statement_id=dict(required=True, aliases=["sid"]),
385 alias=dict(),
386 version=dict(type="int"),
387 action=dict(
388 required=True,
389 ),
390 principal=dict(
391 required=True,
392 ),
393 source_arn=dict(),
394 source_account=dict(),
395 event_source_token=dict(no_log=False),
396 )
397
398 return AnsibleAWSModule(
399 argument_spec=argument_spec,
400 supports_check_mode=True,
401 mutually_exclusive=[
402 ["alias", "version"],
403 ["event_source_token", "source_arn"],
404 ["event_source_token", "source_account"],
405 ],
406 )
407
408
409 def main():
410 """
411 Main entry point.
412
413 :return dict: ansible facts
414 """
415
416 module = setup_module_object()
417 client = module.client("lambda")
418 validate_params(module)
419 results = manage_state(module, client)
420
421 module.exit_json(**results)
422
423
424 if __name__ == "__main__":
425 main()