Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 #
3 # Copyright (c) Ansible Project
4 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
5 # SPDX-License-Identifier: GPL-3.0-or-later
6
7 from __future__ import annotations
8
9 DOCUMENTATION = r"""
10 module: jenkins_credential
11 short_description: Manage Jenkins credentials and domains through API
12 version_added: 11.1.0
13 description:
14 - This module allows managing Jenkins credentials and domain scopes through the Jenkins HTTP API.
15 - Create, update, and delete different credential types such as C(username/password), C(secret text), C(SSH key), C(certificates),
16 C(GitHub App), and domains.
17 - For scoped domains (O(type=scope)), it supports restrictions based on V(hostname), V(hostname:port), V(path), and V(scheme).
18 requirements:
19 - urllib3 >= 1.26.0
20 author:
21 - Youssef Ali (@YoussefKhalidAli)
22 extends_documentation_fragment:
23 - community.general._attributes
24 attributes:
25 check_mode:
26 support: full
27 diff_mode:
28 support: none
29 options:
30 id:
31 description:
32 - The ID of the Jenkins credential or domain.
33 - When generating a new token, do not pass O(id). It is generated automatically.
34 type: str
35 type:
36 description:
37 - Type of the credential or action.
38 choices:
39 - user_and_pass
40 - file
41 - text
42 - github_app
43 - ssh_key
44 - certificate
45 - scope
46 - token
47 type: str
48 state:
49 description:
50 - The state of the credential.
51 choices:
52 - present
53 - absent
54 default: present
55 type: str
56 scope:
57 description:
58 - Jenkins credential domain scope.
59 - Deleting a domain scope deletes all credentials within it.
60 type: str
61 default: '_'
62 force:
63 description:
64 - Force update if the credential already exists, used with O(state=present).
65 - If set to V(true), it deletes the existing credential before creating a new one.
66 - Always returns RV(ignore:changed=true).
67 type: bool
68 default: false
69 url:
70 description:
71 - Jenkins server URL.
72 type: str
73 default: http://localhost:8080
74 jenkins_user:
75 description:
76 - Jenkins user for authentication.
77 required: true
78 type: str
79 jenkins_password:
80 description:
81 - Jenkins password for token creation. Required if O(type=token).
82 type: str
83 token:
84 description:
85 - Jenkins API token. Required unless O(type=token).
86 type: str
87 description:
88 description:
89 - Description of the credential or domain.
90 default: ''
91 type: str
92 location:
93 description:
94 - Location of the credential. Either V(system) or V(folder).
95 - If O(location=folder) then O(url) must be set to V(<jenkins-server>/job/<folder_name>).
96 choices:
97 - system
98 - folder
99 default: 'system'
100 type: str
101 name:
102 description:
103 - Name of the token to generate. Required if O(type=token).
104 - When generating a new token, do not pass O(id). It is generated automatically.
105 - Creating two tokens with the same name generates two distinct tokens with different RV(token_uuid) values.
106 - Replacing a token with another one of the same name requires deleting the original first using O(force=True).
107 type: str
108 username:
109 description:
110 - Username for credentials types that require it (for example O(type=ssh_key) or O(type=user_and_pass)).
111 type: str
112 password:
113 description:
114 - Password for credentials types that require it (for example O(type=user_and_passs) or O(type=certificate)).
115 type: str
116 secret:
117 description:
118 - Secret text (used when O(type=text)).
119 type: str
120 appID:
121 description:
122 - GitHub App ID.
123 type: str
124 api_uri:
125 description:
126 - Link to Github API.
127 default: 'https://api.github.com'
128 type: str
129 owner:
130 description:
131 - GitHub App owner.
132 type: str
133 file_path:
134 description:
135 - File path to secret file (for example O(type=file) or O(type=certificate)).
136 - For O(type=certificate), this can be a V(.p12) or V(.pem) file.
137 type: path
138 private_key_path:
139 description:
140 - Path to private key file for PEM certificates or GitHub Apps.
141 type: path
142 passphrase:
143 description:
144 - SSH passphrase if needed.
145 type: str
146 inc_hostname:
147 description:
148 - List of hostnames to include in scope.
149 type: list
150 elements: str
151 exc_hostname:
152 description:
153 - List of hostnames to exclude from scope.
154 - If a hostname appears in both this list and O(inc_hostname), the hostname is excluded.
155 type: list
156 elements: str
157 inc_hostname_port:
158 description:
159 - List of V(host:port) to include in scope.
160 type: list
161 elements: str
162 exc_hostname_port:
163 description:
164 - List of host:port to exclude from scope.
165 - If a hostname and port appears in both this list and O(inc_hostname_port), it is excluded.
166 type: list
167 elements: str
168 inc_path:
169 description:
170 - List of URL paths to include when matching credentials to domains.
171 - 'B(Matching is hierarchical): subpaths of excluded paths are also excluded, even if explicitly included.'
172 type: list
173 elements: str
174 exc_path:
175 description:
176 - List of URL paths to exclude.
177 - If a path is also matched by O(exc_path), it is excluded.
178 - If you exclude a subpath of a path previously included, that subpath alone is excluded.
179 type: list
180 elements: str
181 schemes:
182 description:
183 - List of schemes (for example V(http) or V(https)) to match.
184 type: list
185 elements: str
186 """
187
188 EXAMPLES = r"""
189 - name: Generate token
190 community.general.jenkins_credential:
191 name: "test-token"
192 jenkins_user: "admin"
193 jenkins_password: "password"
194 type: "token"
195 register: token_result
196
197 - name: Save Jenkins token to INI file (you must secure/encrypt separately)
198 vars:
199 jenkins_token_ini: # Defining dict for to_ini filter
200 api_token:
201 uuid: "{{ token_result.token_uuid }}"
202 token: "{{ token_result.token }}"
203 ansible.builtin.copy:
204 dest: "/secure/path/jenkins_token.ini"
205 mode: '0600'
206 content: "{{ jenkins_token_ini | community.general.to_ini }}"
207
208 # Note:
209 # (1) Jenkins token is intended to be securely stored in encrypted storage
210 # or secrets vault outside the playbook, retrieved when needed.
211 # (2) Examples below showcasing token retrieval from
212 # variable "token_result" are NOT how it should be used to add credentials.
213 # (3) Data in "token_result" is inconsistent and unavailable
214 # across different playbooks and multiple executions.
215
216 - name: Add CUSTOM scope credential
217 community.general.jenkins_credential:
218 id: "CUSTOM"
219 type: "scope"
220 jenkins_user: "admin"
221 token: "{{ token_result.token }}"
222 description: "Custom scope credential"
223 inc_path:
224 - "include/path"
225 - "include/path2"
226 exc_path:
227 - "exclude/path"
228 - "exclude/path2"
229 inc_hostname:
230 - "included-hostname"
231 - "included-hostname2"
232 exc_hostname:
233 - "excluded-hostname"
234 - "excluded-hostname2"
235 schemes:
236 - "http"
237 - "https"
238 inc_hostname_port:
239 - "included-hostname:7000"
240 - "included-hostname2:7000"
241 exc_hostname_port:
242 - "excluded-hostname:7000"
243 - "excluded-hostname2:7000"
244
245 - name: Add user_and_pass credential
246 community.general.jenkins_credential:
247 id: "userpass-id"
248 type: "user_and_pass"
249 jenkins_user: "admin"
250 token: "{{ token_result.token }}"
251 description: "User and password credential"
252 username: "user1"
253 password: "pass1"
254
255 - name: Add file credential to custom scope
256 community.general.jenkins_credential:
257 id: "file-id"
258 type: "file"
259 jenkins_user: "admin"
260 token: "{{ token_result.token }}"
261 scope: "CUSTOM"
262 description: "File credential"
263 file_path: "../vars/my-secret.pem"
264
265 - name: Add text credential to folder
266 community.general.jenkins_credential:
267 id: "text-id"
268 type: "text"
269 jenkins_user: "admin"
270 token: "{{ token_result.token }}"
271 description: "Text credential"
272 secret: "mysecrettext"
273 location: "folder"
274 url: "http://localhost:8080/job/test"
275
276 - name: Add githubApp credential
277 community.general.jenkins_credential:
278 id: "githubapp-id"
279 type: "github_app"
280 jenkins_user: "admin"
281 token: "{{ token_result.token }}"
282 description: "GitHub app credential"
283 appID: "12345"
284 file_path: "../vars/github.pem"
285 owner: "github_owner"
286
287 - name: Add sshKey credential
288 community.general.jenkins_credential:
289 id: "sshkey-id"
290 type: "ssh_key"
291 jenkins_user: "admin"
292 token: "{{ token_result.token }}"
293 description: "SSH key credential"
294 username: "sshuser"
295 file_path: "../vars/ssh_key"
296 passphrase: 1234
297
298 - name: Add certificate credential (p12)
299 community.general.jenkins_credential:
300 id: "certificate-id"
301 type: "certificate"
302 jenkins_user: "admin"
303 token: "{{ token_result.token }}"
304 description: "Certificate credential"
305 password: "12345678901234"
306 file_path: "../vars/certificate.p12"
307
308 - name: Add certificate credential (pem)
309 community.general.jenkins_credential:
310 id: "certificate-id-pem"
311 type: "certificate"
312 jenkins_user: "admin"
313 token: "{{ token_result.token }}"
314 description: "Certificate credential (pem)"
315 file_path: "../vars/cert.pem"
316 private_key_path: "../vars/private.key"
317 """
318 RETURN = r"""
319 details:
320 description: Return more details in case of errors.
321 type: str
322 returned: failed
323 token:
324 description:
325 - The generated API token if O(type=token).
326 - This is needed to authenticate API calls later.
327 - This should be stored securely, as it is the only time it is returned.
328 type: str
329 returned: success
330 token_uuid:
331 description:
332 - The generated ID of the token.
333 - You pass this value back to the module as O(id) to edit or revoke the token later.
334 - This should be stored securely, as it is the only time it is returned.
335 type: str
336 returned: success
337 """
338
339 import base64
340 import json
341 import os
342 from urllib.parse import urlencode
343
344 from ansible.module_utils.basic import AnsibleModule
345 from ansible.module_utils.urls import basic_auth_header, fetch_url
346
347 from ansible_collections.community.general.plugins.module_utils import _deps as deps
348
349 with deps.declare("urllib3", reason="urllib3 is required to embed files into requests"):
350 import urllib3
351
352
353 # Function to validate file paths exist on disk
354 def validate_file_exist(module, path):
355 if path and not os.path.exists(path):
356 module.fail_json(msg=f"File not found: {path}")
357
358
359 # Gets the Jenkins crumb for CSRF protection which is required for API calls
360 def get_jenkins_crumb(module, headers):
361 type = module.params["type"]
362 url = module.params["url"]
363
364 if "/job" in url:
365 url = url.split("/job")[0]
366
367 crumb_url = f"{url}/crumbIssuer/api/json"
368
369 response, info = fetch_url(module, crumb_url, headers=headers)
370
371 if info["status"] != 200:
372 module.fail_json(msg="Failed to fetch Jenkins crumb. Confirm token is real.")
373
374 # Cookie is needed to generate API token
375 cookie = info.get("set-cookie", "")
376 session_cookie = cookie.split(";")[0] if cookie else None
377
378 try:
379 data = response.read()
380 json_data = json.loads(data)
381 crumb_request_field = json_data["crumbRequestField"]
382 crumb = json_data["crumb"]
383 headers[crumb_request_field] = crumb # Set the crumb in headers
384 headers["Content-Type"] = "application/x-www-form-urlencoded" # Set Content-Type for form data
385 if type == "token":
386 headers["Cookie"] = session_cookie # Set session cookie for token operations
387 return crumb_request_field, crumb, session_cookie # Return for test purposes
388
389 except Exception:
390 return None
391
392
393 # Function to clean the data sent via API by removing unwanted keys and None values
394 def clean_data(data):
395 # Keys to remove (including those with None values)
396 keys_to_remove = {
397 "url",
398 "token",
399 "jenkins_user",
400 "jenkins_password",
401 "file_path",
402 "private_key_path",
403 "type",
404 "state",
405 "force",
406 "name",
407 "scope",
408 "location",
409 "api_uri",
410 }
411
412 # Filter out None values and unwanted keys
413 cleaned_data = {key: value for key, value in data.items() if value is not None and key not in keys_to_remove}
414
415 return cleaned_data
416
417
418 # Function to check if credentials/domain exists
419 def target_exists(module, check_domain=False):
420 url = module.params["url"]
421 location = module.params["location"]
422 scope = module.params["scope"]
423 name = module.params["id"]
424 user = module.params["jenkins_user"]
425 token = module.params["token"]
426
427 headers = {"Authorization": basic_auth_header(user, token)}
428
429 if module.params["type"] == "scope" or check_domain:
430 target_url = f"{url}/credentials/store/{location}/domain/{scope if check_domain else name}/api/json"
431 elif module.params["type"] == "token":
432 return False # Can't check token
433 else:
434 target_url = f"{url}/credentials/store/{location}/domain/{scope}/credential/{name}/api/json"
435
436 response, info = fetch_url(module, target_url, headers=headers)
437 status = info.get("status", 0)
438
439 if status == 200:
440 return True
441 elif status == 404:
442 return False
443 else:
444 module.fail_json(msg=f"Unexpected status code {status} when checking {name} existence.")
445
446
447 # Function to delete the scope or credential provided
448 def delete_target(module, headers):
449 user = module.params["jenkins_user"]
450 type = module.params["type"]
451 url = module.params["url"]
452 location = module.params["location"]
453 id = module.params["id"]
454 scope = module.params["scope"]
455
456 body = False
457
458 try:
459 if type == "token":
460 delete_url = f"{url}/user/{user}/descriptorByName/jenkins.security.ApiTokenProperty/revoke"
461 body = urlencode({"tokenUuid": id})
462
463 elif type == "scope":
464 delete_url = f"{url}/credentials/store/{location}/domain/{id}/doDelete"
465
466 else:
467 delete_url = f"{url}/credentials/store/{location}/domain/{scope}/credential/{id}/doDelete"
468
469 response, info = fetch_url(
470 module,
471 delete_url,
472 headers=headers,
473 data=body if body else None,
474 method="POST",
475 )
476
477 status = info.get("status", 0)
478 if status != 200:
479 module.fail_json(msg=f"Failed to delete: HTTP {status}, {response}, {headers}")
480
481 except Exception as e:
482 module.fail_json(msg=f"Exception during delete: {e}")
483
484
485 # Function to read the private key for types texts and ssh_key
486 def read_privateKey(module):
487 try:
488 with open(module.params["private_key_path"]) as f:
489 private_key = f.read().strip()
490 return private_key
491 except Exception as e:
492 module.fail_json(msg=f"Failed to read private key file: {e}")
493
494
495 # Function to builds multipart form-data body and content-type header for file credential upload.
496 # Returns:
497 # body (bytes): Encoded multipart data
498 # content_type (str): Content-Type header including boundary
499 def embed_file_into_body(module, file_path, credentials):
500 filename = os.path.basename(file_path)
501
502 try:
503 with open(file_path, "rb") as f:
504 file_bytes = f.read()
505 except Exception as e:
506 module.fail_json(msg=f"Failed to read file: {e}")
507 return "", "" # Return for test purposes
508
509 credentials.update(
510 {
511 "file": "file0",
512 "fileName": filename,
513 }
514 )
515
516 payload = {"credentials": credentials}
517
518 fields = {"file0": (filename, file_bytes), "json": json.dumps(payload)}
519
520 body, content_type = urllib3.encode_multipart_formdata(fields)
521 return body, content_type
522
523
524 # Main function to run the Ansible module
525 def run_module():
526 module = AnsibleModule(
527 argument_spec=dict(
528 id=dict(type="str"),
529 type=dict(
530 type="str",
531 choices=[
532 "user_and_pass",
533 "file",
534 "text",
535 "github_app",
536 "ssh_key",
537 "certificate",
538 "scope",
539 "token",
540 ],
541 ),
542 state=dict(type="str", default="present", choices=["present", "absent"]),
543 force=dict(type="bool", default=False),
544 scope=dict(type="str", default="_"),
545 url=dict(type="str", default="http://localhost:8080"),
546 jenkins_user=dict(type="str", required=True),
547 jenkins_password=dict(type="str", no_log=True),
548 token=dict(type="str", no_log=True),
549 description=dict(type="str", default=""),
550 location=dict(type="str", default="system", choices=["system", "folder"]),
551 name=dict(type="str"),
552 username=dict(type="str"),
553 password=dict(type="str", no_log=True),
554 file_path=dict(type="path"),
555 secret=dict(type="str", no_log=True),
556 appID=dict(type="str"),
557 api_uri=dict(type="str", default="https://api.github.com"),
558 owner=dict(type="str"),
559 passphrase=dict(type="str", no_log=True),
560 private_key_path=dict(type="path", no_log=True),
561 # Scope specifications parameters
562 inc_hostname=dict(type="list", elements="str"),
563 exc_hostname=dict(type="list", elements="str"),
564 inc_hostname_port=dict(type="list", elements="str"),
565 exc_hostname_port=dict(type="list", elements="str"),
566 inc_path=dict(type="list", elements="str"),
567 exc_path=dict(type="list", elements="str"),
568 schemes=dict(type="list", elements="str"),
569 ),
570 supports_check_mode=True,
571 required_if=[
572 ("state", "present", ["type"]),
573 ("state", "absent", ["id"]),
574 ("type", "token", ["name", "jenkins_password"]),
575 ("type", "user_and_pass", ["username", "password", "id", "token"]),
576 ("type", "file", ["file_path", "id", "token"]),
577 ("type", "text", ["secret", "id", "token"]),
578 ("type", "github_app", ["appID", "private_key_path", "id", "token"]),
579 ("type", "ssh_key", ["username", "private_key_path", "id", "token"]),
580 ("type", "certificate", ["file_path", "id", "token"]),
581 ("type", "scope", ["id", "token"]),
582 ],
583 )
584
585 # Parameters
586 id = module.params["id"]
587 type = module.params["type"]
588 state = module.params["state"]
589 force = module.params["force"]
590 scope = module.params["scope"]
591 url = module.params["url"]
592 jenkins_user = module.params["jenkins_user"]
593 jenkins_password = module.params["jenkins_password"]
594 name = module.params["name"]
595 token = module.params["token"]
596 description = module.params["description"]
597 location = module.params["location"]
598 filePath = module.params["file_path"]
599 private_key_path = module.params["private_key_path"]
600 api_uri = module.params["api_uri"]
601 inc_hostname = module.params["inc_hostname"]
602 exc_hostname = module.params["exc_hostname"]
603 inc_hostname_port = module.params["inc_hostname_port"]
604 exc_hostname_port = module.params["exc_hostname_port"]
605 inc_path = module.params["inc_path"]
606 exc_path = module.params["exc_path"]
607 schemes = module.params["schemes"]
608
609 deps.validate(module)
610
611 headers = {
612 "Authorization": basic_auth_header(jenkins_user, token or jenkins_password),
613 }
614
615 # Get the crumb for CSRF protection
616 get_jenkins_crumb(module, headers)
617
618 result = dict(
619 changed=False,
620 msg="",
621 )
622
623 credentials = clean_data(module.params)
624
625 does_exist = target_exists(module)
626
627 # Check if the credential/domain doesn't exist and the user wants to delete
628 if not does_exist and state == "absent" and type != "token":
629 result["changed"] = False
630 result["msg"] = f"{id} does not exist."
631 module.exit_json(**result)
632
633 if state == "present":
634 # If updating, we need to delete the existing credential/domain first based on force parameter
635 if force and (does_exist or type == "token"):
636 delete_target(module, headers)
637 elif does_exist and not force:
638 result["changed"] = False
639 result["msg"] = f"{id} already exists. Use force=True to update."
640 module.exit_json(**result)
641
642 if type == "token":
643 post_url = f"{url}/user/{jenkins_user}/descriptorByName/jenkins.security.ApiTokenProperty/generateNewToken"
644
645 body = f"newTokenName={name}"
646
647 elif type == "scope":
648 post_url = f"{url}/credentials/store/{location}/createDomain"
649
650 specifications = []
651
652 # Create a domain in Jenkins
653 if inc_hostname or exc_hostname:
654 specifications.append(
655 {
656 "stapler-class": "com.cloudbees.plugins.credentials.domains.HostnameSpecification",
657 "includes": ",".join(inc_hostname),
658 "excludes": ",".join(exc_hostname),
659 }
660 )
661
662 if inc_hostname_port or exc_hostname_port:
663 specifications.append(
664 {
665 "stapler-class": "com.cloudbees.plugins.credentials.domains.HostnamePortSpecification",
666 "includes": ",".join(inc_hostname_port),
667 "excludes": ",".join(exc_hostname_port),
668 }
669 )
670
671 if schemes:
672 specifications.append(
673 {
674 "stapler-class": "com.cloudbees.plugins.credentials.domains.SchemeSpecification",
675 "schemes": ",".join(schemes),
676 },
677 )
678
679 if inc_path or exc_path:
680 specifications.append(
681 {
682 "stapler-class": "com.cloudbees.plugins.credentials.domains.PathSpecification",
683 "includes": ",".join(inc_path),
684 "excludes": ",".join(exc_path),
685 }
686 )
687
688 payload = {
689 "name": id,
690 "description": description,
691 "specifications": specifications,
692 }
693
694 else:
695 if filePath:
696 validate_file_exist(module, filePath)
697 elif private_key_path:
698 validate_file_exist(module, private_key_path)
699
700 post_url = f"{url}/credentials/store/{location}/domain/{scope}/createCredentials"
701
702 cred_class = {
703 "user_and_pass": "com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl",
704 "file": "org.jenkinsci.plugins.plaincredentials.impl.FileCredentialsImpl",
705 "text": "org.jenkinsci.plugins.plaincredentials.impl.StringCredentialsImpl",
706 "github_app": "org.jenkinsci.plugins.github_branch_source.GitHubAppCredentials",
707 "ssh_key": "com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey",
708 "certificate": "com.cloudbees.plugins.credentials.impl.CertificateCredentialsImpl",
709 }
710 credentials.update({"$class": cred_class[type]})
711
712 if type == "file":
713 # Build multipart body and content-type
714 body, content_type = embed_file_into_body(module, filePath, credentials)
715 headers["Content-Type"] = content_type
716
717 elif type == "github_app":
718 private_key = read_privateKey(module)
719
720 credentials.update(
721 {
722 "privateKey": private_key,
723 "apiUri": api_uri,
724 }
725 )
726
727 elif type == "ssh_key":
728 private_key = read_privateKey(module)
729
730 credentials.update(
731 {
732 "privateKeySource": {
733 "stapler-class": "com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey$DirectEntryPrivateKeySource",
734 "privateKey": private_key,
735 },
736 }
737 )
738
739 elif type == "certificate":
740 name, ext = os.path.splitext(filePath)
741
742 if ext.lower() in [".p12", ".pfx"]:
743 try:
744 with open(filePath, "rb") as f:
745 file_content = f.read()
746 uploaded_keystore = base64.b64encode(file_content).decode("utf-8")
747 except Exception as e:
748 module.fail_json(msg=f"Failed to read or encode keystore file: {e}")
749
750 credentials.update(
751 {
752 "keyStoreSource": {
753 "$class": "com.cloudbees.plugins.credentials.impl.CertificateCredentialsImpl$UploadedKeyStoreSource",
754 "uploadedKeystore": uploaded_keystore,
755 },
756 }
757 )
758
759 elif ext.lower() in [".pem", ".crt"]: # PEM mode
760 try:
761 with open(filePath) as f:
762 cert_chain = f.read()
763 with open(private_key_path) as f:
764 private_key = f.read()
765 except Exception as e:
766 module.fail_json(msg=f"Failed to read PEM files: {e}")
767
768 credentials.update(
769 {
770 "keyStoreSource": {
771 "$class": "com.cloudbees.plugins.credentials.impl.CertificateCredentialsImpl$PEMEntryKeyStoreSource",
772 "certChain": cert_chain,
773 "privateKey": private_key,
774 },
775 }
776 )
777
778 else:
779 module.fail_json(
780 msg="Unsupported certificate file type. Only .p12, .pfx, .pem or .crt are supported."
781 )
782
783 payload = {"credentials": credentials}
784
785 if type != "file" and type != "token":
786 body = urlencode({"json": json.dumps(payload)})
787
788 else: # Delete
789 delete_target(module, headers)
790
791 module.exit_json(changed=True, msg=f"{id} deleted successfully.")
792
793 if type != "scope" and scope != "_": # Check if custom scope exists if adding to a custom scope
794 if not target_exists(module, True):
795 module.fail_json(msg=f"Domain {scope} doesn't exists")
796
797 try:
798 response, info = fetch_url(module, post_url, headers=headers, data=body, method="POST")
799 except Exception as e:
800 module.fail_json(msg=f"Request to {post_url} failed: {e}")
801
802 status = info.get("status", 0)
803
804 if status != 200:
805 body = response.read() if response else b""
806 module.fail_json(
807 msg=f"Failed to {'add/update' if state == 'present' else 'delete'} credential",
808 details=body.decode("utf-8", errors="ignore"),
809 )
810
811 if type == "token":
812 response_data = json.loads(response.read())
813 result["token"] = response_data["data"]["tokenValue"]
814 result["token_uuid"] = response_data["data"]["tokenUuid"]
815
816 result["changed"] = True
817 result["msg"] = response.read().decode("utf-8")
818
819 module.exit_json(**result)
820
821
822 if __name__ == "__main__":
823 run_module()