Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: (c) 2018, Rob White (@wimnat)
5 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
6
7 DOCUMENTATION = r"""
8 ---
9 module: glue_crawler
10 version_added: 4.1.0
11 short_description: Manage an AWS Glue crawler
12 description:
13 - Manage an AWS Glue crawler. See U(https://aws.amazon.com/glue/) for details.
14 - Prior to release 5.0.0 this module was called C(community.aws.aws_glue_crawler).
15 The usage did not change.
16 author:
17 - 'Ivan Chekaldin (@ichekaldin)'
18 options:
19 database_name:
20 description:
21 - The name of the database where results are written.
22 type: str
23 description:
24 description:
25 - Description of the crawler being defined.
26 type: str
27 name:
28 description:
29 - The name you assign to this crawler definition. It must be unique in your account.
30 required: true
31 type: str
32 recrawl_policy:
33 description:
34 - A policy that specifies whether to crawl the entire dataset again, or to crawl only folders that were added since the last crawler run.
35 suboptions:
36 recrawl_behavior:
37 description:
38 - Specifies whether to crawl the entire dataset again or to crawl only folders that were added since the last crawler run.
39 - Supported options are C(CRAWL_EVERYTHING) and C(CRAWL_NEW_FOLDERS_ONLY).
40 type: str
41 type: dict
42 role:
43 description:
44 - The name or ARN of the IAM role associated with this crawler.
45 - Required when I(state=present).
46 type: str
47 schema_change_policy:
48 description:
49 - The policy for the crawler's update and deletion behavior.
50 suboptions:
51 delete_behavior:
52 description:
53 - Defines the deletion behavior when the crawler finds a deleted object.
54 - Supported options are C(LOG), C(DELETE_FROM_DATABASE), and C(DEPRECATE_IN_DATABASE).
55 type: str
56 update_behavior:
57 description:
58 - Defines the update behavior when the crawler finds a changed schema..
59 - Supported options are C(LOG) and C(UPDATE_IN_DATABASE).
60 type: str
61 type: dict
62 state:
63 description:
64 - Create or delete the AWS Glue crawler.
65 required: true
66 choices: [ 'present', 'absent' ]
67 type: str
68 table_prefix:
69 description:
70 - The table prefix used for catalog tables that are created.
71 type: str
72 targets:
73 description:
74 - A list of targets to crawl. See example below.
75 - Required when I(state=present).
76 type: dict
77 extends_documentation_fragment:
78 - amazon.aws.common.modules
79 - amazon.aws.region.modules
80 - amazon.aws.tags
81 - amazon.aws.boto3
82 """
83
84 EXAMPLES = r"""
85 # Note: These examples do not set authentication details, see the AWS Guide for details.
86
87 # Create an AWS Glue crawler
88 - community.aws.glue_crawler:
89 name: my-glue-crawler
90 database_name: my_database
91 role: my-iam-role
92 schema_change_policy:
93 delete_behavior: DELETE_FROM_DATABASE
94 update_behavior: UPDATE_IN_DATABASE
95 recrawl_policy:
96 recrawl_ehavior: CRAWL_EVERYTHING
97 targets:
98 S3Targets:
99 - Path: "s3://my-bucket/prefix/folder/"
100 ConnectionName: my-connection
101 Exclusions:
102 - "**.json"
103 - "**.yml"
104 state: present
105
106 # Delete an AWS Glue crawler
107 - community.aws.glue_crawler:
108 name: my-glue-crawler
109 state: absent
110 """
111
112 RETURN = r"""
113 creation_time:
114 description: The time and date that this crawler definition was created.
115 returned: when state is present
116 type: str
117 sample: '2021-04-01T05:19:58.326000+00:00'
118 database_name:
119 description: The name of the database where results are written.
120 returned: when state is present
121 type: str
122 sample: my_table
123 description:
124 description: Description of the crawler.
125 returned: when state is present
126 type: str
127 sample: My crawler
128 last_updated:
129 description: The time and date that this crawler definition was last updated.
130 returned: when state is present
131 type: str
132 sample: '2021-04-01T05:19:58.326000+00:00'
133 name:
134 description: The name of the AWS Glue crawler.
135 returned: always
136 type: str
137 sample: my-glue-crawler
138 recrawl_policy:
139 description: A policy that specifies whether to crawl the entire dataset again, or to crawl only folders that were added since the last crawler run.
140 returned: when state is present
141 type: complex
142 contains:
143 RecrawlBehavior:
144 description: Whether to crawl the entire dataset again or to crawl only folders that were added since the last crawler run.
145 returned: when state is present
146 type: str
147 sample: CRAWL_EVERYTHING
148 role:
149 description: The name or ARN of the IAM role associated with this crawler.
150 returned: when state is present
151 type: str
152 sample: my-iam-role
153 schema_change_policy:
154 description: The policy for the crawler's update and deletion behavior.
155 returned: when state is present
156 type: complex
157 contains:
158 DeleteBehavior:
159 description: The deletion behavior when the crawler finds a deleted object.
160 returned: when state is present
161 type: str
162 sample: DELETE_FROM_DATABASE
163 UpdateBehavior:
164 description: The update behavior when the crawler finds a changed schema.
165 returned: when state is present
166 type: str
167 sample: UPDATE_IN_DATABASE
168
169 table_prefix:
170 description: The table prefix used for catalog tables that are created.
171 returned: when state is present
172 type: str
173 sample: my_prefix
174 targets:
175 description: A list of targets to crawl.
176 returned: when state is present
177 type: complex
178 contains:
179 S3Targets:
180 description: List of S3 targets.
181 returned: when state is present
182 type: list
183 JdbcTargets:
184 description: List of JDBC targets.
185 returned: when state is present
186 type: list
187 MongoDBTargets:
188 description: List of Mongo DB targets.
189 returned: when state is present
190 type: list
191 DynamoDBTargets:
192 description: List of DynamoDB targets.
193 returned: when state is present
194 type: list
195 CatalogTargets:
196 description: List of catalog targets.
197 returned: when state is present
198 type: list
199 """
200
201 try:
202 import botocore
203 except ImportError:
204 pass # Handled by AnsibleAWSModule
205
206 from ansible.module_utils.common.dict_transformations import camel_dict_to_snake_dict
207 from ansible.module_utils.common.dict_transformations import snake_dict_to_camel_dict
208
209 from ansible_collections.amazon.aws.plugins.module_utils.botocore import is_boto3_error_code
210 from ansible_collections.amazon.aws.plugins.module_utils.iam import get_aws_account_info
211 from ansible_collections.amazon.aws.plugins.module_utils.retries import AWSRetry
212 from ansible_collections.amazon.aws.plugins.module_utils.tagging import compare_aws_tags
213
214 from ansible_collections.community.aws.plugins.module_utils.modules import AnsibleCommunityAWSModule as AnsibleAWSModule
215
216
217 def _get_glue_crawler(connection, module, glue_crawler_name):
218 """
219 Get an AWS Glue crawler based on name. If not found, return None.
220 """
221 try:
222 return connection.get_crawler(aws_retry=True, Name=glue_crawler_name)["Crawler"]
223 except is_boto3_error_code("EntityNotFoundException"):
224 return None
225 except (
226 botocore.exceptions.ClientError,
227 botocore.exceptions.BotoCoreError,
228 ) as e: # pylint: disable=duplicate-except
229 module.fail_json_aws(e)
230
231
232 def _trim_targets(targets):
233 return [_trim_target(t) for t in targets]
234
235
236 def _trim_target(target):
237 """
238 Some target types have optional parameters which AWS will fill in and return
239 To compare the desired targets and the current targets we need to ignore the defaults
240 """
241 if not target:
242 return None
243 retval = target.copy()
244 if not retval.get("Exclusions", None):
245 retval.pop("Exclusions", None)
246 return retval
247
248
249 def _compare_glue_crawler_params(user_params, current_params):
250 """
251 Compare Glue crawler params. If there is a difference, return True immediately else return False
252 """
253 if "DatabaseName" in user_params and user_params["DatabaseName"] != current_params["DatabaseName"]:
254 return True
255 if "Description" in user_params and user_params["Description"] != current_params["Description"]:
256 return True
257 if "RecrawlPolicy" in user_params and user_params["RecrawlPolicy"] != current_params["RecrawlPolicy"]:
258 return True
259 if "Role" in user_params and user_params["Role"] != current_params["Role"]:
260 return True
261 if (
262 "SchemaChangePolicy" in user_params
263 and user_params["SchemaChangePolicy"] != current_params["SchemaChangePolicy"]
264 ):
265 return True
266 if "TablePrefix" in user_params and user_params["TablePrefix"] != current_params["TablePrefix"]:
267 return True
268 if "Targets" in user_params:
269 if "S3Targets" in user_params["Targets"]:
270 if _trim_targets(user_params["Targets"]["S3Targets"]) != _trim_targets(
271 current_params["Targets"]["S3Targets"]
272 ):
273 return True
274 if (
275 "JdbcTargets" in user_params["Targets"]
276 and user_params["Targets"]["JdbcTargets"] != current_params["Targets"]["JdbcTargets"]
277 ):
278 if _trim_targets(user_params["Targets"]["JdbcTargets"]) != _trim_targets(
279 current_params["Targets"]["JdbcTargets"]
280 ):
281 return True
282 if (
283 "MongoDBTargets" in user_params["Targets"]
284 and user_params["Targets"]["MongoDBTargets"] != current_params["Targets"]["MongoDBTargets"]
285 ):
286 return True
287 if (
288 "DynamoDBTargets" in user_params["Targets"]
289 and user_params["Targets"]["DynamoDBTargets"] != current_params["Targets"]["DynamoDBTargets"]
290 ):
291 return True
292 if (
293 "CatalogTargets" in user_params["Targets"]
294 and user_params["Targets"]["CatalogTargets"] != current_params["Targets"]["CatalogTargets"]
295 ):
296 return True
297
298 return False
299
300
301 def ensure_tags(connection, module, glue_crawler):
302 changed = False
303
304 if module.params.get("tags") is None:
305 return False
306
307 account_id, partition = get_aws_account_info(module)
308 arn = f"arn:{partition}:glue:{module.region}:{account_id}:crawler/{module.params.get('name')}"
309
310 try:
311 existing_tags = connection.get_tags(aws_retry=True, ResourceArn=arn).get("Tags", {})
312 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
313 if module.check_mode:
314 existing_tags = {}
315 else:
316 module.fail_json_aws(e, msg=f"Unable to get tags for Glue crawler {module.params.get('name')}")
317
318 tags_to_add, tags_to_remove = compare_aws_tags(
319 existing_tags, module.params.get("tags"), module.params.get("purge_tags")
320 )
321
322 if tags_to_remove:
323 changed = True
324 if not module.check_mode:
325 try:
326 connection.untag_resource(aws_retry=True, ResourceArn=arn, TagsToRemove=tags_to_remove)
327 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
328 module.fail_json_aws(e, msg=f"Unable to set tags for Glue crawler {module.params.get('name')}")
329
330 if tags_to_add:
331 changed = True
332 if not module.check_mode:
333 try:
334 connection.tag_resource(aws_retry=True, ResourceArn=arn, TagsToAdd=tags_to_add)
335 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
336 module.fail_json_aws(e, msg=f"Unable to set tags for Glue crawler {module.params.get('name')}")
337
338 return changed
339
340
341 def create_or_update_glue_crawler(connection, module, glue_crawler):
342 """
343 Create or update an AWS Glue crawler
344 """
345
346 changed = False
347 params = dict()
348 params["Name"] = module.params.get("name")
349 params["Role"] = module.params.get("role")
350 params["Targets"] = module.params.get("targets")
351 if module.params.get("database_name") is not None:
352 params["DatabaseName"] = module.params.get("database_name")
353 if module.params.get("description") is not None:
354 params["Description"] = module.params.get("description")
355 if module.params.get("recrawl_policy") is not None:
356 params["RecrawlPolicy"] = snake_dict_to_camel_dict(module.params.get("recrawl_policy"), capitalize_first=True)
357 if module.params.get("role") is not None:
358 params["Role"] = module.params.get("role")
359 if module.params.get("schema_change_policy") is not None:
360 params["SchemaChangePolicy"] = snake_dict_to_camel_dict(
361 module.params.get("schema_change_policy"), capitalize_first=True
362 )
363 if module.params.get("table_prefix") is not None:
364 params["TablePrefix"] = module.params.get("table_prefix")
365 if module.params.get("targets") is not None:
366 params["Targets"] = module.params.get("targets")
367
368 if glue_crawler:
369 if _compare_glue_crawler_params(params, glue_crawler):
370 try:
371 if not module.check_mode:
372 connection.update_crawler(aws_retry=True, **params)
373 changed = True
374 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
375 module.fail_json_aws(e)
376 else:
377 try:
378 if not module.check_mode:
379 connection.create_crawler(aws_retry=True, **params)
380 changed = True
381 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
382 module.fail_json_aws(e)
383
384 glue_crawler = _get_glue_crawler(connection, module, params["Name"])
385
386 changed |= ensure_tags(connection, module, glue_crawler)
387
388 module.exit_json(
389 changed=changed,
390 **camel_dict_to_snake_dict(glue_crawler or {}, ignore_list=["SchemaChangePolicy", "RecrawlPolicy", "Targets"]),
391 )
392
393
394 def delete_glue_crawler(connection, module, glue_crawler):
395 """
396 Delete an AWS Glue crawler
397 """
398 changed = False
399
400 if glue_crawler:
401 try:
402 if not module.check_mode:
403 connection.delete_crawler(aws_retry=True, Name=glue_crawler["Name"])
404 changed = True
405 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
406 module.fail_json_aws(e)
407
408 module.exit_json(changed=changed)
409
410
411 def main():
412 argument_spec = dict(
413 database_name=dict(type="str"),
414 description=dict(type="str"),
415 name=dict(required=True, type="str"),
416 purge_tags=dict(type="bool", default=True),
417 recrawl_policy=dict(type="dict", options=dict(recrawl_behavior=dict(type="str"))),
418 role=dict(type="str"),
419 schema_change_policy=dict(
420 type="dict", options=dict(delete_behavior=dict(type="str"), update_behavior=dict(type="str"))
421 ),
422 state=dict(required=True, choices=["present", "absent"], type="str"),
423 table_prefix=dict(type="str"),
424 tags=dict(type="dict", aliases=["resource_tags"]),
425 targets=dict(type="dict"),
426 )
427
428 module = AnsibleAWSModule(
429 argument_spec=argument_spec,
430 required_if=[("state", "present", ["role", "targets"])],
431 supports_check_mode=True,
432 )
433
434 connection = module.client("glue", retry_decorator=AWSRetry.jittered_backoff(retries=10))
435
436 state = module.params.get("state")
437
438 glue_crawler = _get_glue_crawler(connection, module, module.params.get("name"))
439
440 if state == "present":
441 create_or_update_glue_crawler(connection, module, glue_crawler)
442 else:
443 delete_glue_crawler(connection, module, glue_crawler)
444
445
446 if __name__ == "__main__":
447 main()