| 1 |
#!/usr/bin/python |
| 2 |
|
| 3 |
# Copyright (c) 2016, James Hogarth <[email protected]> |
| 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 |
author: James Hogarth (@hogarthj) |
| 11 |
module: jenkins_script |
| 12 |
short_description: Executes a groovy script in the jenkins instance |
| 13 |
description: |
| 14 |
- The C(jenkins_script) module takes a script plus a dict of values to use within the script and returns the result of the |
| 15 |
script being run. |
| 16 |
extends_documentation_fragment: |
| 17 |
- community.general._attributes |
| 18 |
|
| 19 |
attributes: |
| 20 |
check_mode: |
| 21 |
support: none |
| 22 |
diff_mode: |
| 23 |
support: none |
| 24 |
|
| 25 |
options: |
| 26 |
script: |
| 27 |
type: str |
| 28 |
description: |
| 29 |
- The groovy script to be executed. This gets passed as a string Template if args is defined. |
| 30 |
required: true |
| 31 |
url: |
| 32 |
type: str |
| 33 |
description: |
| 34 |
- The jenkins server to execute the script against. The default is a local jenkins instance that is not being proxied |
| 35 |
through a webserver. |
| 36 |
default: http://localhost:8080 |
| 37 |
validate_certs: |
| 38 |
description: |
| 39 |
- If set to V(false), the SSL certificates are not validated. This should only set to V(false) used on personally controlled |
| 40 |
sites using self-signed certificates as it avoids verifying the source site. |
| 41 |
type: bool |
| 42 |
default: true |
| 43 |
user: |
| 44 |
type: str |
| 45 |
description: |
| 46 |
- The username to connect to the jenkins server with. |
| 47 |
password: |
| 48 |
type: str |
| 49 |
description: |
| 50 |
- The password to connect to the jenkins server with. |
| 51 |
timeout: |
| 52 |
type: int |
| 53 |
description: |
| 54 |
- The request timeout in seconds. |
| 55 |
default: 10 |
| 56 |
args: |
| 57 |
type: dict |
| 58 |
description: |
| 59 |
- A dict of key-value pairs used in formatting the script using string.Template (see https://docs.python.org/2/library/string.html#template-strings). |
| 60 |
notes: |
| 61 |
- Since the script can do anything this does not report on changes. Knowing the script is being run it is important to set |
| 62 |
C(changed_when) for the ansible output to be clear on any alterations made. |
| 63 |
""" |
| 64 |
|
| 65 |
EXAMPLES = r""" |
| 66 |
- name: Obtaining a list of plugins |
| 67 |
community.general.jenkins_script: |
| 68 |
script: 'println(Jenkins.instance.pluginManager.plugins)' |
| 69 |
user: admin |
| 70 |
password: admin |
| 71 |
|
| 72 |
- name: Setting master using a variable to hold a more complicate script |
| 73 |
ansible.builtin.set_fact: |
| 74 |
setmaster_mode: | |
| 75 |
import jenkins.model.* |
| 76 |
instance = Jenkins.getInstance() |
| 77 |
instance.setMode(${jenkins_mode}) |
| 78 |
instance.save() |
| 79 |
|
| 80 |
- name: Use the variable as the script |
| 81 |
community.general.jenkins_script: |
| 82 |
script: "{{ setmaster_mode }}" |
| 83 |
args: |
| 84 |
jenkins_mode: Node.Mode.EXCLUSIVE |
| 85 |
|
| 86 |
- name: Interacting with an untrusted HTTPS connection |
| 87 |
community.general.jenkins_script: |
| 88 |
script: "println(Jenkins.instance.pluginManager.plugins)" |
| 89 |
user: admin |
| 90 |
password: admin |
| 91 |
url: https://localhost |
| 92 |
validate_certs: false # only do this when you trust the network! |
| 93 |
""" |
| 94 |
|
| 95 |
RETURN = r""" |
| 96 |
output: |
| 97 |
description: Result of script. |
| 98 |
returned: success |
| 99 |
type: str |
| 100 |
sample: 'Result: true' |
| 101 |
""" |
| 102 |
|
| 103 |
import json |
| 104 |
from http import cookiejar |
| 105 |
from string import Template |
| 106 |
from urllib.parse import urlencode |
| 107 |
|
| 108 |
from ansible.module_utils.basic import AnsibleModule |
| 109 |
from ansible.module_utils.common.text.converters import to_native |
| 110 |
from ansible.module_utils.urls import fetch_url |
| 111 |
|
| 112 |
|
| 113 |
def is_csrf_protection_enabled(module): |
| 114 |
resp, info = fetch_url(module, f"{module.params['url']}/api/json", timeout=module.params["timeout"], method="GET") |
| 115 |
if info["status"] != 200: |
| 116 |
module.fail_json(msg=f"HTTP error {info['status']} {info['msg']}", output="") |
| 117 |
|
| 118 |
return json.loads(resp.read()).get("useCrumbs", False) |
| 119 |
|
| 120 |
|
| 121 |
def get_crumb(module, cookies): |
| 122 |
resp, info = fetch_url( |
| 123 |
module, |
| 124 |
f"{module.params['url']}/crumbIssuer/api/json", |
| 125 |
method="GET", |
| 126 |
timeout=module.params["timeout"], |
| 127 |
cookies=cookies, |
| 128 |
) |
| 129 |
if info["status"] != 200: |
| 130 |
module.fail_json(msg=f"HTTP error {info['status']} {info['msg']}", output="") |
| 131 |
|
| 132 |
return json.loads(resp.read()) |
| 133 |
|
| 134 |
|
| 135 |
def main(): |
| 136 |
module = AnsibleModule( |
| 137 |
argument_spec=dict( |
| 138 |
script=dict(required=True, type="str"), |
| 139 |
url=dict(type="str", default="http://localhost:8080"), |
| 140 |
validate_certs=dict(type="bool", default=True), |
| 141 |
user=dict(type="str"), |
| 142 |
password=dict(no_log=True, type="str"), |
| 143 |
timeout=dict(type="int", default=10), |
| 144 |
args=dict(type="dict"), |
| 145 |
) |
| 146 |
) |
| 147 |
|
| 148 |
if module.params["user"] is not None: |
| 149 |
if module.params["password"] is None: |
| 150 |
module.fail_json(msg="password required when user provided", output="") |
| 151 |
module.params["url_username"] = module.params["user"] |
| 152 |
module.params["url_password"] = module.params["password"] |
| 153 |
module.params["force_basic_auth"] = True |
| 154 |
|
| 155 |
if module.params["args"] is not None: |
| 156 |
try: |
| 157 |
script_contents = Template(module.params["script"]).substitute(module.params["args"]) |
| 158 |
except KeyError as err: |
| 159 |
module.fail_json(msg=f"Error with templating variable: {err}", output="") |
| 160 |
else: |
| 161 |
script_contents = module.params["script"] |
| 162 |
|
| 163 |
headers = {} |
| 164 |
cookies = None |
| 165 |
if is_csrf_protection_enabled(module): |
| 166 |
cookies = cookiejar.LWPCookieJar() |
| 167 |
crumb = get_crumb(module, cookies) |
| 168 |
headers = {crumb["crumbRequestField"]: crumb["crumb"]} |
| 169 |
|
| 170 |
resp, info = fetch_url( |
| 171 |
module, |
| 172 |
f"{module.params['url']}/scriptText", |
| 173 |
data=urlencode({"script": script_contents}), |
| 174 |
headers=headers, |
| 175 |
method="POST", |
| 176 |
timeout=module.params["timeout"], |
| 177 |
cookies=cookies, |
| 178 |
) |
| 179 |
|
| 180 |
if info["status"] != 200: |
| 181 |
module.fail_json(msg=f"HTTP error {info['status']} {info['msg']}", output="") |
| 182 |
|
| 183 |
result = to_native(resp.read()) |
| 184 |
|
| 185 |
if "Exception:" in result and "at java.lang.Thread" in result: |
| 186 |
module.fail_json(msg=f"script failed with stacktrace:\n {result}", output="") |
| 187 |
|
| 188 |
module.exit_json( |
| 189 |
output=result, |
| 190 |
) |
| 191 |
|
| 192 |
|
| 193 |
if __name__ == "__main__": |
| 194 |
main() |