| 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_job |
| 11 |
short_description: Manage jenkins jobs |
| 12 |
description: |
| 13 |
- Manage Jenkins jobs by using Jenkins REST API. |
| 14 |
requirements: |
| 15 |
- "python-jenkins >= 0.4.12" |
| 16 |
author: "Sergio Millan Rodriguez (@sermilrod)" |
| 17 |
extends_documentation_fragment: |
| 18 |
- community.general._attributes |
| 19 |
attributes: |
| 20 |
check_mode: |
| 21 |
support: full |
| 22 |
diff_mode: |
| 23 |
support: full |
| 24 |
options: |
| 25 |
config: |
| 26 |
type: str |
| 27 |
description: |
| 28 |
- Config in XML format. |
| 29 |
- Required if job does not yet exist. |
| 30 |
- Mutually exclusive with O(enabled). |
| 31 |
- Considered if O(state=present). |
| 32 |
enabled: |
| 33 |
description: |
| 34 |
- Whether the job should be enabled or disabled. |
| 35 |
- Mutually exclusive with O(config). |
| 36 |
- Considered if O(state=present). |
| 37 |
type: bool |
| 38 |
name: |
| 39 |
type: str |
| 40 |
description: |
| 41 |
- Name of the Jenkins job. |
| 42 |
required: true |
| 43 |
password: |
| 44 |
type: str |
| 45 |
description: |
| 46 |
- Password to authenticate with the Jenkins server. |
| 47 |
state: |
| 48 |
type: str |
| 49 |
description: |
| 50 |
- Attribute that specifies if the job has to be created or deleted. |
| 51 |
default: present |
| 52 |
choices: ['present', 'absent'] |
| 53 |
token: |
| 54 |
type: str |
| 55 |
description: |
| 56 |
- API token used to authenticate alternatively to password. |
| 57 |
url: |
| 58 |
type: str |
| 59 |
description: |
| 60 |
- URL where the Jenkins server is accessible. |
| 61 |
default: http://localhost:8080 |
| 62 |
user: |
| 63 |
type: str |
| 64 |
description: |
| 65 |
- User to authenticate with the Jenkins server. |
| 66 |
validate_certs: |
| 67 |
type: bool |
| 68 |
default: true |
| 69 |
description: |
| 70 |
- If set to V(false), the SSL certificates are not validated. This should only set to V(false) used on personally controlled |
| 71 |
sites using self-signed certificates as it avoids verifying the source site. |
| 72 |
- The C(python-jenkins) library only handles this by using the environment variable E(PYTHONHTTPSVERIFY). |
| 73 |
version_added: 2.3.0 |
| 74 |
""" |
| 75 |
|
| 76 |
EXAMPLES = r""" |
| 77 |
- name: Create a jenkins job using basic authentication |
| 78 |
community.general.jenkins_job: |
| 79 |
config: "{{ lookup('file', 'templates/test.xml') }}" |
| 80 |
name: test |
| 81 |
password: admin |
| 82 |
url: http://localhost:8080 |
| 83 |
user: admin |
| 84 |
|
| 85 |
- name: Create a jenkins job using the token |
| 86 |
community.general.jenkins_job: |
| 87 |
config: "{{ lookup('template', 'templates/test.xml.j2') }}" |
| 88 |
name: test |
| 89 |
token: asdfasfasfasdfasdfadfasfasdfasdfc |
| 90 |
url: http://localhost:8080 |
| 91 |
user: admin |
| 92 |
|
| 93 |
- name: Delete a jenkins job using basic authentication |
| 94 |
community.general.jenkins_job: |
| 95 |
name: test |
| 96 |
password: admin |
| 97 |
state: absent |
| 98 |
url: http://localhost:8080 |
| 99 |
user: admin |
| 100 |
|
| 101 |
- name: Delete a jenkins job using the token |
| 102 |
community.general.jenkins_job: |
| 103 |
name: test |
| 104 |
token: asdfasfasfasdfasdfadfasfasdfasdfc |
| 105 |
state: absent |
| 106 |
url: http://localhost:8080 |
| 107 |
user: admin |
| 108 |
|
| 109 |
- name: Disable a jenkins job using basic authentication |
| 110 |
community.general.jenkins_job: |
| 111 |
name: test |
| 112 |
password: admin |
| 113 |
enabled: false |
| 114 |
url: http://localhost:8080 |
| 115 |
user: admin |
| 116 |
|
| 117 |
- name: Disable a jenkins job using the token |
| 118 |
community.general.jenkins_job: |
| 119 |
name: test |
| 120 |
token: asdfasfasfasdfasdfadfasfasdfasdfc |
| 121 |
enabled: false |
| 122 |
url: http://localhost:8080 |
| 123 |
user: admin |
| 124 |
""" |
| 125 |
|
| 126 |
RETURN = r""" |
| 127 |
name: |
| 128 |
description: Name of the jenkins job. |
| 129 |
returned: success |
| 130 |
type: str |
| 131 |
sample: test-job |
| 132 |
state: |
| 133 |
description: State of the jenkins job. |
| 134 |
returned: success |
| 135 |
type: str |
| 136 |
sample: present |
| 137 |
enabled: |
| 138 |
description: Whether the jenkins job is enabled or not. |
| 139 |
returned: success |
| 140 |
type: bool |
| 141 |
sample: true |
| 142 |
user: |
| 143 |
description: User used for authentication. |
| 144 |
returned: success |
| 145 |
type: str |
| 146 |
sample: admin |
| 147 |
url: |
| 148 |
description: URL to connect to the Jenkins server. |
| 149 |
returned: success |
| 150 |
type: str |
| 151 |
sample: https://jenkins.mydomain.com |
| 152 |
""" |
| 153 |
|
| 154 |
import os |
| 155 |
import traceback |
| 156 |
import xml.etree.ElementTree as ET |
| 157 |
|
| 158 |
JENKINS_IMP_ERR = None |
| 159 |
try: |
| 160 |
import jenkins |
| 161 |
|
| 162 |
python_jenkins_installed = True |
| 163 |
except ImportError: |
| 164 |
JENKINS_IMP_ERR = traceback.format_exc() |
| 165 |
python_jenkins_installed = False |
| 166 |
|
| 167 |
from ansible.module_utils.basic import AnsibleModule, missing_required_lib |
| 168 |
from ansible.module_utils.common.text.converters import to_native |
| 169 |
|
| 170 |
|
| 171 |
class JenkinsJob: |
| 172 |
def __init__(self, module): |
| 173 |
self.module = module |
| 174 |
|
| 175 |
self.config = module.params.get("config") |
| 176 |
self.name = module.params.get("name") |
| 177 |
self.password = module.params.get("password") |
| 178 |
self.state = module.params.get("state") |
| 179 |
self.enabled = module.params.get("enabled") |
| 180 |
self.token = module.params.get("token") |
| 181 |
self.user = module.params.get("user") |
| 182 |
self.jenkins_url = module.params.get("url") |
| 183 |
self.server = self.get_jenkins_connection() |
| 184 |
|
| 185 |
self.result = { |
| 186 |
"changed": False, |
| 187 |
"url": self.jenkins_url, |
| 188 |
"name": self.name, |
| 189 |
"user": self.user, |
| 190 |
"state": self.state, |
| 191 |
"diff": {"before": "", "after": ""}, |
| 192 |
} |
| 193 |
|
| 194 |
self.EXCL_STATE = "excluded state" |
| 195 |
if not module.params["validate_certs"]: |
| 196 |
os.environ["PYTHONHTTPSVERIFY"] = "0" |
| 197 |
|
| 198 |
def get_jenkins_connection(self): |
| 199 |
try: |
| 200 |
if self.user and self.password: |
| 201 |
return jenkins.Jenkins(self.jenkins_url, self.user, self.password) |
| 202 |
elif self.user and self.token: |
| 203 |
return jenkins.Jenkins(self.jenkins_url, self.user, self.token) |
| 204 |
elif self.user and not (self.password or self.token): |
| 205 |
return jenkins.Jenkins(self.jenkins_url, self.user) |
| 206 |
else: |
| 207 |
return jenkins.Jenkins(self.jenkins_url) |
| 208 |
except Exception as e: |
| 209 |
self.module.fail_json(msg=f"Unable to connect to Jenkins server, {e}", exception=traceback.format_exc()) |
| 210 |
|
| 211 |
def get_job_status(self): |
| 212 |
try: |
| 213 |
response = self.server.get_job_info(self.name) |
| 214 |
if "color" not in response: |
| 215 |
return self.EXCL_STATE |
| 216 |
else: |
| 217 |
return to_native(response["color"]) |
| 218 |
|
| 219 |
except Exception as e: |
| 220 |
self.module.fail_json(msg=f"Unable to fetch job information, {e}", exception=traceback.format_exc()) |
| 221 |
|
| 222 |
def job_exists(self): |
| 223 |
try: |
| 224 |
return bool(self.server.job_exists(self.name)) |
| 225 |
except Exception as e: |
| 226 |
self.module.fail_json( |
| 227 |
msg=f"Unable to validate if job exists, {e} for {self.jenkins_url}", exception=traceback.format_exc() |
| 228 |
) |
| 229 |
|
| 230 |
def get_config(self): |
| 231 |
return job_config_to_string(self.config) |
| 232 |
|
| 233 |
def get_current_config(self): |
| 234 |
return job_config_to_string(self.server.get_job_config(self.name).encode("utf-8")) |
| 235 |
|
| 236 |
def has_config_changed(self): |
| 237 |
# config is optional, if not provided we keep the current config as is |
| 238 |
if self.config is None: |
| 239 |
return False |
| 240 |
|
| 241 |
config_file = self.get_config() |
| 242 |
machine_file = self.get_current_config() |
| 243 |
|
| 244 |
self.result["diff"]["after"] = config_file |
| 245 |
self.result["diff"]["before"] = machine_file |
| 246 |
|
| 247 |
return machine_file != config_file |
| 248 |
|
| 249 |
def present_job(self): |
| 250 |
if self.config is None and self.enabled is None: |
| 251 |
self.module.fail_json(msg="one of the following params is required on state=present: config,enabled") |
| 252 |
|
| 253 |
if not self.job_exists(): |
| 254 |
self.create_job() |
| 255 |
else: |
| 256 |
self.update_job() |
| 257 |
|
| 258 |
def has_state_changed(self, status): |
| 259 |
# Keep in current state if enabled arg_spec is not given |
| 260 |
if self.enabled is None: |
| 261 |
return False |
| 262 |
|
| 263 |
return (self.enabled is False and status != "disabled") or (self.enabled is True and status == "disabled") |
| 264 |
|
| 265 |
def switch_state(self): |
| 266 |
if self.enabled is False: |
| 267 |
self.server.disable_job(self.name) |
| 268 |
else: |
| 269 |
self.server.enable_job(self.name) |
| 270 |
|
| 271 |
def update_job(self): |
| 272 |
try: |
| 273 |
status = self.get_job_status() |
| 274 |
|
| 275 |
# Handle job config |
| 276 |
if self.has_config_changed(): |
| 277 |
self.result["changed"] = True |
| 278 |
if not self.module.check_mode: |
| 279 |
self.server.reconfig_job(self.name, self.get_config()) |
| 280 |
|
| 281 |
# Handle job disable/enable |
| 282 |
elif status != self.EXCL_STATE and self.has_state_changed(status): |
| 283 |
self.result["changed"] = True |
| 284 |
if not self.module.check_mode: |
| 285 |
self.switch_state() |
| 286 |
|
| 287 |
except Exception as e: |
| 288 |
self.module.fail_json( |
| 289 |
msg=f"Unable to reconfigure job, {e} for {self.jenkins_url}", exception=traceback.format_exc() |
| 290 |
) |
| 291 |
|
| 292 |
def create_job(self): |
| 293 |
if self.config is None: |
| 294 |
self.module.fail_json(msg="missing required param: config") |
| 295 |
|
| 296 |
self.result["changed"] = True |
| 297 |
try: |
| 298 |
config_file = self.get_config() |
| 299 |
self.result["diff"]["after"] = config_file |
| 300 |
if not self.module.check_mode: |
| 301 |
self.server.create_job(self.name, config_file) |
| 302 |
except Exception as e: |
| 303 |
self.module.fail_json( |
| 304 |
msg=f"Unable to create job, {e} for {self.jenkins_url}", exception=traceback.format_exc() |
| 305 |
) |
| 306 |
|
| 307 |
def absent_job(self): |
| 308 |
if self.job_exists(): |
| 309 |
self.result["changed"] = True |
| 310 |
self.result["diff"]["before"] = self.get_current_config() |
| 311 |
if not self.module.check_mode: |
| 312 |
try: |
| 313 |
self.server.delete_job(self.name) |
| 314 |
except Exception as e: |
| 315 |
self.module.fail_json( |
| 316 |
msg=f"Unable to delete job, {e} for {self.jenkins_url}", exception=traceback.format_exc() |
| 317 |
) |
| 318 |
|
| 319 |
def get_result(self): |
| 320 |
result = self.result |
| 321 |
if self.job_exists(): |
| 322 |
result["enabled"] = self.get_job_status() != "disabled" |
| 323 |
else: |
| 324 |
result["enabled"] = None |
| 325 |
return result |
| 326 |
|
| 327 |
|
| 328 |
def test_dependencies(module): |
| 329 |
if not python_jenkins_installed: |
| 330 |
module.fail_json( |
| 331 |
msg=missing_required_lib( |
| 332 |
"python-jenkins", url="https://python-jenkins.readthedocs.io/en/latest/install.html" |
| 333 |
), |
| 334 |
exception=JENKINS_IMP_ERR, |
| 335 |
) |
| 336 |
|
| 337 |
|
| 338 |
def job_config_to_string(xml_str): |
| 339 |
return ET.tostring(ET.fromstring(xml_str)).decode("ascii") |
| 340 |
|
| 341 |
|
| 342 |
def main(): |
| 343 |
module = AnsibleModule( |
| 344 |
argument_spec=dict( |
| 345 |
config=dict(type="str"), |
| 346 |
name=dict(type="str", required=True), |
| 347 |
password=dict(type="str", no_log=True), |
| 348 |
state=dict(type="str", choices=["present", "absent"], default="present"), |
| 349 |
enabled=dict(type="bool"), |
| 350 |
token=dict(type="str", no_log=True), |
| 351 |
url=dict(type="str", default="http://localhost:8080"), |
| 352 |
user=dict(type="str"), |
| 353 |
validate_certs=dict(type="bool", default=True), |
| 354 |
), |
| 355 |
mutually_exclusive=[ |
| 356 |
["password", "token"], |
| 357 |
["config", "enabled"], |
| 358 |
], |
| 359 |
supports_check_mode=True, |
| 360 |
) |
| 361 |
|
| 362 |
test_dependencies(module) |
| 363 |
jenkins_job = JenkinsJob(module) |
| 364 |
|
| 365 |
if module.params.get("state") == "present": |
| 366 |
jenkins_job.present_job() |
| 367 |
else: |
| 368 |
jenkins_job.absent_job() |
| 369 |
|
| 370 |
result = jenkins_job.get_result() |
| 371 |
module.exit_json(**result) |
| 372 |
|
| 373 |
|
| 374 |
if __name__ == "__main__": |
| 375 |
main() |