Debian Codegraph @

ansible_collections/community/general/plugins/modules/jenkins_build_info.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_build_info
11 short_description: Get information about Jenkins builds
12 version_added: 7.4.0
13 description:
14 - Get information about Jenkins builds with Jenkins REST API.
15 requirements:
16 - "python-jenkins >= 0.4.12"
17 author:
18 - Juan Casanova (@juanmcasanova)
19 extends_documentation_fragment:
20 - community.general._attributes
21 - community.general._attributes.info_module
22 options:
23 name:
24 description:
25 - Name of the Jenkins job to which the build belongs.
26 required: true
27 type: str
28 build_number:
29 description:
30 - An integer which specifies a build of a job.
31 - If not specified the last build information is returned.
32 type: int
33 password:
34 description:
35 - Password to authenticate with the Jenkins server.
36 type: str
37 token:
38 description:
39 - API token used to authenticate with the Jenkins server.
40 type: str
41 url:
42 description:
43 - URL of the Jenkins server.
44 default: http://localhost:8080
45 type: str
46 user:
47 description:
48 - User to authenticate with the Jenkins server.
49 type: str
50 """
51
52 EXAMPLES = r"""
53 - name: Get information about a jenkins build using basic authentication
54 community.general.jenkins_build_info:
55 name: "test-check"
56 build_number: 1
57 user: admin
58 password: asdfg
59 url: http://localhost:8080
60
61 - name: Get information about a jenkins build anonymously
62 community.general.jenkins_build_info:
63 name: "stop-check"
64 build_number: 3
65 url: http://localhost:8080
66
67 - name: Get information about a jenkins build using token authentication
68 community.general.jenkins_build_info:
69 name: "delete-experiment"
70 build_number: 30
71 user: Jenkins
72 token: abcdefghijklmnopqrstuvwxyz123456
73 url: http://localhost:8080
74 """
75
76 RETURN = r"""
77 name:
78 description: Name of the jenkins job.
79 returned: success
80 type: str
81 sample: "test-job"
82 state:
83 description: State of the jenkins job.
84 returned: success
85 type: str
86 sample: present
87 user:
88 description: User used for authentication.
89 returned: success
90 type: str
91 sample: admin
92 url:
93 description: URL to connect to the Jenkins server.
94 returned: success
95 type: str
96 sample: https://jenkins.mydomain.com
97 build_info:
98 description: Build info of the jenkins job.
99 returned: success
100 type: dict
101 """
102
103 import traceback
104
105 JENKINS_IMP_ERR = None
106 try:
107 import jenkins
108
109 python_jenkins_installed = True
110 except ImportError:
111 JENKINS_IMP_ERR = traceback.format_exc()
112 python_jenkins_installed = False
113
114 from ansible.module_utils.basic import AnsibleModule, missing_required_lib
115
116
117 class JenkinsBuildInfo:
118 def __init__(self, module):
119 self.module = module
120
121 self.name = module.params.get("name")
122 self.password = module.params.get("password")
123 self.token = module.params.get("token")
124 self.user = module.params.get("user")
125 self.jenkins_url = module.params.get("url")
126 self.build_number = module.params.get("build_number")
127 self.server = self.get_jenkins_connection()
128
129 self.result = {
130 "changed": False,
131 "url": self.jenkins_url,
132 "name": self.name,
133 "user": self.user,
134 }
135
136 def get_jenkins_connection(self):
137 try:
138 if self.user and self.password:
139 return jenkins.Jenkins(self.jenkins_url, self.user, self.password)
140 elif self.user and self.token:
141 return jenkins.Jenkins(self.jenkins_url, self.user, self.token)
142 elif self.user and not (self.password or self.token):
143 return jenkins.Jenkins(self.jenkins_url, self.user)
144 else:
145 return jenkins.Jenkins(self.jenkins_url)
146 except Exception as e:
147 self.module.fail_json(msg=f"Unable to connect to Jenkins server, {e}")
148
149 def get_build_status(self):
150 try:
151 if self.build_number is None:
152 job_info = self.server.get_job_info(self.name)
153 self.build_number = job_info["lastBuild"]["number"]
154
155 return self.server.get_build_info(self.name, self.build_number)
156 except jenkins.JenkinsException:
157 response = {}
158 response["result"] = "ABSENT"
159 return response
160 except Exception as e:
161 self.module.fail_json(msg=f"Unable to fetch build information, {e}", exception=traceback.format_exc())
162
163 def get_result(self):
164 result = self.result
165 build_status = self.get_build_status()
166
167 if build_status["result"] == "ABSENT":
168 result["failed"] = True
169 result["build_info"] = build_status
170
171 return result
172
173
174 def test_dependencies(module):
175 if not python_jenkins_installed:
176 module.fail_json(
177 msg=missing_required_lib(
178 "python-jenkins", url="https://python-jenkins.readthedocs.io/en/latest/install.html"
179 ),
180 exception=JENKINS_IMP_ERR,
181 )
182
183
184 def main():
185 module = AnsibleModule(
186 argument_spec=dict(
187 build_number=dict(type="int"),
188 name=dict(required=True),
189 password=dict(no_log=True),
190 token=dict(no_log=True),
191 url=dict(default="http://localhost:8080"),
192 user=dict(),
193 ),
194 mutually_exclusive=[["password", "token"]],
195 supports_check_mode=True,
196 )
197
198 test_dependencies(module)
199 jenkins_build_info = JenkinsBuildInfo(module)
200
201 result = jenkins_build_info.get_result()
202 module.exit_json(**result)
203
204
205 if __name__ == "__main__":
206 main()