ansible/web_infrastructure/jenkins_job.py

359 lines
11 KiB
Python
Raw Normal View History

2016-09-05 22:04:33 +02:00
#!/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/>.
DOCUMENTATION = '''
---
module: jenkins_job
short_description: Manage jenkins jobs
description:
2016-09-10 18:26:30 +02:00
- Manage Jenkins jobs by using Jenkins REST API.
2016-09-05 22:04:33 +02:00
requirements:
- "python-jenkins >= 0.4.12"
- "lxml >= 3.3.3"
version_added: "2.2"
2016-09-10 09:07:09 +02:00
author: "Sergio Millan Rodriguez (@sermilrod)"
2016-09-05 22:04:33 +02:00
options:
config:
description:
- config in XML format.
- Required if job does not yet exist.
- Mututally exclusive with C(enabled).
- Considered if C(state=present).
2016-09-05 22:04:33 +02:00
required: false
enabled:
2016-09-05 22:04:33 +02:00
description:
- Whether the job should be enabled or disabled.
- Mututally exclusive with C(config).
- Considered if C(state=present).
2016-09-05 22:04:33 +02:00
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.
2016-09-10 09:07:09 +02:00
required: false
default: present
2016-09-05 22:04:33 +02:00
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
2016-09-05 22:04:33 +02:00
url: "http://localhost:8080"
user: admin
# Disable a jenkins job using the token
- jenkins_job:
name: test
token: asdfasfasfasdfasdfadfasfasdfasdfc
enabled: false
2016-09-05 22:04:33 +02:00
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
2016-09-10 18:26:30 +02:00
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
2016-09-05 22:04:33 +02:00
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
2016-09-10 18:26:30 +02:00
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')
2016-09-05 22:04:33 +02:00
self.server = self.get_jenkins_connection()
2016-09-10 18:26:30 +02:00
self.result = {
'changed': False,
'url': self.jenkins_url,
'name': self.name,
'user': self.user,
'state': self.state,
'diff': {
'before': "",
'after': ""
}
2016-09-10 17:21:42 +02:00
}
2016-09-05 22:04:33 +02:00
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()
2016-09-10 18:26:30 +02:00
self.module.fail_json(msg='Unable to connect to Jenkins server, %s' % str(e))
2016-09-05 22:04:33 +02:00
2016-09-10 18:26:30 +02:00
def get_job_status(self):
2016-09-05 22:04:33 +02:00
try:
return self.server.get_job_info(self.name)['color'].encode('utf-8')
except Exception:
e = get_exception()
2016-09-10 18:26:30 +02:00
self.module.fail_json(msg='Unable to fetch job information, %s' % str(e))
2016-09-05 22:04:33 +02:00
2016-09-10 18:26:30 +02:00
def job_exists(self):
2016-09-05 22:04:33 +02:00
try:
return bool(self.server.job_exists(self.name))
except Exception:
e = get_exception()
2016-09-10 18:26:30 +02:00
self.module.fail_json(msg='Unable to validate if job exists, %s for %s' % (str(e), self.jenkins_url))
2016-09-05 22:04:33 +02:00
def get_config(self):
return job_config_to_string(self.config)
2016-09-10 18:26:30 +02:00
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
2016-09-05 22:04:33 +02:00
config_file = self.get_config()
2016-09-10 18:26:30 +02:00
machine_file = self.get_current_config()
self.result['diff']['after'] = config_file
self.result['diff']['before'] = machine_file
if machine_file != config_file:
2016-09-10 18:26:30 +02:00
return True
return False
2016-09-05 22:04:33 +02:00
2016-09-10 18:26:30 +02:00
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')
2016-09-10 18:26:30 +02:00
if not self.job_exists():
self.create_job()
2016-09-05 22:04:33 +02:00
else:
2016-09-10 18:26:30 +02:00
self.update_job()
2016-09-05 22:04:33 +02:00
2016-09-10 18:26:30 +02:00
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") ):
2016-09-10 18:26:30 +02:00
return True
return False
2016-09-05 22:04:33 +02:00
2016-09-10 18:26:30 +02:00
def switch_state(self):
if self.enabled == False:
2016-09-05 22:04:33 +02:00
self.server.disable_job(self.name)
else:
self.server.enable_job(self.name)
2016-09-10 18:26:30 +02:00
def update_job(self):
2016-09-05 22:04:33 +02:00
try:
2016-09-10 18:26:30 +02:00
status = self.get_job_status()
# Handle job config
2016-09-10 18:26:30 +02:00
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
2016-09-10 18:26:30 +02:00
elif self.has_state_changed(status):
self.result['changed'] = True
if not self.module.check_mode:
self.switch_state()
2016-09-05 22:04:33 +02:00
except Exception:
e = get_exception()
2016-09-10 18:26:30 +02:00
self.module.fail_json(msg='Unable to reconfigure job, %s for %s' % (str(e), self.jenkins_url))
2016-09-10 18:26:30 +02:00
def create_job(self):
if self.config is None:
2016-09-10 18:26:30 +02:00
self.module.fail_json(msg='missing required param: config')
2016-09-10 18:26:30 +02:00
self.result['changed'] = True
2016-09-05 22:04:33 +02:00
try:
2016-09-10 17:21:42 +02:00
config_file = self.get_config()
2016-09-10 18:26:30 +02:00
self.result['diff']['after'] = config_file
if not self.module.check_mode:
2016-09-10 17:21:42 +02:00
self.server.create_job(self.name, config_file)
2016-09-05 22:04:33 +02:00
except Exception:
e = get_exception()
2016-09-10 18:26:30 +02:00
self.module.fail_json(msg='Unable to create job, %s for %s' % (str(e), self.jenkins_url))
2016-09-05 22:04:33 +02:00
2016-09-10 18:26:30 +02:00
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:
2016-09-05 22:04:33 +02:00
try:
self.server.delete_job(self.name)
except Exception:
e = get_exception()
2016-09-10 18:26:30 +02:00
self.module.fail_json(msg='Unable to delete job, %s for %s' % (str(e), self.jenkins_url))
2016-09-05 22:04:33 +02:00
2016-09-10 18:26:30 +02:00
def get_result(self):
result = self.result
if self.job_exists():
result['enabled'] = self.get_job_status() != "disabled"
else:
result['enabled'] = None
return result
2016-09-05 22:04:33 +02:00
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),
2016-09-10 09:07:09 +02:00
state = dict(required=False, choices=['present', 'absent'], default="present"),
enabled = dict(required=False, type='bool'),
2016-09-05 22:04:33 +02:00
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'],
2016-09-05 22:04:33 +02:00
],
supports_check_mode=True,
)
test_dependencies(module)
2016-09-10 18:26:30 +02:00
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)
2016-09-05 22:04:33 +02:00
from ansible.module_utils.basic import *
if __name__ == '__main__':
main()