summaryrefslogtreecommitdiff
path: root/web_infrastructure/jenkins_job.py
blob: 0c91c8b876e9ee409f931834d680bedb00f9af9c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
#!/usr/bin/python
#
# This is a free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This Ansible library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this library.  If not, see <http://www.gnu.org/licenses/>.

ANSIBLE_METADATA = {'status': ['preview'],
                    'supported_by': 'community',
                    'version': '1.0'}

DOCUMENTATION = '''
---
module: jenkins_job
short_description: Manage jenkins jobs
description:
    - Manage Jenkins jobs by using Jenkins REST API.
requirements:
  - "python-jenkins >= 0.4.12"
  - "lxml >= 3.3.3"
version_added: "2.2"
author: "Sergio Millan Rodriguez (@sermilrod)"
options:
  config:
    description:
      - config in XML format.
      - Required if job does not yet exist.
      - Mututally exclusive with C(enabled).
      - Considered if C(state=present).
    required: false
  enabled:
    description:
      - Whether the job should be enabled or disabled.
      - Mututally exclusive with C(config).
      - Considered if C(state=present).
    required: false
  name:
    description:
      - Name of the Jenkins job.
    required: true
  password:
    description:
      - Password to authenticate with the Jenkins server.
    required: false
  state:
    description:
      - Attribute that specifies if the job has to be created or deleted.
    required: false
    default: present
    choices: ['present', 'absent']
  token:
    description:
      - API token used to authenticate alternatively to password.
    required: false
  url:
    description:
      - Url where the Jenkins server is accessible.
    required: false
    default: http://localhost:8080
  user:
    description:
       - User to authenticate with the Jenkins server.
    required: false
'''

EXAMPLES = '''
# Create a jenkins job using basic authentication
- jenkins_job:
    config: "{{ lookup('file', 'templates/test.xml') }}"
    name: test
    password: admin
    url: "http://localhost:8080"
    user: admin

# Create a jenkins job using the token
- jenkins_job:
    config: "{{ lookup('template', 'templates/test.xml.j2') }}"
    name: test
    token: asdfasfasfasdfasdfadfasfasdfasdfc
    url: "http://localhost:8080"
    user: admin

# Delete a jenkins job using basic authentication
- jenkins_job:
    name: test
    password: admin
    state: absent
    url: "http://localhost:8080"
    user: admin

# Delete a jenkins job using the token
- jenkins_job:
    name: test
    token: asdfasfasfasdfasdfadfasfasdfasdfc
    state: absent
    url: "http://localhost:8080"
    user: admin

# Disable a jenkins job using basic authentication
- jenkins_job:
    name: test
    password: admin
    enabled: false
    url: "http://localhost:8080"
    user: admin

# Disable a jenkins job using the token
- jenkins_job:
    name: test
    token: asdfasfasfasdfasdfadfasfasdfasdfc
    enabled: false
    url: "http://localhost:8080"
    user: admin
'''

RETURN = '''
---
name:
  description: Name of the jenkins job.
  returned: success
  type: string
  sample: test-job
state:
  description: State of the jenkins job.
  returned: success
  type: string
  sample: present
enabled:
  description: Whether the jenkins job is enabled or not.
  returned: success
  type: bool
  sample: true
user:
  description: User used for authentication.
  returned: success
  type: string
  sample: admin
url:
  description: Url to connect to the Jenkins server.
  returned: success
  type: string
  sample: https://jenkins.mydomain.com
'''

try:
    import jenkins
    python_jenkins_installed = True
except ImportError:
    python_jenkins_installed = False

try:
    from lxml import etree as ET
    python_lxml_installed = True
except ImportError:
    python_lxml_installed = False

