Debian Codegraph @

ansible_collections/community/aws/plugins/modules/s3_bucket_notification.py

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: (c) 2021, Ansible Project
5 # (c) 2019, XLAB d.o.o <www.xlab.si>
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: s3_bucket_notification
11 version_added: 1.0.0
12 short_description: Creates, updates or deletes S3 Bucket notifications targeting Lambda functions, SNS or SQS.
13 description:
14 - This module supports the creation, updates and deletions of S3 bucket notification profiles targeting
15 either Lambda functions, SNS topics or SQS queues.
16 - The target for the notifications must already exist. For lambdas use module M(community.aws.lambda)
17 to manage the lambda function itself, M(community.aws.lambda_alias)
18 to manage function aliases and M(community.aws.lambda_policy) to modify lambda permissions.
19 For SNS or SQS then use M(community.aws.sns_topic) or M(community.aws.sqs_queue).
20 notes:
21 - If using Lambda function as the target then a Lambda policy is also needed, use
22 M(community.aws.lambda_policy) to do so to allow C(lambda:InvokeFunction) for the notification.
23 author:
24 - XLAB d.o.o. (@xlab-si)
25 - Aljaz Kosir (@aljazkosir)
26 - Miha Plesko (@miha-plesko)
27 - Mark Woolley (@marknet15)
28 options:
29 event_name:
30 description:
31 - Unique name for event notification on bucket.
32 required: true
33 type: str
34 bucket_name:
35 description:
36 - S3 bucket name.
37 required: true
38 type: str
39 state:
40 description:
41 - Describes the desired state.
42 default: "present"
43 choices: ["present", "absent"]
44 type: str
45 queue_arn:
46 description:
47 - The ARN of the SQS queue.
48 - Mutually exclusive with I(topic_arn) and I(lambda_function_arn).
49 type: str
50 version_added: 3.2.0
51 topic_arn:
52 description:
53 - The ARN of the SNS topic.
54 - Mutually exclusive with I(queue_arn) and I(lambda_function_arn).
55 type: str
56 version_added: 3.2.0
57 lambda_function_arn:
58 description:
59 - The ARN of the lambda function.
60 - Mutually exclusive with I(queue_arn) and I(topic_arn).
61 aliases: ['function_arn']
62 type: str
63 lambda_alias:
64 description:
65 - Name of the Lambda function alias.
66 - Mutually exclusive with I(lambda_version).
67 type: str
68 lambda_version:
69 description:
70 - Version of the Lambda function.
71 - Mutually exclusive with I(lambda_alias).
72 type: int
73 default: 0
74 events:
75 description:
76 - Events that will be triggering a notification. You can select multiple events to send
77 to the same destination, you can set up different events to send to different destinations,
78 and you can set up a prefix or suffix for an event. However, for each bucket,
79 individual events cannot have multiple configurations with overlapping prefixes or
80 suffixes that could match the same object key.
81 - Required when I(state=present).
82 choices: ['s3:ObjectCreated:*', 's3:ObjectCreated:Put', 's3:ObjectCreated:Post',
83 's3:ObjectCreated:Copy', 's3:ObjectCreated:CompleteMultipartUpload',
84 's3:ObjectRemoved:*', 's3:ObjectRemoved:Delete',
85 's3:ObjectRemoved:DeleteMarkerCreated', 's3:ObjectRestore:Post',
86 's3:ObjectRestore:Completed', 's3:ReducedRedundancyLostObject']
87 type: list
88 elements: str
89 default: []
90 prefix:
91 description:
92 - Optional prefix to limit the notifications to objects with keys that start with matching
93 characters.
94 type: str
95 default: ''
96 suffix:
97 description:
98 - Optional suffix to limit the notifications to objects with keys that end with matching
99 characters.
100 type: str
101 default: ''
102 extends_documentation_fragment:
103 - amazon.aws.common.modules
104 - amazon.aws.region.modules
105 - amazon.aws.boto3
106 """
107
108 EXAMPLES = r"""
109 ---
110 # Examples adding notification target configs to a S3 bucket
111 - name: Setup bucket event notification to a Lambda function
112 community.aws.s3_bucket_notification:
113 state: present
114 event_name: on_file_add_or_remove
115 bucket_name: test-bucket
116 lambda_function_arn: arn:aws:lambda:us-east-2:123456789012:function:test-lambda
117 events: ["s3:ObjectCreated:*", "s3:ObjectRemoved:*"]
118 prefix: images/
119 suffix: .jpg
120
121 - name: Setup bucket event notification to SQS
122 community.aws.s3_bucket_notification:
123 state: present
124 event_name: on_file_add_or_remove
125 bucket_name: test-bucket
126 queue_arn: arn:aws:sqs:us-east-2:123456789012:test-queue
127 events: ["s3:ObjectCreated:*", "s3:ObjectRemoved:*"]
128 prefix: images/
129 suffix: .jpg
130
131 # Example removing an event notification
132 - name: Remove event notification
133 community.aws.s3_bucket_notification:
134 state: absent
135 event_name: on_file_add_or_remove
136 bucket_name: test-bucket
137 """
138
139 RETURN = r"""
140 notification_configuration:
141 description: dictionary of currently applied notifications
142 returned: success
143 type: complex
144 contains:
145 lambda_function_configurations:
146 description:
147 - List of current Lambda function notification configurations applied to the bucket.
148 type: list
149 queue_configurations:
150 description:
151 - List of current SQS notification configurations applied to the bucket.
152 type: list
153 topic_configurations:
154 description:
155 - List of current SNS notification configurations applied to the bucket.
156 type: list
157 """
158
159 try:
160 from botocore.exceptions import BotoCoreError
161 from botocore.exceptions import ClientError
162 except ImportError:
163 pass # will be protected by AnsibleAWSModule
164
165 from ansible.module_utils.common.dict_transformations import camel_dict_to_snake_dict
166
167 from ansible_collections.community.aws.plugins.module_utils.modules import AnsibleCommunityAWSModule as AnsibleAWSModule
168
169
170 class AmazonBucket:
171 def __init__(self, module, client):
172 self.module = module
173 self.client = client
174 self.bucket_name = module.params["bucket_name"]
175 self.check_mode = module.check_mode
176 self._full_config_cache = None
177
178 def full_config(self):
179 if self._full_config_cache is None:
180 self._full_config_cache = dict(
181 QueueConfigurations=[], TopicConfigurations=[], LambdaFunctionConfigurations=[]
182 )
183
184 try:
185 config_lookup = self.client.get_bucket_notification_configuration(Bucket=self.bucket_name)
186 except (ClientError, BotoCoreError) as e:
187 self.module.fail_json(msg=f"{e}")
188
189 # Handle different event targets
190 if config_lookup.get("QueueConfigurations"):
191 for queue_config in config_lookup.get("QueueConfigurations"):
192 self._full_config_cache["QueueConfigurations"].append(Config.from_api(queue_config))
193
194 if config_lookup.get("TopicConfigurations"):
195 for topic_config in config_lookup.get("TopicConfigurations"):
196 self._full_config_cache["TopicConfigurations"].append(Config.from_api(topic_config))
197
198 if config_lookup.get("LambdaFunctionConfigurations"):
199 for function_config in config_lookup.get("LambdaFunctionConfigurations"):
200 self._full_config_cache["LambdaFunctionConfigurations"].append(Config.from_api(function_config))
201
202 return self._full_config_cache
203
204 def current_config(self, config_name):
205 # Iterate through configs and get current event config
206 for target_configs in self.full_config():
207 for config in self.full_config()[target_configs]:
208 if config.raw["Id"] == config_name:
209 return config
210
211 def apply_config(self, desired):
212 configs = dict(QueueConfigurations=[], TopicConfigurations=[], LambdaFunctionConfigurations=[])
213
214 # Iterate through existing configs then add the desired config
215 for target_configs in self.full_config():
216 for config in self.full_config()[target_configs]:
217 if config.name != desired.raw["Id"]:
218 configs[target_configs].append(config.raw)
219
220 if self.module.params.get("queue_arn"):
221 configs["QueueConfigurations"].append(desired.raw)
222 if self.module.params.get("topic_arn"):
223 configs["TopicConfigurations"].append(desired.raw)
224 if self.module.params.get("lambda_function_arn"):
225 configs["LambdaFunctionConfigurations"].append(desired.raw)
226
227 self._upload_bucket_config(configs)
228 return configs
229
230 def delete_config(self, desired):
231 configs = dict(QueueConfigurations=[], TopicConfigurations=[], LambdaFunctionConfigurations=[])
232
233 # Iterate through existing configs omitting specified config
234 for target_configs in self.full_config():
235 for config in self.full_config()[target_configs]:
236 if config.name != desired.raw["Id"]:
237 configs[target_configs].append(config.raw)
238
239 self._upload_bucket_config(configs)
240 return configs
241
242 def _upload_bucket_config(self, configs):
243 api_params = dict(Bucket=self.bucket_name, NotificationConfiguration=dict())
244
245 # Iterate through available configs
246 for target_configs in configs:
247 if len(configs[target_configs]) > 0:
248 api_params["NotificationConfiguration"][target_configs] = configs[target_configs]
249
250 if not self.check_mode:
251 try:
252 self.client.put_bucket_notification_configuration(**api_params)
253 except (ClientError, BotoCoreError) as e:
254 self.module.fail_json(msg=f"{e}")
255
256
257 class Config:
258 def __init__(self, content):
259 self._content = content
260 self.name = content.get("Id")
261
262 @property
263 def raw(self):
264 return self._content
265
266 def __eq__(self, other):
267 if other:
268 return self.raw == other.raw
269 return False
270
271 @classmethod
272 def from_params(cls, **params):
273 """Generate bucket notification params for target"""
274
275 bucket_event_params = dict(
276 Id=params["event_name"],
277 Events=sorted(params["events"]),
278 Filter=dict(
279 Key=dict(
280 FilterRules=[
281 dict(Name="Prefix", Value=params["prefix"]),
282 dict(Name="Suffix", Value=params["suffix"]),
283 ]
284 )
285 ),
286 )
287
288 # Handle different event targets
289 if params.get("queue_arn"):
290 bucket_event_params["QueueArn"] = params["queue_arn"]
291 if params.get("topic_arn"):
292 bucket_event_params["TopicArn"] = params["topic_arn"]
293 if params.get("lambda_function_arn"):
294 function_arn = params["lambda_function_arn"]
295
296 qualifier = None
297 if params["lambda_version"] > 0:
298 qualifier = str(params["lambda_version"])
299 elif params["lambda_alias"]:
300 qualifier = str(params["lambda_alias"])
301 if qualifier:
302 params["lambda_function_arn"] = f"{function_arn}:{qualifier}"
303
304 bucket_event_params["LambdaFunctionArn"] = params["lambda_function_arn"]
305
306 return cls(bucket_event_params)
307
308 @classmethod
309 def from_api(cls, config):
310 return cls(config)
311
312
313 def setup_module_object():
314 event_types = [
315 "s3:ObjectCreated:*",
316 "s3:ObjectCreated:Put",
317 "s3:ObjectCreated:Post",
318 "s3:ObjectCreated:Copy",
319 "s3:ObjectCreated:CompleteMultipartUpload",
320 "s3:ObjectRemoved:*",
321 "s3:ObjectRemoved:Delete",
322 "s3:ObjectRemoved:DeleteMarkerCreated",
323 "s3:ObjectRestore:Post",
324 "s3:ObjectRestore:Completed",
325 "s3:ReducedRedundancyLostObject",
326 ]
327
328 argument_spec = dict(
329 state=dict(default="present", choices=["present", "absent"]),
330 event_name=dict(required=True),
331 lambda_function_arn=dict(aliases=["function_arn"]),
332 queue_arn=dict(type="str"),
333 topic_arn=dict(type="str"),
334 bucket_name=dict(required=True),
335 events=dict(type="list", default=[], choices=event_types, elements="str"),
336 prefix=dict(default=""),
337 suffix=dict(default=""),
338 lambda_alias=dict(),
339 lambda_version=dict(type="int", default=0),
340 )
341
342 mutually_exclusive = [
343 ["queue_arn", "topic_arn", "lambda_function_arn"],
344 ["lambda_alias", "lambda_version"],
345 ]
346
347 return AnsibleAWSModule(
348 argument_spec=argument_spec,
349 supports_check_mode=True,
350 mutually_exclusive=mutually_exclusive,
351 required_if=[["state", "present", ["events"]]],
352 )
353
354
355 def main():
356 module = setup_module_object()
357
358 client = module.client("s3")
359 bucket = AmazonBucket(module, client)
360 current = bucket.current_config(module.params["event_name"])
361 desired = Config.from_params(**module.params)
362
363 notification_configs = dict(QueueConfigurations=[], TopicConfigurations=[], LambdaFunctionConfigurations=[])
364
365 for target_configs in bucket.full_config():
366 for cfg in bucket.full_config()[target_configs]:
367 notification_configs[target_configs].append(camel_dict_to_snake_dict(cfg.raw))
368
369 state = module.params["state"]
370 updated_configuration = dict()
371 changed = False
372
373 if state == "present":
374 if current != desired:
375 updated_configuration = bucket.apply_config(desired)
376 changed = True
377 elif state == "absent":
378 if current:
379 updated_configuration = bucket.delete_config(desired)
380 changed = True
381
382 for target_configs in updated_configuration:
383 notification_configs[target_configs] = []
384 for cfg in updated_configuration.get(target_configs, list()):
385 notification_configs[target_configs].append(camel_dict_to_snake_dict(cfg))
386
387 module.exit_json(changed=changed, notification_configuration=camel_dict_to_snake_dict(notification_configs))
388
389
390 if __name__ == "__main__":
391 main()