Debian Codegraph @

ansible_collections/community/general/plugins/modules/maven_artifact.py

raw
1 #!/usr/bin/python
2
3 # Copyright (c) 2014, Chris Schmidt <chris.schmidt () contrastsecurity.com>
4 #
5 # Built using https://github.com/hamnis/useful-scripts/blob/master/python/download-maven-artifact
6 # as a reference and starting point.
7 #
8 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
9 # SPDX-License-Identifier: GPL-3.0-or-later
10 from __future__ import annotations
11
12 DOCUMENTATION = r"""
13 module: maven_artifact
14 short_description: Downloads an Artifact from a Maven Repository
15 description:
16 - Downloads an artifact from a maven repository given the maven coordinates provided to the module.
17 - Can retrieve snapshots or release versions of the artifact and resolve the latest available version if one is not available.
18 author: "Chris Schmidt (@chrisisbeef)"
19 requirements:
20 - lxml
21 - boto if using a S3 repository (V(s3://...))
22 attributes:
23 check_mode:
24 support: none
25 diff_mode:
26 support: none
27 options:
28 group_id:
29 type: str
30 description:
31 - The Maven groupId coordinate.
32 required: true
33 artifact_id:
34 type: str
35 description:
36 - The maven artifactId coordinate.
37 required: true
38 version:
39 type: str
40 description:
41 - The maven version coordinate.
42 - Mutually exclusive with O(version_by_spec).
43 version_by_spec:
44 type: str
45 description:
46 - The maven dependency version ranges.
47 - See supported version ranges on U(https://cwiki.apache.org/confluence/display/MAVENOLD/Dependency+Mediation+and+Conflict+Resolution).
48 - The range type V((,1.0],[1.2,\)) and V((,1.1\),(1.1,\)) is not supported.
49 - Mutually exclusive with O(version).
50 version_added: '0.2.0'
51 classifier:
52 type: str
53 description:
54 - The maven classifier coordinate.
55 default: ''
56 extension:
57 type: str
58 description:
59 - The maven type/extension coordinate.
60 default: jar
61 repository_url:
62 type: str
63 description:
64 - The URL of the Maven Repository to download from.
65 - Use V(s3://...) if the repository is hosted on Amazon S3.
66 - Use V(file://...) if the repository is local.
67 default: https://repo1.maven.org/maven2
68 username:
69 type: str
70 description:
71 - The username to authenticate as to the Maven Repository. Use AWS secret key of the repository is hosted on S3.
72 aliases: ["aws_secret_key"]
73 password:
74 type: str
75 description:
76 - The password to authenticate with to the Maven Repository. Use AWS secret access key of the repository is hosted on
77 S3.
78 aliases: ["aws_secret_access_key"]
79 headers:
80 description:
81 - Add custom HTTP headers to a request in hash/dict format.
82 type: dict
83 force_basic_auth:
84 description:
85 - C(httplib2), the library used by the URI module only sends authentication information when a webservice responds to
86 an initial request with a 401 status. Since some basic auth services do not properly send a 401, logins fail. This
87 option forces the sending of the Basic authentication header upon initial request.
88 default: false
89 type: bool
90 version_added: '0.2.0'
91 dest:
92 type: path
93 description:
94 - The path where the artifact should be written to.
95 - If file mode or ownerships are specified and destination path already exists, they affect the downloaded file.
96 required: true
97 state:
98 type: str
99 description:
100 - The desired state of the artifact.
101 default: present
102 choices: [present, absent]
103 timeout:
104 type: int
105 description:
106 - Specifies a timeout in seconds for the connection attempt.
107 default: 10
108 validate_certs:
109 description:
110 - If V(false), SSL certificates are not validated. This should only be set to V(false) when no other option exists.
111 type: bool
112 default: true
113 client_cert:
114 description:
115 - PEM formatted certificate chain file to be used for SSL client authentication.
116 - This file can also include the key as well, and if the key is included, O(client_key) is not required.
117 type: path
118 version_added: '1.3.0'
119 client_key:
120 description:
121 - PEM formatted file that contains your private key to be used for SSL client authentication.
122 - If O(client_cert) contains both the certificate and key, this option is not required.
123 type: path
124 version_added: '1.3.0'
125 keep_name:
126 description:
127 - If V(true), the downloaded artifact's name is preserved, in other words the version number remains part of it.
128 - This option only has effect when O(dest) is a directory and O(version) is set to V(latest) or O(version_by_spec) is
129 defined.
130 type: bool
131 default: false
132 verify_checksum:
133 type: str
134 description:
135 - If V(never), the MD5/SHA1 checksum is never downloaded and verified.
136 - If V(download), the MD5/SHA1 checksum is downloaded and verified only after artifact download. This is the default.
137 - If V(change), the MD5/SHA1 checksum is downloaded and verified if the destination already exist, to verify if they
138 are identical. This was the behaviour before 2.6. Since it downloads the checksum before (maybe) downloading the artifact,
139 and since some repository software, when acting as a proxy/cache, return a 404 error if the artifact has not been
140 cached yet, it may fail unexpectedly. If you still need it, you should consider using V(always) instead - if you deal
141 with a checksum, it is better to use it to verify integrity after download.
142 - V(always) combines V(download) and V(change).
143 default: 'download'
144 choices: ['never', 'download', 'change', 'always']
145 checksum_alg:
146 type: str
147 description:
148 - If V(md5), checksums use the MD5 algorithm. This is the default.
149 - If V(sha1), checksums use the SHA1 algorithm. This can be used on systems configured to use FIPS-compliant algorithms,
150 since MD5 is blocked on such systems.
151 default: 'md5'
152 choices: ['md5', 'sha1']
153 version_added: 3.2.0
154 unredirected_headers:
155 type: list
156 elements: str
157 version_added: 5.2.0
158 description:
159 - A list of headers that should not be included in the redirection. This headers are sent to the C(fetch_url) function.
160 - On ansible-core version 2.12 or later, the default of this option is V([Authorization, Cookie]).
161 - Useful if the redirection URL does not need to have sensitive headers in the request.
162 - Requires ansible-core version 2.12 or later.
163 directory_mode:
164 type: str
165 description:
166 - Filesystem permission mode applied recursively to O(dest) when it is a directory.
167 extends_documentation_fragment:
168 - ansible.builtin.files
169 - community.general._attributes
170 """
171
172 EXAMPLES = r"""
173 - name: Download the latest version of the JUnit framework artifact from Maven Central
174 community.general.maven_artifact:
175 group_id: junit
176 artifact_id: junit
177 dest: /tmp/junit-latest.jar
178
179 - name: Download JUnit 4.11 from Maven Central
180 community.general.maven_artifact:
181 group_id: junit
182 artifact_id: junit
183 version: 4.11
184 dest: /tmp/junit-4.11.jar
185
186 - name: Download an artifact from a private repository requiring authentication
187 community.general.maven_artifact:
188 group_id: com.company
189 artifact_id: library-name
190 repository_url: 'https://repo.company.com/maven'
191 username: user
192 password: pass
193 dest: /tmp/library-name-latest.jar
194
195 - name: Download an artifact from a private repository requiring certificate authentication
196 community.general.maven_artifact:
197 group_id: com.company
198 artifact_id: library-name
199 repository_url: 'https://repo.company.com/maven'
200 client_cert: /path/to/cert.pem
201 client_key: /path/to/key.pem
202 dest: /tmp/library-name-latest.jar
203
204 - name: Download a WAR File to the Tomcat webapps directory to be deployed
205 community.general.maven_artifact:
206 group_id: com.company
207 artifact_id: web-app
208 extension: war
209 repository_url: 'https://repo.company.com/maven'
210 dest: /var/lib/tomcat7/webapps/web-app.war
211
212 - name: Keep a downloaded artifact's name, i.e. retain the version
213 community.general.maven_artifact:
214 version: latest
215 artifact_id: spring-core
216 group_id: org.springframework
217 dest: /tmp/
218 keep_name: true
219
220 - name: Download the latest version of the JUnit framework artifact from Maven local
221 community.general.maven_artifact:
222 group_id: junit
223 artifact_id: junit
224 dest: /tmp/junit-latest.jar
225 repository_url: "file://{{ lookup('env','HOME') }}/.m2/repository"
226
227 - name: Download the latest version between 3.8 and 4.0 (exclusive) of the JUnit framework artifact from Maven Central
228 community.general.maven_artifact:
229 group_id: junit
230 artifact_id: junit
231 version_by_spec: "[3.8,4.0)"
232 dest: /tmp/
233 """
234
235 import hashlib
236 import os
237 import posixpath
238 import re
239 import shutil
240 import tempfile
241 import traceback
242 from re import match
243 from urllib.parse import urlparse
244
245 from ansible.module_utils.ansible_release import __version__ as ansible_version
246
247 LXML_ETREE_IMP_ERR = None
248 try:
249 from lxml import etree
250
251 HAS_LXML_ETREE = True
252 except ImportError:
253 LXML_ETREE_IMP_ERR = traceback.format_exc()
254 HAS_LXML_ETREE = False
255
256 BOTO_IMP_ERR = None
257 try:
258 import boto3
259
260 HAS_BOTO = True
261 except ImportError:
262 BOTO_IMP_ERR = traceback.format_exc()
263 HAS_BOTO = False
264
265 SEMANTIC_VERSION_IMP_ERR = None
266 try:
267 from semantic_version import Spec, Version
268
269 HAS_SEMANTIC_VERSION = True
270 except ImportError:
271 SEMANTIC_VERSION_IMP_ERR = traceback.format_exc()
272 HAS_SEMANTIC_VERSION = False
273
274
275 from ansible.module_utils.basic import AnsibleModule, missing_required_lib
276 from ansible.module_utils.common.text.converters import to_bytes, to_text
277 from ansible.module_utils.urls import fetch_url
278
279
280 def split_pre_existing_dir(dirname):
281 """
282 Return the first pre-existing directory and a list of the new directories that will be created.
283 """
284 head, tail = os.path.split(dirname)
285 b_head = to_bytes(head, errors="surrogate_or_strict")
286 if not os.path.exists(b_head):
287 if head == dirname:
288 return None, [head]
289 else:
290 (pre_existing_dir, new_directory_list) = split_pre_existing_dir(head)
291 else:
292 return head, [tail]
293 new_directory_list.append(tail)
294 return pre_existing_dir, new_directory_list
295
296
297 def adjust_recursive_directory_permissions(pre_existing_dir, new_directory_list, module, directory_args, changed):
298 """
299 Walk the new directories list and make sure that permissions are as we would expect
300 """
301 if new_directory_list:
302 first_sub_dir = new_directory_list.pop(0)
303 if not pre_existing_dir:
304 working_dir = first_sub_dir
305 else:
306 working_dir = os.path.join(pre_existing_dir, first_sub_dir)
307 directory_args["path"] = working_dir
308 changed = module.set_fs_attributes_if_different(directory_args, changed)
309 changed = adjust_recursive_directory_permissions(
310 working_dir, new_directory_list, module, directory_args, changed
311 )
312 return changed
313
314
315 class Artifact:
316 def __init__(self, group_id, artifact_id, version, version_by_spec, classifier="", extension="jar"):
317 if not group_id:
318 raise ValueError("group_id must be set")
319 if not artifact_id:
320 raise ValueError("artifact_id must be set")
321
322 self.group_id = group_id
323 self.artifact_id = artifact_id
324 self.version = version
325 self.version_by_spec = version_by_spec
326 self.classifier = classifier
327
328 if not extension:
329 self.extension = "jar"
330 else:
331 self.extension = extension
332
333 def is_snapshot(self):
334 return self.version and self.version.endswith("SNAPSHOT")
335
336 def path(self, with_version=True):
337 base = posixpath.join(self.group_id.replace(".", "/"), self.artifact_id)
338 if with_version and self.version:
339 timestamp_version_match = re.match("^(.*-)?([0-9]{8}\\.[0-9]{6}-[0-9]+)$", self.version)
340 if timestamp_version_match:
341 base = posixpath.join(base, f"{timestamp_version_match.group(1)}SNAPSHOT")
342 else:
343 base = posixpath.join(base, self.version)
344 return base
345
346 def _generate_filename(self):
347 filename = f"{self.artifact_id}-{self.classifier}.{self.extension}"
348 if not self.classifier:
349 filename = f"{self.artifact_id}.{self.extension}"
350 return filename
351
352 def get_filename(self, filename=None):
353 if not filename:
354 filename = self._generate_filename()
355 elif os.path.isdir(filename):
356 filename = os.path.join(filename, self._generate_filename())
357 return filename
358
359 def __str__(self):
360 result = f"{self.group_id}:{self.artifact_id}:{self.version}"
361 if self.classifier:
362 result = f"{self.group_id}:{self.artifact_id}:{self.extension}:{self.classifier}:{self.version}"
363 elif self.extension != "jar":
364 result = f"{self.group_id}:{self.artifact_id}:{self.extension}:{self.version}"
365 return result
366
367 @staticmethod
368 def parse(input):
369 parts = input.split(":")
370 if len(parts) >= 3:
371 g = parts[0]
372 a = parts[1]
373 v = parts[-1]
374 t = None
375 c = None
376 if len(parts) == 4:
377 t = parts[2]
378 if len(parts) == 5:
379 t = parts[2]
380 c = parts[3]
381 return Artifact(g, a, v, c, t)
382 else:
383 return None
384
385
386 class MavenDownloader:
387 def __init__(self, module, base, local=False, headers=None):
388 self.module = module
389 if base.endswith("/"):
390 base = base.rstrip("/")
391 self.base = base
392 self.local = local
393 self.headers = headers
394 self.user_agent = f"Ansible {ansible_version} maven_artifact"
395 self.latest_version_found = None
396 self.metadata_file_name = "maven-metadata-local.xml" if local else "maven-metadata.xml"
397
398 def find_version_by_spec(self, artifact):
399 path = f"/{artifact.path(False)}/{self.metadata_file_name}"
400 content = self._getContent(self.base + path, f"Failed to retrieve the maven metadata file: {path}")
401 xml = etree.fromstring(content)
402 original_versions = xml.xpath("/metadata/versioning/versions/version/text()")
403 versions = []
404 for version in original_versions:
405 try:
406 versions.append(Version.coerce(version))
407 except ValueError:
408 # This means that version string is not a valid semantic versioning
409 pass
410
411 parse_versions_syntax = {
412 # example -> (,1.0]
413 r"^\(,(?P<upper_bound>[0-9.]*)]$": "<={upper_bound}",
414 # example -> 1.0
415 r"^(?P<version>[0-9.]*)$": "~={version}",
416 # example -> [1.0]
417 r"^\[(?P<version>[0-9.]*)\]$": "=={version}",
418 # example -> [1.2, 1.3]
419 r"^\[(?P<lower_bound>[0-9.]*),\s*(?P<upper_bound>[0-9.]*)\]$": ">={lower_bound},<={upper_bound}",
420 # example -> [1.2, 1.3)
421 r"^\[(?P<lower_bound>[0-9.]*),\s*(?P<upper_bound>[0-9.]+)\)$": ">={lower_bound},<{upper_bound}",
422 # example -> [1.5,)
423 r"^\[(?P<lower_bound>[0-9.]*),\)$": ">={lower_bound}",
424 }
425
426 for regex, spec_format in parse_versions_syntax.items():
427 regex_result = match(regex, artifact.version_by_spec)
428 if regex_result:
429 spec = Spec(spec_format.format(**regex_result.groupdict()))
430 selected_version = spec.select(versions)
431
432 if not selected_version:
433 raise ValueError(f"No version found with this spec version: {artifact.version_by_spec}")
434
435 # To deal when repos on maven don't have patch number on first build (e.g. 3.8 instead of 3.8.0)
436 if str(selected_version) not in original_versions:
437 selected_version.patch = None
438
439 return str(selected_version)
440
441 raise ValueError(f"The spec version {artifact.version_by_spec} is not supported! ")
442
443 def find_latest_version_available(self, artifact):
444 if self.latest_version_found:
445 return self.latest_version_found
446 path = f"/{artifact.path(False)}/{self.metadata_file_name}"
447 content = self._getContent(self.base + path, f"Failed to retrieve the maven metadata file: {path}")
448 xml = etree.fromstring(content)
449 v = xml.xpath("/metadata/versioning/versions/version[last()]/text()")
450 if v:
451 self.latest_version_found = v[0]
452 return v[0]
453
454 def find_uri_for_artifact(self, artifact):
455 if artifact.version_by_spec:
456 artifact.version = self.find_version_by_spec(artifact)
457
458 if artifact.version == "latest":
459 artifact.version = self.find_latest_version_available(artifact)
460
461 if artifact.is_snapshot():
462 if self.local:
463 return self._uri_for_artifact(artifact, artifact.version)
464 path = f"/{artifact.path()}/{self.metadata_file_name}"
465 content = self._getContent(self.base + path, f"Failed to retrieve the maven metadata file: {path}")
466 xml = etree.fromstring(content)
467
468 candidates = []
469 for snapshot_artifact in xml.xpath("/metadata/versioning/snapshotVersions/snapshotVersion"):
470 classifier = snapshot_artifact.xpath("classifier/text()")
471 extension = snapshot_artifact.xpath("extension/text()")
472 if (classifier[0] if classifier else "") == artifact.classifier and (
473 extension[0] if extension else ""
474 ) == artifact.extension:
475 value = snapshot_artifact.xpath("value/text()")
476 updated = snapshot_artifact.xpath("updated/text()")
477 if value:
478 candidates.append((updated[0] if updated else "", value[0]))
479 if candidates:
480 # updated is yyyymmddHHMMSS, so lexical max == newest
481 return self._uri_for_artifact(artifact, max(candidates, key=lambda item: item[0])[1])
482 timestamp_xmlpath = xml.xpath("/metadata/versioning/snapshot/timestamp/text()")
483 build_number_xmlpath = xml.xpath("/metadata/versioning/snapshot/buildNumber/text()")
484 if timestamp_xmlpath and build_number_xmlpath:
485 timestamp = timestamp_xmlpath[0]
486 build_number = build_number_xmlpath[0]
487 return self._uri_for_artifact(
488 artifact, artifact.version.replace("SNAPSHOT", f"{timestamp}-{build_number}")
489 )
490
491 return self._uri_for_artifact(artifact, artifact.version)
492
493 def _uri_for_artifact(self, artifact, version=None):
494 if artifact.is_snapshot() and not version:
495 raise ValueError(f"Expected uniqueversion for snapshot artifact {artifact}")
496 elif not artifact.is_snapshot():
497 version = artifact.version
498 if artifact.classifier:
499 return posixpath.join(
500 self.base,
501 artifact.path(),
502 f"{artifact.artifact_id}-{version}-{artifact.classifier}.{artifact.extension}",
503 )
504
505 return posixpath.join(self.base, artifact.path(), f"{artifact.artifact_id}-{version}.{artifact.extension}")
506
507 # for small files, directly get the full content
508 def _getContent(self, url, failmsg, force=True):
509 if self.local:
510 parsed_url = urlparse(url)
511 if os.path.isfile(parsed_url.path):
512 with open(parsed_url.path, "rb") as f:
513 return f.read()
514 if force:
515 raise ValueError(f"{failmsg} because can not find file: {url}")
516 return None
517 response = self._request(url, failmsg, force)
518 if response:
519 return response.read()
520 return None
521
522 # only for HTTP request
523 def _request(self, url, failmsg, force=True):
524 url_to_use = url
525 parsed_url = urlparse(url)
526
527 if parsed_url.scheme == "s3":
528 parsed_url = urlparse(url)
529 bucket_name = parsed_url.netloc
530 key_name = parsed_url.path[1:]
531 client = boto3.client(
532 "s3",
533 aws_access_key_id=self.module.params.get("username", ""),
534 aws_secret_access_key=self.module.params.get("password", ""),
535 )
536 url_to_use = client.generate_presigned_url(
537 "get_object", Params={"Bucket": bucket_name, "Key": key_name}, ExpiresIn=10
538 )
539
540 req_timeout = self.module.params.get("timeout")
541
542 # Hack to add parameters in the way that fetch_url expects
543 self.module.params["url_username"] = self.module.params.get("username", "")
544 self.module.params["url_password"] = self.module.params.get("password", "")
545 self.module.params["http_agent"] = self.user_agent
546
547 kwargs = {}
548 if self.module.params["unredirected_headers"]:
549 kwargs["unredirected_headers"] = self.module.params["unredirected_headers"]
550
551 response, info = fetch_url(self.module, url_to_use, timeout=req_timeout, headers=self.headers, **kwargs)
552
553 if info["status"] == 200:
554 return response
555 if force:
556 raise ValueError(f"{failmsg} because of {info['msg']}for URL {url_to_use}")
557 return None
558
559 def download(self, tmpdir, artifact, verify_download, filename=None, checksum_alg="md5"):
560 if (not artifact.version and not artifact.version_by_spec) or artifact.version == "latest":
561 artifact = Artifact(
562 artifact.group_id,
563 artifact.artifact_id,
564 self.find_latest_version_available(artifact),
565 None,
566 artifact.classifier,
567 artifact.extension,
568 )
569 url = self.find_uri_for_artifact(artifact)
570 tempfd, tempname = tempfile.mkstemp(dir=tmpdir)
571
572 try:
573 # copy to temp file
574 if self.local:
575 parsed_url = urlparse(url)
576 if os.path.isfile(parsed_url.path):
577 shutil.copy2(parsed_url.path, tempname)
578 else:
579 return f"Can not find local file: {parsed_url.path}"
580 else:
581 response = self._request(url, f"Failed to download artifact {artifact}")
582 with os.fdopen(tempfd, "wb") as f:
583 shutil.copyfileobj(response, f)
584
585 if verify_download:
586 invalid_checksum = self.is_invalid_checksum(tempname, url, checksum_alg)
587 if invalid_checksum:
588 # if verify_change was set, the previous file would be deleted
589 os.remove(tempname)
590 return invalid_checksum
591 except Exception as e:
592 os.remove(tempname)
593 raise e
594
595 # all good, now copy temp file to target
596 shutil.move(tempname, artifact.get_filename(filename))
597 return None
598
599 def is_invalid_checksum(self, file, remote_url, checksum_alg="md5"):
600 if os.path.exists(file):
601 local_checksum = self._local_checksum(checksum_alg, file)
602 if self.local:
603 parsed_url = urlparse(remote_url)
604 remote_checksum = self._local_checksum(checksum_alg, parsed_url.path)
605 else:
606 try:
607 remote_checksum = to_text(
608 self._getContent(f"{remote_url}.{checksum_alg}", "Failed to retrieve checksum", False),
609 errors="strict",
610 )
611 except UnicodeError as e:
612 return f"Cannot retrieve a valid {checksum_alg} checksum from {remote_url}: {e}"
613 if not remote_checksum:
614 return f"Cannot find {checksum_alg} checksum from {remote_url}"
615 try:
616 # Check if remote checksum only contains md5/sha1 or md5/sha1 + filename
617 _remote_checksum = remote_checksum.split(None, 1)[0]
618 remote_checksum = _remote_checksum
619 # remote_checksum is empty so we continue and keep original checksum string
620 # This should not happen since we check for remote_checksum before
621 except IndexError:
622 pass
623 if local_checksum.lower() == remote_checksum.lower():
624 return None
625 else:
626 return (
627 f"Checksum does not match: we computed {local_checksum} but the repository states {remote_checksum}"
628 )
629
630 return f"Path does not exist: {file}"
631
632 def _local_checksum(self, checksum_alg, file):
633 if checksum_alg.lower() == "md5":
634 hash = hashlib.md5()
635 elif checksum_alg.lower() == "sha1":
636 hash = hashlib.sha1()
637 else:
638 raise ValueError(f"Unknown checksum_alg {checksum_alg}")
639 with open(file, "rb") as f:
640 for chunk in iter(lambda: f.read(8192), b""):
641 hash.update(chunk)
642 return hash.hexdigest()
643
644
645 def main():
646 module = AnsibleModule(
647 argument_spec=dict(
648 group_id=dict(required=True),
649 artifact_id=dict(required=True),
650 version=dict(),
651 version_by_spec=dict(),
652 classifier=dict(default=""),
653 extension=dict(default="jar"),
654 repository_url=dict(default="https://repo1.maven.org/maven2"),
655 username=dict(aliases=["aws_secret_key"]),
656 password=dict(no_log=True, aliases=["aws_secret_access_key"]),
657 headers=dict(type="dict"),
658 force_basic_auth=dict(default=False, type="bool"),
659 state=dict(default="present", choices=["present", "absent"]),
660 timeout=dict(default=10, type="int"),
661 dest=dict(type="path", required=True),
662 validate_certs=dict(default=True, type="bool"),
663 client_cert=dict(type="path"),
664 client_key=dict(type="path"),
665 keep_name=dict(default=False, type="bool"),
666 verify_checksum=dict(default="download", choices=["never", "download", "change", "always"]),
667 checksum_alg=dict(default="md5", choices=["md5", "sha1"]),
668 unredirected_headers=dict(type="list", elements="str"),
669 directory_mode=dict(type="str"),
670 ),
671 add_file_common_args=True,
672 mutually_exclusive=([("version", "version_by_spec")]),
673 )
674
675 if module.params["unredirected_headers"] is None:
676 # if the user did not supply unredirected params, we use the default
677 module.params["unredirected_headers"] = ["Authorization", "Cookie"]
678
679 if not HAS_LXML_ETREE:
680 module.fail_json(msg=missing_required_lib("lxml"), exception=LXML_ETREE_IMP_ERR)
681
682 if module.params["version_by_spec"] and not HAS_SEMANTIC_VERSION:
683 module.fail_json(msg=missing_required_lib("semantic_version"), exception=SEMANTIC_VERSION_IMP_ERR)
684
685 repository_url = module.params["repository_url"]
686 if not repository_url:
687 repository_url = "https://repo1.maven.org/maven2"
688 try:
689 parsed_url = urlparse(repository_url)
690 except AttributeError as e:
691 module.fail_json(msg=f"url parsing went wrong {e}")
692
693 local = parsed_url.scheme == "file"
694
695 if parsed_url.scheme == "s3" and not HAS_BOTO:
696 module.fail_json(
697 msg=missing_required_lib("boto3", reason="when using s3:// repository URLs"), exception=BOTO_IMP_ERR
698 )
699
700 group_id = module.params["group_id"]
701 artifact_id = module.params["artifact_id"]
702 version = module.params["version"]
703 version_by_spec = module.params["version_by_spec"]
704 classifier = module.params["classifier"]
705 extension = module.params["extension"]
706 headers = module.params["headers"]
707 state = module.params["state"]
708 dest = module.params["dest"]
709 b_dest = to_bytes(dest, errors="surrogate_or_strict")
710 keep_name = module.params["keep_name"]
711 verify_checksum = module.params["verify_checksum"]
712 verify_download = verify_checksum in ["download", "always"]
713 verify_change = verify_checksum in ["change", "always"]
714 checksum_alg = module.params["checksum_alg"]
715
716 downloader = MavenDownloader(module, repository_url, local, headers)
717
718 if not version_by_spec and not version:
719 version = "latest"
720
721 try:
722 artifact = Artifact(group_id, artifact_id, version, version_by_spec, classifier, extension)
723 except ValueError as e:
724 module.fail_json(msg=e.args[0])
725
726 changed = False
727 prev_state = "absent"
728
729 if dest.endswith(os.sep):
730 b_dest = to_bytes(dest, errors="surrogate_or_strict")
731 if not os.path.exists(b_dest):
732 (pre_existing_dir, new_directory_list) = split_pre_existing_dir(dest)
733 os.makedirs(b_dest)
734 directory_args = module.load_file_common_arguments(module.params)
735 directory_mode = module.params["directory_mode"]
736 if directory_mode is not None:
737 directory_args["mode"] = directory_mode
738 else:
739 directory_args["mode"] = None
740 changed = adjust_recursive_directory_permissions(
741 pre_existing_dir, new_directory_list, module, directory_args, changed
742 )
743
744 if os.path.isdir(b_dest):
745 version_part = version
746 if version == "latest":
747 version_part = downloader.find_latest_version_available(artifact)
748 elif version_by_spec:
749 version_part = downloader.find_version_by_spec(artifact)
750
751 filename = f"{artifact_id}{(f'-{version_part}' if keep_name else '')}{(f'-{classifier}' if classifier else '')}.{extension}"
752 dest = posixpath.join(dest, filename)
753
754 b_dest = to_bytes(dest, errors="surrogate_or_strict")
755
756 if os.path.lexists(b_dest) and (
757 (not verify_change)
758 or not downloader.is_invalid_checksum(dest, downloader.find_uri_for_artifact(artifact), checksum_alg)
759 ):
760 prev_state = "present"
761
762 if prev_state == "absent":
763 try:
764 download_error = downloader.download(module.tmpdir, artifact, verify_download, b_dest, checksum_alg)
765 if download_error is None:
766 changed = True
767 else:
768 module.fail_json(msg=f"Cannot retrieve the artifact to destination: {download_error}")
769 except ValueError as e:
770 module.fail_json(msg=e.args[0])
771
772 file_args = module.load_file_common_arguments(module.params, path=dest)
773 changed = module.set_fs_attributes_if_different(file_args, changed)
774 if changed:
775 module.exit_json(
776 state=state,
777 dest=dest,
778 group_id=group_id,
779 artifact_id=artifact_id,
780 version=version,
781 classifier=classifier,
782 extension=extension,
783 repository_url=repository_url,
784 changed=changed,
785 )
786 else:
787 module.exit_json(state=state, dest=dest, changed=changed)
788
789
790 if __name__ == "__main__":
791 main()