class JenkinsJob:
    def __init__(self, module):
        self.module = module

        self.config = module.params.get('config')
        self.name = module.params.get('name')
        self.password = module.params.get('password')
        self.state = module.params.get('state')
        self.enabled = module.params.get('enabled')
        self.token = module.params.get('token')
        self.user = module.params.get('user')
        self.jenkins_url = module.params.get('url')
        self.server = self.get_jenkins_connection()

        self.result = {
            'changed': False,
            'url': self.jenkins_url,
            'name': self.name,
            'user': self.user,
            'state': self.state,
            'diff': {
                'before': "",
                'after': ""
            }
        }

    def get_jenkins_connection(self):
        try:
            if (self.user and self.password):
                return jenkins.Jenkins(self.jenkins_url, self.user, self.password)
            elif (self.user and self.token):
                return jenkins.Jenkins(self.jenkins_url, self.user, self.token)
            elif (self.user and not (self.password or self.token)):
                return jenkins.Jenkins(self.jenkins_url, self.user)
            else:
                return jenkins.Jenkins(self.jenkins_url)
        except Exception:
            e = get_exception()
            self.module.fail_json(msg='Unable to connect to Jenkins server, %s' % str(e))

    def get_job_status(self):
        try:
            return self.server.get_job_info(self.name)['color'].encode('utf-8')
        except Exception:
            e = get_exception()
            self.module.fail_json(msg='Unable to fetch job information, %s' % str(e))

    def job_exists(self):
        try:
            return bool(self.server.job_exists(self.name))
        except Exception:
            e = get_exception()
            self.module.fail_json(msg='Unable to validate if job exists, %s for %s' % (str(e), self.jenkins_url))

    def get_config(self):
        return job_config_to_string(self.config)

    def get_current_config(self):
        return job_config_to_string(self.server.get_job_config(self.name).encode('utf-8'))

    def has_config_changed(self):
        # config is optional, if not provided we keep the current config as is
        if self.config is None:
            return False

        config_file = self.get_config()
        machine_file = self.get_current_config()

        self.result['diff']['after'] = config_file
        self.result['diff']['before'] = machine_file

        if machine_file != config_file:
            return True
        return False

    def present_job(self):
        if self.config is None and self.enabled is None:
            self.module.fail_json(msg='one of the following params is required on state=present: config,enabled')

        if not self.job_exists():
            self.create_job()
        else:
            self.update_job()

    def has_state_changed(self, status):
        # Keep in current state if enabled arg_spec is not given
        if self.enabled is None:
            return False

        if ( (self.enabled == False and status != "disabled") or (self.enabled == True and status == "disabled") ):
            return True
        return False

    def switch_state(self):
        if self.enabled == False:
            self.server.disable_job(self.name)
        else:
            self.server.enable_job(self.name)

    def update_job(self):
        try:
            status = self.get_job_status()

            # Handle job config
            if self.has_config_changed():
                self.result['changed'] = True
                if not self.module.check_mode:
                    self.server.reconfig_job(self.name, self.get_config())

            # Handle job disable/enable
            elif self.has_state_changed(status):
                self.result['changed'] = True
                if not self.module.check_mode:
                    self.switch_state()

        except Exception:
            e = get_exception()
            self.module.fail_json(msg='Unable to reconfigure job, %s for %s' % (str(e), self.jenkins_url))

    def create_job(self):
        if self.config is None:
            self.module.fail_json(msg='missing required param: config')

        self.result['changed'] = True
        try:
            config_file = self.get_config()
            self.result['diff']['after'] = config_file
            if not self.module.check_mode:
                self.server.create_job(self.name, config_file)
        except Exception:
            e = get_exception()
            self.module.fail_json(msg='Unable to create job, %s for %s' % (str(e), self.jenkins_url))

    def absent_job(self):
        if self.job_exists():
            self.result['changed'] = True
            self.result['diff']['before'] = self.get_current_config()
            if not self.module.check_mode:
                try:
                    self.server.delete_job(self.name)
                except Exception:
                    e = get_exception()
                    self.module.fail_json(msg='Unable to delete job, %s for %s' % (str(e), self.jenkins_url))

    def get_result(self):
        result = self.result
        if self.job_exists():
            result['enabled'] = self.get_job_status() != "disabled"
        else:
            result['enabled'] = None
        return result

def test_dependencies(module):
    if not python_jenkins_installed:
        module.fail_json(msg="python-jenkins required for this module. "\
              "see http://python-jenkins.readthedocs.io/en/latest/install.html")

    if not python_lxml_installed:
        module.fail_json(msg="lxml required for this module. "\
              "see http://lxml.de/installation.html")

def job_config_to_string(xml_str):
    return ET.tostring(ET.fromstring(xml_str))

def main():
    module = AnsibleModule(
        argument_spec = dict(
            config      = dict(required=False),
            name        = dict(required=True),
            password    = dict(required=False, no_log=True),
            state       = dict(required=False, choices=['present', 'absent'], default="present"),
            enabled     = dict(required=False, type='bool'),
            token       = dict(required=False, no_log=True),
            url         = dict(required=False, default="http://localhost:8080"),
            user        = dict(required=False)
        ),
        mutually_exclusive = [
            ['password', 'token'],
            ['config', 'enabled'],
        ],
        supports_check_mode=True,
    )

    test_dependencies(module)
    jenkins_job = JenkinsJob(module)

    if module.params.get('state') == "present":
        jenkins_job.present_job()
    else:
        jenkins_job.absent_job()

    result = jenkins_job.get_result()
    module.exit_json(**result)


from ansible.module_utils.basic import *
if __name__ == '__main__':
    main()