#!/usr/bin/python from ansible.module_utils.basic import * import subprocess class GitlabRunner: def __init__(self, name): self.name = name self.exist = self.name in open('/etc/gitlab-runner/config.toml').read() def register(self, url, token, executor, options): opts = [] for k, v in options.items(): if v is False: opts.append('--%s=false' % k) else: if isinstance(v, list): for av in v: opts.append('--%s' % k) opts.append(str(av)) else: opts.append('--%s' % k) if v is not True: opts.append(str(v)) subprocess.check_call(['gitlab-runner', 'register', '--non-interactive', '--name', self.name, '--url', url, '--registration-token', token, '--executor', executor, ] + opts ) def unregister(self): subprocess.check_call(['gitlab-runner', 'unregister', '--name', self.name]) def main(): changed = False fields = { 'name': { 'type': 'str', 'required': True }, 'url': { 'type': 'str', 'required': True }, 'token': { 'type': 'str', 'required': True, 'no_log': True }, 'executor': { 'type': 'str', 'required': True }, 'options': { 'type': 'dict', 'default': {} }, 'state': { 'type': 'str', 'default': 'present', 'choices': ['present', 'absent'] } } module = AnsibleModule(argument_spec=fields) runner = GitlabRunner(module.params['name']) if module.params['state'] == 'present': if not runner.exist: runner.register(module.params['url'], module.params['token'], module.params['executor'], module.params['options']) changed = True elif runner.exist: runner.unregister() changed = True module.exit_json(changed=changed) if __name__ == '__main__': main()