mirror of
https://github.com/ansible-collections/community.general.git
synced 2025-07-24 13:50:22 -07:00
Initial commit
This commit is contained in:
commit
aebc1b03fd
4861 changed files with 812621 additions and 0 deletions
300
plugins/modules/source_control/gitlab/gitlab_deploy_key.py
Normal file
300
plugins/modules/source_control/gitlab/gitlab_deploy_key.py
Normal file
|
@ -0,0 +1,300 @@
|
|||
#!/usr/bin/python
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# Copyright: (c) 2019, Guillaume Martinez (lunik@tiwabbit.fr)
|
||||
# Copyright: (c) 2018, Marcus Watkins <marwatk@marcuswatkins.net>
|
||||
# Based on code:
|
||||
# Copyright: (c) 2013, Phillip Gentry <phillip@cx.com>
|
||||
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
|
||||
from __future__ import absolute_import, division, print_function
|
||||
__metaclass__ = type
|
||||
|
||||
ANSIBLE_METADATA = {'metadata_version': '1.1',
|
||||
'status': ['preview'],
|
||||
'supported_by': 'community'}
|
||||
|
||||
DOCUMENTATION = '''
|
||||
module: gitlab_deploy_key
|
||||
short_description: Manages GitLab project deploy keys.
|
||||
description:
|
||||
- Adds, updates and removes project deploy keys
|
||||
author:
|
||||
- Marcus Watkins (@marwatk)
|
||||
- Guillaume Martinez (@Lunik)
|
||||
requirements:
|
||||
- python >= 2.7
|
||||
- python-gitlab python module
|
||||
extends_documentation_fragment:
|
||||
- community.general.auth_basic
|
||||
|
||||
options:
|
||||
api_token:
|
||||
description:
|
||||
- GitLab token for logging in.
|
||||
type: str
|
||||
project:
|
||||
description:
|
||||
- Id or Full path of project in the form of group/name.
|
||||
required: true
|
||||
type: str
|
||||
title:
|
||||
description:
|
||||
- Deploy key's title.
|
||||
required: true
|
||||
type: str
|
||||
key:
|
||||
description:
|
||||
- Deploy key
|
||||
required: true
|
||||
type: str
|
||||
can_push:
|
||||
description:
|
||||
- Whether this key can push to the project.
|
||||
type: bool
|
||||
default: no
|
||||
state:
|
||||
description:
|
||||
- When C(present) the deploy key added to the project if it doesn't exist.
|
||||
- When C(absent) it will be removed from the project if it exists.
|
||||
required: true
|
||||
default: present
|
||||
type: str
|
||||
choices: [ "present", "absent" ]
|
||||
'''
|
||||
|
||||
EXAMPLES = '''
|
||||
- name: "Adding a project deploy key"
|
||||
gitlab_deploy_key:
|
||||
api_url: https://gitlab.example.com/
|
||||
api_token: "{{ api_token }}"
|
||||
project: "my_group/my_project"
|
||||
title: "Jenkins CI"
|
||||
state: present
|
||||
key: "ssh-rsa AAAAB3NzaC1yc2EAAAABJQAAAIEAiPWx6WM4lhHNedGfBpPJNPpZ7yKu+dnn1SJejgt4596k6YjzGGphH2TUxwKzxcKDKKezwkpfnxPkSMkuEspGRt/aZZ9w..."
|
||||
|
||||
- name: "Update the above deploy key to add push access"
|
||||
gitlab_deploy_key:
|
||||
api_url: https://gitlab.example.com/
|
||||
api_token: "{{ api_token }}"
|
||||
project: "my_group/my_project"
|
||||
title: "Jenkins CI"
|
||||
state: present
|
||||
can_push: yes
|
||||
|
||||
- name: "Remove the previous deploy key from the project"
|
||||
gitlab_deploy_key:
|
||||
api_url: https://gitlab.example.com/
|
||||
api_token: "{{ api_token }}"
|
||||
project: "my_group/my_project"
|
||||
state: absent
|
||||
key: "ssh-rsa AAAAB3NzaC1yc2EAAAABJQAAAIEAiPWx6WM4lhHNedGfBpPJNPpZ7yKu+dnn1SJejgt4596k6YjzGGphH2TUxwKzxcKDKKezwkpfnxPkSMkuEspGRt/aZZ9w..."
|
||||
|
||||
'''
|
||||
|
||||
RETURN = '''
|
||||
msg:
|
||||
description: Success or failure message
|
||||
returned: always
|
||||
type: str
|
||||
sample: "Success"
|
||||
|
||||
result:
|
||||
description: json parsed response from the server
|
||||
returned: always
|
||||
type: dict
|
||||
|
||||
error:
|
||||
description: the error message returned by the GitLab API
|
||||
returned: failed
|
||||
type: str
|
||||
sample: "400: key is already in use"
|
||||
|
||||
deploy_key:
|
||||
description: API object
|
||||
returned: always
|
||||
type: dict
|
||||
'''
|
||||
|
||||
import re
|
||||
import traceback
|
||||
|
||||
GITLAB_IMP_ERR = None
|
||||
try:
|
||||
import gitlab
|
||||
HAS_GITLAB_PACKAGE = True
|
||||
except Exception:
|
||||
GITLAB_IMP_ERR = traceback.format_exc()
|
||||
HAS_GITLAB_PACKAGE = False
|
||||
|
||||
from ansible.module_utils.api import basic_auth_argument_spec
|
||||
from ansible.module_utils.basic import AnsibleModule, missing_required_lib
|
||||
from ansible.module_utils._text import to_native
|
||||
|
||||
from ansible_collections.community.general.plugins.module_utils.gitlab import findProject, gitlabAuthentication
|
||||
|
||||
|
||||
class GitLabDeployKey(object):
|
||||
def __init__(self, module, gitlab_instance):
|
||||
self._module = module
|
||||
self._gitlab = gitlab_instance
|
||||
self.deployKeyObject = None
|
||||
|
||||
'''
|
||||
@param project Project object
|
||||
@param key_title Title of the key
|
||||
@param key_key String of the key
|
||||
@param key_can_push Option of the deployKey
|
||||
@param options Deploy key options
|
||||
'''
|
||||
def createOrUpdateDeployKey(self, project, key_title, key_key, options):
|
||||
changed = False
|
||||
|
||||
# Because we have already call existsDeployKey in main()
|
||||
if self.deployKeyObject is None:
|
||||
deployKey = self.createDeployKey(project, {
|
||||
'title': key_title,
|
||||
'key': key_key,
|
||||
'can_push': options['can_push']})
|
||||
changed = True
|
||||
else:
|
||||
changed, deployKey = self.updateDeployKey(self.deployKeyObject, {
|
||||
'can_push': options['can_push']})
|
||||
|
||||
self.deployKeyObject = deployKey
|
||||
if changed:
|
||||
if self._module.check_mode:
|
||||
self._module.exit_json(changed=True, msg="Successfully created or updated the deploy key %s" % key_title)
|
||||
|
||||
try:
|
||||
deployKey.save()
|
||||
except Exception as e:
|
||||
self._module.fail_json(msg="Failed to update deploy key: %s " % e)
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
|
||||
'''
|
||||
@param project Project Object
|
||||
@param arguments Attributes of the deployKey
|
||||
'''
|
||||
def createDeployKey(self, project, arguments):
|
||||
if self._module.check_mode:
|
||||
return True
|
||||
|
||||
try:
|
||||
deployKey = project.keys.create(arguments)
|
||||
except (gitlab.exceptions.GitlabCreateError) as e:
|
||||
self._module.fail_json(msg="Failed to create deploy key: %s " % to_native(e))
|
||||
|
||||
return deployKey
|
||||
|
||||
'''
|
||||
@param deployKey Deploy Key Object
|
||||
@param arguments Attributes of the deployKey
|
||||
'''
|
||||
def updateDeployKey(self, deployKey, arguments):
|
||||
changed = False
|
||||
|
||||
for arg_key, arg_value in arguments.items():
|
||||
if arguments[arg_key] is not None:
|
||||
if getattr(deployKey, arg_key) != arguments[arg_key]:
|
||||
setattr(deployKey, arg_key, arguments[arg_key])
|
||||
changed = True
|
||||
|
||||
return (changed, deployKey)
|
||||
|
||||
'''
|
||||
@param project Project object
|
||||
@param key_title Title of the key
|
||||
'''
|
||||
def findDeployKey(self, project, key_title):
|
||||
deployKeys = project.keys.list()
|
||||
for deployKey in deployKeys:
|
||||
if (deployKey.title == key_title):
|
||||
return deployKey
|
||||
|
||||
'''
|
||||
@param project Project object
|
||||
@param key_title Title of the key
|
||||
'''
|
||||
def existsDeployKey(self, project, key_title):
|
||||
# When project exists, object will be stored in self.projectObject.
|
||||
deployKey = self.findDeployKey(project, key_title)
|
||||
if deployKey:
|
||||
self.deployKeyObject = deployKey
|
||||
return True
|
||||
return False
|
||||
|
||||
def deleteDeployKey(self):
|
||||
if self._module.check_mode:
|
||||
return True
|
||||
|
||||
return self.deployKeyObject.delete()
|
||||
|
||||
|
||||
def main():
|
||||
argument_spec = basic_auth_argument_spec()
|
||||
argument_spec.update(dict(
|
||||
api_token=dict(type='str', no_log=True),
|
||||
state=dict(type='str', default="present", choices=["absent", "present"]),
|
||||
project=dict(type='str', required=True),
|
||||
key=dict(type='str', required=True),
|
||||
can_push=dict(type='bool', default=False),
|
||||
title=dict(type='str', required=True)
|
||||
))
|
||||
|
||||
module = AnsibleModule(
|
||||
argument_spec=argument_spec,
|
||||
mutually_exclusive=[
|
||||
['api_username', 'api_token'],
|
||||
['api_password', 'api_token']
|
||||
],
|
||||
required_together=[
|
||||
['api_username', 'api_password']
|
||||
],
|
||||
required_one_of=[
|
||||
['api_username', 'api_token']
|
||||
],
|
||||
supports_check_mode=True,
|
||||
)
|
||||
|
||||
state = module.params['state']
|
||||
project_identifier = module.params['project']
|
||||
key_title = module.params['title']
|
||||
key_keyfile = module.params['key']
|
||||
key_can_push = module.params['can_push']
|
||||
|
||||
if not HAS_GITLAB_PACKAGE:
|
||||
module.fail_json(msg=missing_required_lib("python-gitlab"), exception=GITLAB_IMP_ERR)
|
||||
|
||||
gitlab_instance = gitlabAuthentication(module)
|
||||
|
||||
gitlab_deploy_key = GitLabDeployKey(module, gitlab_instance)
|
||||
|
||||
project = findProject(gitlab_instance, project_identifier)
|
||||
|
||||
if project is None:
|
||||
module.fail_json(msg="Failed to create deploy key: project %s doesn't exists" % project_identifier)
|
||||
|
||||
deployKey_exists = gitlab_deploy_key.existsDeployKey(project, key_title)
|
||||
|
||||
if state == 'absent':
|
||||
if deployKey_exists:
|
||||
gitlab_deploy_key.deleteDeployKey()
|
||||
module.exit_json(changed=True, msg="Successfully deleted deploy key %s" % key_title)
|
||||
else:
|
||||
module.exit_json(changed=False, msg="Deploy key deleted or does not exists")
|
||||
|
||||
if state == 'present':
|
||||
if gitlab_deploy_key.createOrUpdateDeployKey(project, key_title, key_keyfile, {'can_push': key_can_push}):
|
||||
|
||||
module.exit_json(changed=True, msg="Successfully created or updated the deploy key %s" % key_title,
|
||||
deploy_key=gitlab_deploy_key.deployKeyObject._attrs)
|
||||
else:
|
||||
module.exit_json(changed=False, msg="No need to update the deploy key %s" % key_title,
|
||||
deploy_key=gitlab_deploy_key.deployKeyObject._attrs)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
324
plugins/modules/source_control/gitlab/gitlab_group.py
Normal file
324
plugins/modules/source_control/gitlab/gitlab_group.py
Normal file
|
@ -0,0 +1,324 @@
|
|||
#!/usr/bin/python
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# Copyright: (c) 2019, Guillaume Martinez (lunik@tiwabbit.fr)
|
||||
# Copyright: (c) 2015, Werner Dijkerman (ikben@werner-dijkerman.nl)
|
||||
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
|
||||
from __future__ import absolute_import, division, print_function
|
||||
__metaclass__ = type
|
||||
|
||||
ANSIBLE_METADATA = {'metadata_version': '1.1',
|
||||
'status': ['preview'],
|
||||
'supported_by': 'community'}
|
||||
|
||||
DOCUMENTATION = '''
|
||||
---
|
||||
module: gitlab_group
|
||||
short_description: Creates/updates/deletes GitLab Groups
|
||||
description:
|
||||
- When the group does not exist in GitLab, it will be created.
|
||||
- When the group does exist and state=absent, the group will be deleted.
|
||||
author:
|
||||
- Werner Dijkerman (@dj-wasabi)
|
||||
- Guillaume Martinez (@Lunik)
|
||||
requirements:
|
||||
- python >= 2.7
|
||||
- python-gitlab python module
|
||||
extends_documentation_fragment:
|
||||
- community.general.auth_basic
|
||||
|
||||
options:
|
||||
api_token:
|
||||
description:
|
||||
- GitLab token for logging in.
|
||||
type: str
|
||||
name:
|
||||
description:
|
||||
- Name of the group you want to create.
|
||||
required: true
|
||||
type: str
|
||||
path:
|
||||
description:
|
||||
- The path of the group you want to create, this will be api_url/group_path
|
||||
- If not supplied, the group_name will be used.
|
||||
type: str
|
||||
description:
|
||||
description:
|
||||
- A description for the group.
|
||||
type: str
|
||||
state:
|
||||
description:
|
||||
- create or delete group.
|
||||
- Possible values are present and absent.
|
||||
default: present
|
||||
type: str
|
||||
choices: ["present", "absent"]
|
||||
parent:
|
||||
description:
|
||||
- Allow to create subgroups
|
||||
- Id or Full path of parent group in the form of group/name
|
||||
type: str
|
||||
visibility:
|
||||
description:
|
||||
- Default visibility of the group
|
||||
choices: ["private", "internal", "public"]
|
||||
default: private
|
||||
type: str
|
||||
'''
|
||||
|
||||
EXAMPLES = '''
|
||||
- name: "Delete GitLab Group"
|
||||
gitlab_group:
|
||||
api_url: https://gitlab.example.com/
|
||||
api_token: "{{ access_token }}"
|
||||
validate_certs: False
|
||||
name: my_first_group
|
||||
state: absent
|
||||
|
||||
- name: "Create GitLab Group"
|
||||
gitlab_group:
|
||||
api_url: https://gitlab.example.com/
|
||||
validate_certs: True
|
||||
api_username: dj-wasabi
|
||||
api_password: "MySecretPassword"
|
||||
name: my_first_group
|
||||
path: my_first_group
|
||||
state: present
|
||||
|
||||
# The group will by created at https://gitlab.dj-wasabi.local/super_parent/parent/my_first_group
|
||||
- name: "Create GitLab SubGroup"
|
||||
gitlab_group:
|
||||
api_url: https://gitlab.example.com/
|
||||
validate_certs: True
|
||||
api_username: dj-wasabi
|
||||
api_password: "MySecretPassword"
|
||||
name: my_first_group
|
||||
path: my_first_group
|
||||
state: present
|
||||
parent: "super_parent/parent"
|
||||
'''
|
||||
|
||||
RETURN = '''
|
||||
msg:
|
||||
description: Success or failure message
|
||||
returned: always
|
||||
type: str
|
||||
sample: "Success"
|
||||
|
||||
result:
|
||||
description: json parsed response from the server
|
||||
returned: always
|
||||
type: dict
|
||||
|
||||
error:
|
||||
description: the error message returned by the GitLab API
|
||||
returned: failed
|
||||
type: str
|
||||
sample: "400: path is already in use"
|
||||
|
||||
group:
|
||||
description: API object
|
||||
returned: always
|
||||
type: dict
|
||||
'''
|
||||
|
||||
import traceback
|
||||
|
||||
GITLAB_IMP_ERR = None
|
||||
try:
|
||||
import gitlab
|
||||
HAS_GITLAB_PACKAGE = True
|
||||
except Exception:
|
||||
GITLAB_IMP_ERR = traceback.format_exc()
|
||||
HAS_GITLAB_PACKAGE = False
|
||||
|
||||
from ansible.module_utils.api import basic_auth_argument_spec
|
||||
from ansible.module_utils.basic import AnsibleModule, missing_required_lib
|
||||
from ansible.module_utils._text import to_native
|
||||
|
||||
from ansible_collections.community.general.plugins.module_utils.gitlab import findGroup, gitlabAuthentication
|
||||
|
||||
|
||||
class GitLabGroup(object):
|
||||
def __init__(self, module, gitlab_instance):
|
||||
self._module = module
|
||||
self._gitlab = gitlab_instance
|
||||
self.groupObject = None
|
||||
|
||||
'''
|
||||
@param group Group object
|
||||
'''
|
||||
def getGroupId(self, group):
|
||||
if group is not None:
|
||||
return group.id
|
||||
return None
|
||||
|
||||
'''
|
||||
@param name Name of the group
|
||||
@param parent Parent group full path
|
||||
@param options Group options
|
||||
'''
|
||||
def createOrUpdateGroup(self, name, parent, options):
|
||||
changed = False
|
||||
|
||||
# Because we have already call userExists in main()
|
||||
if self.groupObject is None:
|
||||
parent_id = self.getGroupId(parent)
|
||||
|
||||
group = self.createGroup({
|
||||
'name': name,
|
||||
'path': options['path'],
|
||||
'parent_id': parent_id,
|
||||
'visibility': options['visibility']})
|
||||
changed = True
|
||||
else:
|
||||
changed, group = self.updateGroup(self.groupObject, {
|
||||
'name': name,
|
||||
'description': options['description'],
|
||||
'visibility': options['visibility']})
|
||||
|
||||
self.groupObject = group
|
||||
if changed:
|
||||
if self._module.check_mode:
|
||||
self._module.exit_json(changed=True, msg="Successfully created or updated the group %s" % name)
|
||||
|
||||
try:
|
||||
group.save()
|
||||
except Exception as e:
|
||||
self._module.fail_json(msg="Failed to update group: %s " % e)
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
|
||||
'''
|
||||
@param arguments Attributes of the group
|
||||
'''
|
||||
def createGroup(self, arguments):
|
||||
if self._module.check_mode:
|
||||
return True
|
||||
|
||||
try:
|
||||
group = self._gitlab.groups.create(arguments)
|
||||
except (gitlab.exceptions.GitlabCreateError) as e:
|
||||
self._module.fail_json(msg="Failed to create group: %s " % to_native(e))
|
||||
|
||||
return group
|
||||
|
||||
'''
|
||||
@param group Group Object
|
||||
@param arguments Attributes of the group
|
||||
'''
|
||||
def updateGroup(self, group, arguments):
|
||||
changed = False
|
||||
|
||||
for arg_key, arg_value in arguments.items():
|
||||
if arguments[arg_key] is not None:
|
||||
if getattr(group, arg_key) != arguments[arg_key]:
|
||||
setattr(group, arg_key, arguments[arg_key])
|
||||
changed = True
|
||||
|
||||
return (changed, group)
|
||||
|
||||
def deleteGroup(self):
|
||||
group = self.groupObject
|
||||
|
||||
if len(group.projects.list()) >= 1:
|
||||
self._module.fail_json(
|
||||
msg="There are still projects in this group. These needs to be moved or deleted before this group can be removed.")
|
||||
else:
|
||||
if self._module.check_mode:
|
||||
return True
|
||||
|
||||
try:
|
||||
group.delete()
|
||||
except Exception as e:
|
||||
self._module.fail_json(msg="Failed to delete group: %s " % to_native(e))
|
||||
|
||||
'''
|
||||
@param name Name of the groupe
|
||||
@param full_path Complete path of the Group including parent group path. <parent_path>/<group_path>
|
||||
'''
|
||||
def existsGroup(self, project_identifier):
|
||||
# When group/user exists, object will be stored in self.groupObject.
|
||||
group = findGroup(self._gitlab, project_identifier)
|
||||
if group:
|
||||
self.groupObject = group
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def main():
|
||||
argument_spec = basic_auth_argument_spec()
|
||||
argument_spec.update(dict(
|
||||
api_token=dict(type='str', no_log=True),
|
||||
name=dict(type='str', required=True),
|
||||
path=dict(type='str'),
|
||||
description=dict(type='str'),
|
||||
state=dict(type='str', default="present", choices=["absent", "present"]),
|
||||
parent=dict(type='str'),
|
||||
visibility=dict(type='str', default="private", choices=["internal", "private", "public"]),
|
||||
))
|
||||
|
||||
module = AnsibleModule(
|
||||
argument_spec=argument_spec,
|
||||
mutually_exclusive=[
|
||||
['api_username', 'api_token'],
|
||||
['api_password', 'api_token'],
|
||||
],
|
||||
required_together=[
|
||||
['api_username', 'api_password'],
|
||||
],
|
||||
required_one_of=[
|
||||
['api_username', 'api_token']
|
||||
],
|
||||
supports_check_mode=True,
|
||||
)
|
||||
|
||||
group_name = module.params['name']
|
||||
group_path = module.params['path']
|
||||
description = module.params['description']
|
||||
state = module.params['state']
|
||||
parent_identifier = module.params['parent']
|
||||
group_visibility = module.params['visibility']
|
||||
|
||||
if not HAS_GITLAB_PACKAGE:
|
||||
module.fail_json(msg=missing_required_lib("python-gitlab"), exception=GITLAB_IMP_ERR)
|
||||
|
||||
gitlab_instance = gitlabAuthentication(module)
|
||||
|
||||
# Define default group_path based on group_name
|
||||
if group_path is None:
|
||||
group_path = group_name.replace(" ", "_")
|
||||
|
||||
gitlab_group = GitLabGroup(module, gitlab_instance)
|
||||
|
||||
parent_group = None
|
||||
if parent_identifier:
|
||||
parent_group = findGroup(gitlab_instance, parent_identifier)
|
||||
if not parent_group:
|
||||
module.fail_json(msg="Failed create GitLab group: Parent group doesn't exists")
|
||||
|
||||
group_exists = gitlab_group.existsGroup(parent_group.full_path + '/' + group_path)
|
||||
else:
|
||||
group_exists = gitlab_group.existsGroup(group_path)
|
||||
|
||||
if state == 'absent':
|
||||
if group_exists:
|
||||
gitlab_group.deleteGroup()
|
||||
module.exit_json(changed=True, msg="Successfully deleted group %s" % group_name)
|
||||
else:
|
||||
module.exit_json(changed=False, msg="Group deleted or does not exists")
|
||||
|
||||
if state == 'present':
|
||||
if gitlab_group.createOrUpdateGroup(group_name, parent_group, {
|
||||
"path": group_path,
|
||||
"description": description,
|
||||
"visibility": group_visibility}):
|
||||
module.exit_json(changed=True, msg="Successfully created or updated the group %s" % group_name, group=gitlab_group.groupObject._attrs)
|
||||
else:
|
||||
module.exit_json(changed=False, msg="No need to update the group %s" % group_name, group=gitlab_group.groupObject._attrs)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
391
plugins/modules/source_control/gitlab/gitlab_hook.py
Normal file
391
plugins/modules/source_control/gitlab/gitlab_hook.py
Normal file
|
@ -0,0 +1,391 @@
|
|||
#!/usr/bin/python
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# Copyright: (c) 2019, Guillaume Martinez (lunik@tiwabbit.fr)
|
||||
# Copyright: (c) 2018, Marcus Watkins <marwatk@marcuswatkins.net>
|
||||
# Based on code:
|
||||
# Copyright: (c) 2013, Phillip Gentry <phillip@cx.com>
|
||||
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
|
||||
from __future__ import absolute_import, division, print_function
|
||||
__metaclass__ = type
|
||||
|
||||
ANSIBLE_METADATA = {'metadata_version': '1.1',
|
||||
'status': ['preview'],
|
||||
'supported_by': 'community'}
|
||||
|
||||
DOCUMENTATION = '''
|
||||
---
|
||||
module: gitlab_hook
|
||||
short_description: Manages GitLab project hooks.
|
||||
description:
|
||||
- Adds, updates and removes project hook
|
||||
author:
|
||||
- Marcus Watkins (@marwatk)
|
||||
- Guillaume Martinez (@Lunik)
|
||||
requirements:
|
||||
- python >= 2.7
|
||||
- python-gitlab python module
|
||||
extends_documentation_fragment:
|
||||
- community.general.auth_basic
|
||||
|
||||
options:
|
||||
api_token:
|
||||
description:
|
||||
- GitLab token for logging in.
|
||||
type: str
|
||||
project:
|
||||
description:
|
||||
- Id or Full path of the project in the form of group/name.
|
||||
required: true
|
||||
type: str
|
||||
hook_url:
|
||||
description:
|
||||
- The url that you want GitLab to post to, this is used as the primary key for updates and deletion.
|
||||
required: true
|
||||
type: str
|
||||
state:
|
||||
description:
|
||||
- When C(present) the hook will be updated to match the input or created if it doesn't exist.
|
||||
- When C(absent) hook will be deleted if it exists.
|
||||
required: true
|
||||
default: present
|
||||
type: str
|
||||
choices: [ "present", "absent" ]
|
||||
push_events:
|
||||
description:
|
||||
- Trigger hook on push events.
|
||||
type: bool
|
||||
default: yes
|
||||
push_events_branch_filter:
|
||||
description:
|
||||
- Branch name of wildcard to trigger hook on push events
|
||||
type: str
|
||||
issues_events:
|
||||
description:
|
||||
- Trigger hook on issues events.
|
||||
type: bool
|
||||
default: no
|
||||
merge_requests_events:
|
||||
description:
|
||||
- Trigger hook on merge requests events.
|
||||
type: bool
|
||||
default: no
|
||||
tag_push_events:
|
||||
description:
|
||||
- Trigger hook on tag push events.
|
||||
type: bool
|
||||
default: no
|
||||
note_events:
|
||||
description:
|
||||
- Trigger hook on note events or when someone adds a comment.
|
||||
type: bool
|
||||
default: no
|
||||
job_events:
|
||||
description:
|
||||
- Trigger hook on job events.
|
||||
type: bool
|
||||
default: no
|
||||
pipeline_events:
|
||||
description:
|
||||
- Trigger hook on pipeline events.
|
||||
type: bool
|
||||
default: no
|
||||
wiki_page_events:
|
||||
description:
|
||||
- Trigger hook on wiki events.
|
||||
type: bool
|
||||
default: no
|
||||
hook_validate_certs:
|
||||
description:
|
||||
- Whether GitLab will do SSL verification when triggering the hook.
|
||||
type: bool
|
||||
default: no
|
||||
aliases: [ enable_ssl_verification ]
|
||||
token:
|
||||
description:
|
||||
- Secret token to validate hook messages at the receiver.
|
||||
- If this is present it will always result in a change as it cannot be retrieved from GitLab.
|
||||
- Will show up in the X-GitLab-Token HTTP request header.
|
||||
required: false
|
||||
type: str
|
||||
'''
|
||||
|
||||
EXAMPLES = '''
|
||||
- name: "Adding a project hook"
|
||||
gitlab_hook:
|
||||
api_url: https://gitlab.example.com/
|
||||
api_token: "{{ access_token }}"
|
||||
project: "my_group/my_project"
|
||||
hook_url: "https://my-ci-server.example.com/gitlab-hook"
|
||||
state: present
|
||||
push_events: yes
|
||||
tag_push_events: yes
|
||||
hook_validate_certs: no
|
||||
token: "my-super-secret-token-that-my-ci-server-will-check"
|
||||
|
||||
- name: "Delete the previous hook"
|
||||
gitlab_hook:
|
||||
api_url: https://gitlab.example.com/
|
||||
api_token: "{{ access_token }}"
|
||||
project: "my_group/my_project"
|
||||
hook_url: "https://my-ci-server.example.com/gitlab-hook"
|
||||
state: absent
|
||||
|
||||
- name: "Delete a hook by numeric project id"
|
||||
gitlab_hook:
|
||||
api_url: https://gitlab.example.com/
|
||||
api_token: "{{ access_token }}"
|
||||
project: 10
|
||||
hook_url: "https://my-ci-server.example.com/gitlab-hook"
|
||||
state: absent
|
||||
'''
|
||||
|
||||
RETURN = '''
|
||||
msg:
|
||||
description: Success or failure message
|
||||
returned: always
|
||||
type: str
|
||||
sample: "Success"
|
||||
|
||||
result:
|
||||
description: json parsed response from the server
|
||||
returned: always
|
||||
type: dict
|
||||
|
||||
error:
|
||||
description: the error message returned by the GitLab API
|
||||
returned: failed
|
||||
type: str
|
||||
sample: "400: path is already in use"
|
||||
|
||||
hook:
|
||||
description: API object
|
||||
returned: always
|
||||
type: dict
|
||||
'''
|
||||
|
||||
import re
|
||||
import traceback
|
||||
|
||||
GITLAB_IMP_ERR = None
|
||||
try:
|
||||
import gitlab
|
||||
HAS_GITLAB_PACKAGE = True
|
||||
except Exception:
|
||||
GITLAB_IMP_ERR = traceback.format_exc()
|
||||
HAS_GITLAB_PACKAGE = False
|
||||
|
||||
from ansible.module_utils.api import basic_auth_argument_spec
|
||||
from ansible.module_utils.basic import AnsibleModule, missing_required_lib
|
||||
from ansible.module_utils._text import to_native
|
||||
|
||||
from ansible_collections.community.general.plugins.module_utils.gitlab import findProject, gitlabAuthentication
|
||||
|
||||
|
||||
class GitLabHook(object):
|
||||
def __init__(self, module, gitlab_instance):
|
||||
self._module = module
|
||||
self._gitlab = gitlab_instance
|
||||
self.hookObject = None
|
||||
|
||||
'''
|
||||
@param project Project Object
|
||||
@param hook_url Url to call on event
|
||||
@param description Description of the group
|
||||
@param parent Parent group full path
|
||||
'''
|
||||
def createOrUpdateHook(self, project, hook_url, options):
|
||||
changed = False
|
||||
|
||||
# Because we have already call userExists in main()
|
||||
if self.hookObject is None:
|
||||
hook = self.createHook(project, {
|
||||
'url': hook_url,
|
||||
'push_events': options['push_events'],
|
||||
'push_events_branch_filter': options['push_events_branch_filter'],
|
||||
'issues_events': options['issues_events'],
|
||||
'merge_requests_events': options['merge_requests_events'],
|
||||
'tag_push_events': options['tag_push_events'],
|
||||
'note_events': options['note_events'],
|
||||
'job_events': options['job_events'],
|
||||
'pipeline_events': options['pipeline_events'],
|
||||
'wiki_page_events': options['wiki_page_events'],
|
||||
'enable_ssl_verification': options['enable_ssl_verification'],
|
||||
'token': options['token']})
|
||||
changed = True
|
||||
else:
|
||||
changed, hook = self.updateHook(self.hookObject, {
|
||||
'push_events': options['push_events'],
|
||||
'push_events_branch_filter': options['push_events_branch_filter'],
|
||||
'issues_events': options['issues_events'],
|
||||
'merge_requests_events': options['merge_requests_events'],
|
||||
'tag_push_events': options['tag_push_events'],
|
||||
'note_events': options['note_events'],
|
||||
'job_events': options['job_events'],
|
||||
'pipeline_events': options['pipeline_events'],
|
||||
'wiki_page_events': options['wiki_page_events'],
|
||||
'enable_ssl_verification': options['enable_ssl_verification'],
|
||||
'token': options['token']})
|
||||
|
||||
self.hookObject = hook
|
||||
if changed:
|
||||
if self._module.check_mode:
|
||||
self._module.exit_json(changed=True, msg="Successfully created or updated the hook %s" % hook_url)
|
||||
|
||||
try:
|
||||
hook.save()
|
||||
except Exception as e:
|
||||
self._module.fail_json(msg="Failed to update hook: %s " % e)
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
|
||||
'''
|
||||
@param project Project Object
|
||||
@param arguments Attributes of the hook
|
||||
'''
|
||||
def createHook(self, project, arguments):
|
||||
if self._module.check_mode:
|
||||
return True
|
||||
|
||||
hook = project.hooks.create(arguments)
|
||||
|
||||
return hook
|
||||
|
||||
'''
|
||||
@param hook Hook Object
|
||||
@param arguments Attributes of the hook
|
||||
'''
|
||||
def updateHook(self, hook, arguments):
|
||||
changed = False
|
||||
|
||||
for arg_key, arg_value in arguments.items():
|
||||
if arguments[arg_key] is not None:
|
||||
if getattr(hook, arg_key) != arguments[arg_key]:
|
||||
setattr(hook, arg_key, arguments[arg_key])
|
||||
changed = True
|
||||
|
||||
return (changed, hook)
|
||||
|
||||
'''
|
||||
@param project Project object
|
||||
@param hook_url Url to call on event
|
||||
'''
|
||||
def findHook(self, project, hook_url):
|
||||
hooks = project.hooks.list()
|
||||
for hook in hooks:
|
||||
if (hook.url == hook_url):
|
||||
return hook
|
||||
|
||||
'''
|
||||
@param project Project object
|
||||
@param hook_url Url to call on event
|
||||
'''
|
||||
def existsHook(self, project, hook_url):
|
||||
# When project exists, object will be stored in self.projectObject.
|
||||
hook = self.findHook(project, hook_url)
|
||||
if hook:
|
||||
self.hookObject = hook
|
||||
return True
|
||||
return False
|
||||
|
||||
def deleteHook(self):
|
||||
if self._module.check_mode:
|
||||
return True
|
||||
|
||||
return self.hookObject.delete()
|
||||
|
||||
|
||||
def main():
|
||||
argument_spec = basic_auth_argument_spec()
|
||||
argument_spec.update(dict(
|
||||
api_token=dict(type='str', no_log=True),
|
||||
state=dict(type='str', default="present", choices=["absent", "present"]),
|
||||
project=dict(type='str', required=True),
|
||||
hook_url=dict(type='str', required=True),
|
||||
push_events=dict(type='bool', default=True),
|
||||
push_events_branch_filter=dict(type='str', default=''),
|
||||
issues_events=dict(type='bool', default=False),
|
||||
merge_requests_events=dict(type='bool', default=False),
|
||||
tag_push_events=dict(type='bool', default=False),
|
||||
note_events=dict(type='bool', default=False),
|
||||
job_events=dict(type='bool', default=False),
|
||||
pipeline_events=dict(type='bool', default=False),
|
||||
wiki_page_events=dict(type='bool', default=False),
|
||||
hook_validate_certs=dict(type='bool', default=False, aliases=['enable_ssl_verification']),
|
||||
token=dict(type='str', no_log=True),
|
||||
))
|
||||
|
||||
module = AnsibleModule(
|
||||
argument_spec=argument_spec,
|
||||
mutually_exclusive=[
|
||||
['api_username', 'api_token'],
|
||||
['api_password', 'api_token']
|
||||
],
|
||||
required_together=[
|
||||
['api_username', 'api_password']
|
||||
],
|
||||
required_one_of=[
|
||||
['api_username', 'api_token']
|
||||
],
|
||||
supports_check_mode=True,
|
||||
)
|
||||
|
||||
state = module.params['state']
|
||||
project_identifier = module.params['project']
|
||||
hook_url = module.params['hook_url']
|
||||
push_events = module.params['push_events']
|
||||
push_events_branch_filter = module.params['push_events_branch_filter']
|
||||
issues_events = module.params['issues_events']
|
||||
merge_requests_events = module.params['merge_requests_events']
|
||||
tag_push_events = module.params['tag_push_events']
|
||||
note_events = module.params['note_events']
|
||||
job_events = module.params['job_events']
|
||||
pipeline_events = module.params['pipeline_events']
|
||||
wiki_page_events = module.params['wiki_page_events']
|
||||
enable_ssl_verification = module.params['hook_validate_certs']
|
||||
hook_token = module.params['token']
|
||||
|
||||
if not HAS_GITLAB_PACKAGE:
|
||||
module.fail_json(msg=missing_required_lib("python-gitlab"), exception=GITLAB_IMP_ERR)
|
||||
|
||||
gitlab_instance = gitlabAuthentication(module)
|
||||
|
||||
gitlab_hook = GitLabHook(module, gitlab_instance)
|
||||
|
||||
project = findProject(gitlab_instance, project_identifier)
|
||||
|
||||
if project is None:
|
||||
module.fail_json(msg="Failed to create hook: project %s doesn't exists" % project_identifier)
|
||||
|
||||
hook_exists = gitlab_hook.existsHook(project, hook_url)
|
||||
|
||||
if state == 'absent':
|
||||
if hook_exists:
|
||||
gitlab_hook.deleteHook()
|
||||
module.exit_json(changed=True, msg="Successfully deleted hook %s" % hook_url)
|
||||
else:
|
||||
module.exit_json(changed=False, msg="Hook deleted or does not exists")
|
||||
|
||||
if state == 'present':
|
||||
if gitlab_hook.createOrUpdateHook(project, hook_url, {
|
||||
"push_events": push_events,
|
||||
"push_events_branch_filter": push_events_branch_filter,
|
||||
"issues_events": issues_events,
|
||||
"merge_requests_events": merge_requests_events,
|
||||
"tag_push_events": tag_push_events,
|
||||
"note_events": note_events,
|
||||
"job_events": job_events,
|
||||
"pipeline_events": pipeline_events,
|
||||
"wiki_page_events": wiki_page_events,
|
||||
"enable_ssl_verification": enable_ssl_verification,
|
||||
"token": hook_token}):
|
||||
|
||||
module.exit_json(changed=True, msg="Successfully created or updated the hook %s" % hook_url, hook=gitlab_hook.hookObject._attrs)
|
||||
else:
|
||||
module.exit_json(changed=False, msg="No need to update the hook %s" % hook_url, hook=gitlab_hook.hookObject._attrs)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
1
plugins/modules/source_control/gitlab/gitlab_hooks.py
Symbolic link
1
plugins/modules/source_control/gitlab/gitlab_hooks.py
Symbolic link
|
@ -0,0 +1 @@
|
|||
gitlab_hook.py
|
364
plugins/modules/source_control/gitlab/gitlab_project.py
Normal file
364
plugins/modules/source_control/gitlab/gitlab_project.py
Normal file
|
@ -0,0 +1,364 @@
|
|||
#!/usr/bin/python
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# Copyright: (c) 2019, Guillaume Martinez (lunik@tiwabbit.fr)
|
||||
# Copyright: (c) 2015, Werner Dijkerman (ikben@werner-dijkerman.nl)
|
||||
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
|
||||
from __future__ import absolute_import, division, print_function
|
||||
__metaclass__ = type
|
||||
|
||||
ANSIBLE_METADATA = {'metadata_version': '1.1',
|
||||
'status': ['preview'],
|
||||
'supported_by': 'community'}
|
||||
|
||||
DOCUMENTATION = '''
|
||||
---
|
||||
module: gitlab_project
|
||||
short_description: Creates/updates/deletes GitLab Projects
|
||||
description:
|
||||
- When the project does not exist in GitLab, it will be created.
|
||||
- When the project does exists and state=absent, the project will be deleted.
|
||||
- When changes are made to the project, the project will be updated.
|
||||
author:
|
||||
- Werner Dijkerman (@dj-wasabi)
|
||||
- Guillaume Martinez (@Lunik)
|
||||
requirements:
|
||||
- python >= 2.7
|
||||
- python-gitlab python module
|
||||
extends_documentation_fragment:
|
||||
- community.general.auth_basic
|
||||
|
||||
options:
|
||||
api_token:
|
||||
description:
|
||||
- GitLab token for logging in.
|
||||
type: str
|
||||
group:
|
||||
description:
|
||||
- Id or The full path of the group of which this projects belongs to.
|
||||
type: str
|
||||
name:
|
||||
description:
|
||||
- The name of the project
|
||||
required: true
|
||||
type: str
|
||||
path:
|
||||
description:
|
||||
- The path of the project you want to create, this will be server_url/<group>/path.
|
||||
- If not supplied, name will be used.
|
||||
type: str
|
||||
description:
|
||||
description:
|
||||
- An description for the project.
|
||||
type: str
|
||||
issues_enabled:
|
||||
description:
|
||||
- Whether you want to create issues or not.
|
||||
- Possible values are true and false.
|
||||
type: bool
|
||||
default: yes
|
||||
merge_requests_enabled:
|
||||
description:
|
||||
- If merge requests can be made or not.
|
||||
- Possible values are true and false.
|
||||
type: bool
|
||||
default: yes
|
||||
wiki_enabled:
|
||||
description:
|
||||
- If an wiki for this project should be available or not.
|
||||
- Possible values are true and false.
|
||||
type: bool
|
||||
default: yes
|
||||
snippets_enabled:
|
||||
description:
|
||||
- If creating snippets should be available or not.
|
||||
- Possible values are true and false.
|
||||
type: bool
|
||||
default: yes
|
||||
visibility:
|
||||
description:
|
||||
- Private. Project access must be granted explicitly for each user.
|
||||
- Internal. The project can be cloned by any logged in user.
|
||||
- Public. The project can be cloned without any authentication.
|
||||
default: private
|
||||
type: str
|
||||
choices: ["private", "internal", "public"]
|
||||
aliases:
|
||||
- visibility_level
|
||||
import_url:
|
||||
description:
|
||||
- Git repository which will be imported into gitlab.
|
||||
- GitLab server needs read access to this git repository.
|
||||
required: false
|
||||
type: str
|
||||
state:
|
||||
description:
|
||||
- create or delete project.
|
||||
- Possible values are present and absent.
|
||||
default: present
|
||||
type: str
|
||||
choices: ["present", "absent"]
|
||||
'''
|
||||
|
||||
EXAMPLES = '''
|
||||
- name: Delete GitLab Project
|
||||
gitlab_project:
|
||||
api_url: https://gitlab.example.com/
|
||||
api_token: "{{ access_token }}"
|
||||
validate_certs: False
|
||||
name: my_first_project
|
||||
state: absent
|
||||
delegate_to: localhost
|
||||
|
||||
- name: Create GitLab Project in group Ansible
|
||||
gitlab_project:
|
||||
api_url: https://gitlab.example.com/
|
||||
validate_certs: True
|
||||
api_username: dj-wasabi
|
||||
api_password: "MySecretPassword"
|
||||
name: my_first_project
|
||||
group: ansible
|
||||
issues_enabled: False
|
||||
wiki_enabled: True
|
||||
snippets_enabled: True
|
||||
import_url: http://git.example.com/example/lab.git
|
||||
state: present
|
||||
delegate_to: localhost
|
||||
'''
|
||||
|
||||
RETURN = '''
|
||||
msg:
|
||||
description: Success or failure message
|
||||
returned: always
|
||||
type: str
|
||||
sample: "Success"
|
||||
|
||||
result:
|
||||
description: json parsed response from the server
|
||||
returned: always
|
||||
type: dict
|
||||
|
||||
error:
|
||||
description: the error message returned by the GitLab API
|
||||
returned: failed
|
||||
type: str
|
||||
sample: "400: path is already in use"
|
||||
|
||||
project:
|
||||
description: API object
|
||||
returned: always
|
||||
type: dict
|
||||
'''
|
||||
|
||||
import traceback
|
||||
|
||||
GITLAB_IMP_ERR = None
|
||||
try:
|
||||
import gitlab
|
||||
HAS_GITLAB_PACKAGE = True
|
||||
except Exception:
|
||||
GITLAB_IMP_ERR = traceback.format_exc()
|
||||
HAS_GITLAB_PACKAGE = False
|
||||
|
||||
from ansible.module_utils.api import basic_auth_argument_spec
|
||||
from ansible.module_utils.basic import AnsibleModule, missing_required_lib
|
||||
from ansible.module_utils._text import to_native
|
||||
|
||||
from ansible_collections.community.general.plugins.module_utils.gitlab import findGroup, findProject, gitlabAuthentication
|
||||
|
||||
|
||||
class GitLabProject(object):
|
||||
def __init__(self, module, gitlab_instance):
|
||||
self._module = module
|
||||
self._gitlab = gitlab_instance
|
||||
self.projectObject = None
|
||||
|
||||
'''
|
||||
@param project_name Name of the project
|
||||
@param namespace Namespace Object (User or Group)
|
||||
@param options Options of the project
|
||||
'''
|
||||
def createOrUpdateProject(self, project_name, namespace, options):
|
||||
changed = False
|
||||
|
||||
# Because we have already call userExists in main()
|
||||
if self.projectObject is None:
|
||||
project = self.createProject(namespace, {
|
||||
'name': project_name,
|
||||
'path': options['path'],
|
||||
'description': options['description'],
|
||||
'issues_enabled': options['issues_enabled'],
|
||||
'merge_requests_enabled': options['merge_requests_enabled'],
|
||||
'wiki_enabled': options['wiki_enabled'],
|
||||
'snippets_enabled': options['snippets_enabled'],
|
||||
'visibility': options['visibility'],
|
||||
'import_url': options['import_url']})
|
||||
changed = True
|
||||
else:
|
||||
changed, project = self.updateProject(self.projectObject, {
|
||||
'name': project_name,
|
||||
'description': options['description'],
|
||||
'issues_enabled': options['issues_enabled'],
|
||||
'merge_requests_enabled': options['merge_requests_enabled'],
|
||||
'wiki_enabled': options['wiki_enabled'],
|
||||
'snippets_enabled': options['snippets_enabled'],
|
||||
'visibility': options['visibility']})
|
||||
|
||||
self.projectObject = project
|
||||
if changed:
|
||||
if self._module.check_mode:
|
||||
self._module.exit_json(changed=True, msg="Successfully created or updated the project %s" % project_name)
|
||||
|
||||
try:
|
||||
project.save()
|
||||
except Exception as e:
|
||||
self._module.fail_json(msg="Failed update project: %s " % e)
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
|
||||
'''
|
||||
@param namespace Namespace Object (User or Group)
|
||||
@param arguments Attributes of the project
|
||||
'''
|
||||
def createProject(self, namespace, arguments):
|
||||
if self._module.check_mode:
|
||||
return True
|
||||
|
||||
arguments['namespace_id'] = namespace.id
|
||||
try:
|
||||
project = self._gitlab.projects.create(arguments)
|
||||
except (gitlab.exceptions.GitlabCreateError) as e:
|
||||
self._module.fail_json(msg="Failed to create project: %s " % to_native(e))
|
||||
|
||||
return project
|
||||
|
||||
'''
|
||||
@param project Project Object
|
||||
@param arguments Attributes of the project
|
||||
'''
|
||||
def updateProject(self, project, arguments):
|
||||
changed = False
|
||||
|
||||
for arg_key, arg_value in arguments.items():
|
||||
if arguments[arg_key] is not None:
|
||||
if getattr(project, arg_key) != arguments[arg_key]:
|
||||
setattr(project, arg_key, arguments[arg_key])
|
||||
changed = True
|
||||
|
||||
return (changed, project)
|
||||
|
||||
def deleteProject(self):
|
||||
if self._module.check_mode:
|
||||
return True
|
||||
|
||||
project = self.projectObject
|
||||
|
||||
return project.delete()
|
||||
|
||||
'''
|
||||
@param namespace User/Group object
|
||||
@param name Name of the project
|
||||
'''
|
||||
def existsProject(self, namespace, path):
|
||||
# When project exists, object will be stored in self.projectObject.
|
||||
project = findProject(self._gitlab, namespace.full_path + '/' + path)
|
||||
if project:
|
||||
self.projectObject = project
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def main():
|
||||
argument_spec = basic_auth_argument_spec()
|
||||
argument_spec.update(dict(
|
||||
api_token=dict(type='str', no_log=True),
|
||||
group=dict(type='str'),
|
||||
name=dict(type='str', required=True),
|
||||
path=dict(type='str'),
|
||||
description=dict(type='str'),
|
||||
issues_enabled=dict(type='bool', default=True),
|
||||
merge_requests_enabled=dict(type='bool', default=True),
|
||||
wiki_enabled=dict(type='bool', default=True),
|
||||
snippets_enabled=dict(default=True, type='bool'),
|
||||
visibility=dict(type='str', default="private", choices=["internal", "private", "public"], aliases=["visibility_level"]),
|
||||
import_url=dict(type='str'),
|
||||
state=dict(type='str', default="present", choices=["absent", "present"]),
|
||||
))
|
||||
|
||||
module = AnsibleModule(
|
||||
argument_spec=argument_spec,
|
||||
mutually_exclusive=[
|
||||
['api_username', 'api_token'],
|
||||
['api_password', 'api_token'],
|
||||
],
|
||||
required_together=[
|
||||
['api_username', 'api_password'],
|
||||
],
|
||||
required_one_of=[
|
||||
['api_username', 'api_token']
|
||||
],
|
||||
supports_check_mode=True,
|
||||
)
|
||||
|
||||
group_identifier = module.params['group']
|
||||
project_name = module.params['name']
|
||||
project_path = module.params['path']
|
||||
project_description = module.params['description']
|
||||
issues_enabled = module.params['issues_enabled']
|
||||
merge_requests_enabled = module.params['merge_requests_enabled']
|
||||
wiki_enabled = module.params['wiki_enabled']
|
||||
snippets_enabled = module.params['snippets_enabled']
|
||||
visibility = module.params['visibility']
|
||||
import_url = module.params['import_url']
|
||||
state = module.params['state']
|
||||
|
||||
if not HAS_GITLAB_PACKAGE:
|
||||
module.fail_json(msg=missing_required_lib("python-gitlab"), exception=GITLAB_IMP_ERR)
|
||||
|
||||
gitlab_instance = gitlabAuthentication(module)
|
||||
|
||||
# Set project_path to project_name if it is empty.
|
||||
if project_path is None:
|
||||
project_path = project_name.replace(" ", "_")
|
||||
|
||||
gitlab_project = GitLabProject(module, gitlab_instance)
|
||||
|
||||
if group_identifier:
|
||||
group = findGroup(gitlab_instance, group_identifier)
|
||||
if group is None:
|
||||
module.fail_json(msg="Failed to create project: group %s doesn't exists" % group_identifier)
|
||||
|
||||
namespace = gitlab_instance.namespaces.get(group.id)
|
||||
project_exists = gitlab_project.existsProject(namespace, project_path)
|
||||
else:
|
||||
user = gitlab_instance.users.list(username=gitlab_instance.user.username)[0]
|
||||
namespace = gitlab_instance.namespaces.get(user.id)
|
||||
project_exists = gitlab_project.existsProject(namespace, project_path)
|
||||
|
||||
if state == 'absent':
|
||||
if project_exists:
|
||||
gitlab_project.deleteProject()
|
||||
module.exit_json(changed=True, msg="Successfully deleted project %s" % project_name)
|
||||
else:
|
||||
module.exit_json(changed=False, msg="Project deleted or does not exists")
|
||||
|
||||
if state == 'present':
|
||||
if gitlab_project.createOrUpdateProject(project_name, namespace, {
|
||||
"path": project_path,
|
||||
"description": project_description,
|
||||
"issues_enabled": issues_enabled,
|
||||
"merge_requests_enabled": merge_requests_enabled,
|
||||
"wiki_enabled": wiki_enabled,
|
||||
"snippets_enabled": snippets_enabled,
|
||||
"visibility": visibility,
|
||||
"import_url": import_url}):
|
||||
|
||||
module.exit_json(changed=True, msg="Successfully created or updated the project %s" % project_name, project=gitlab_project.projectObject._attrs)
|
||||
else:
|
||||
module.exit_json(changed=False, msg="No need to update the project %s" % project_name, project=gitlab_project.projectObject._attrs)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
291
plugins/modules/source_control/gitlab/gitlab_project_variable.py
Normal file
291
plugins/modules/source_control/gitlab/gitlab_project_variable.py
Normal file
|
@ -0,0 +1,291 @@
|
|||
#!/usr/bin/python
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# Copyright: (c) 2019, Markus Bergholz (markuman@gmail.com)
|
||||
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
from __future__ import absolute_import, division, print_function
|
||||
__metaclass__ = type
|
||||
|
||||
ANSIBLE_METADATA = {'metadata_version': '1.1',
|
||||
'status': ['preview'],
|
||||
'supported_by': 'community'}
|
||||
|
||||
|
||||
DOCUMENTATION = '''
|
||||
module: gitlab_project_variable
|
||||
short_description: Creates/updates/deletes GitLab Projects Variables
|
||||
description:
|
||||
- When a project variable does not exist, it will be created.
|
||||
- When a project variable does exist, its value will be updated when the values are different.
|
||||
- Variables which are untouched in the playbook, but are not untouched in the GitLab project,
|
||||
they stay untouched (I(purge) is C(false)) or will be deleted (I(purge) is C(true)).
|
||||
author:
|
||||
- "Markus Bergholz (@markuman)"
|
||||
requirements:
|
||||
- python >= 2.7
|
||||
- python-gitlab python module
|
||||
extends_documentation_fragment:
|
||||
- community.general.auth_basic
|
||||
|
||||
options:
|
||||
state:
|
||||
description:
|
||||
- Create or delete project variable.
|
||||
- Possible values are present and absent.
|
||||
default: present
|
||||
type: str
|
||||
choices: ["present", "absent"]
|
||||
api_token:
|
||||
description:
|
||||
- GitLab access token with API permissions.
|
||||
required: true
|
||||
type: str
|
||||
project:
|
||||
description:
|
||||
- The path and name of the project.
|
||||
required: true
|
||||
type: str
|
||||
purge:
|
||||
description:
|
||||
- When set to true, all variables which are not untouched in the task will be deleted.
|
||||
default: false
|
||||
type: bool
|
||||
vars:
|
||||
description:
|
||||
- When the list element is a simple key-value pair, masked and protected will be set to false.
|
||||
- When the list element is a dict with the keys I(value), I(masked) and I(protected), the user can
|
||||
have full control about whether a value should be masked, protected or both.
|
||||
- Support for protected values requires GitLab >= 9.3.
|
||||
- Support for masked values requires GitLab >= 11.10.
|
||||
- A I(value) must be a string or a number.
|
||||
- When a value is masked, it must be in Base64 and have a length of at least 8 characters.
|
||||
See GitLab documentation on acceptable values for a masked variable (https://docs.gitlab.com/ce/ci/variables/#masked-variables).
|
||||
default: {}
|
||||
type: dict
|
||||
'''
|
||||
|
||||
|
||||
EXAMPLES = '''
|
||||
- name: Set or update some CI/CD variables
|
||||
gitlab_project_variable:
|
||||
api_url: https://gitlab.com
|
||||
api_token: secret_access_token
|
||||
project: markuman/dotfiles
|
||||
purge: false
|
||||
vars:
|
||||
ACCESS_KEY_ID: abc123
|
||||
SECRET_ACCESS_KEY: 321cba
|
||||
|
||||
- name: Set or update some CI/CD variables
|
||||
gitlab_project_variable:
|
||||
api_url: https://gitlab.com
|
||||
api_token: secret_access_token
|
||||
project: markuman/dotfiles
|
||||
purge: false
|
||||
vars:
|
||||
ACCESS_KEY_ID: abc123
|
||||
SECRET_ACCESS_KEY:
|
||||
value: 3214cbad
|
||||
masked: true
|
||||
protected: true
|
||||
|
||||
- name: Delete one variable
|
||||
gitlab_project_variable:
|
||||
api_url: https://gitlab.com
|
||||
api_token: secret_access_token
|
||||
project: markuman/dotfiles
|
||||
state: absent
|
||||
vars:
|
||||
ACCESS_KEY_ID: abc123
|
||||
'''
|
||||
|
||||
RETURN = '''
|
||||
project_variable:
|
||||
description: Four lists of the variablenames which were added, updated, removed or exist.
|
||||
returned: always
|
||||
type: dict
|
||||
contains:
|
||||
added:
|
||||
description: A list of variables which were created.
|
||||
returned: always
|
||||
type: list
|
||||
sample: "['ACCESS_KEY_ID', 'SECRET_ACCESS_KEY']"
|
||||
untouched:
|
||||
description: A list of variables which exist.
|
||||
returned: always
|
||||
type: list
|
||||
sample: "['ACCESS_KEY_ID', 'SECRET_ACCESS_KEY']"
|
||||
removed:
|
||||
description: A list of variables which were deleted.
|
||||
returned: always
|
||||
type: list
|
||||
sample: "['ACCESS_KEY_ID', 'SECRET_ACCESS_KEY']"
|
||||
updated:
|
||||
description: A list of variables whose values were changed.
|
||||
returned: always
|
||||
type: list
|
||||
sample: "['ACCESS_KEY_ID', 'SECRET_ACCESS_KEY']"
|
||||
'''
|
||||
|
||||
import traceback
|
||||
|
||||
from ansible.module_utils.basic import AnsibleModule, missing_required_lib
|
||||
from ansible.module_utils._text import to_native
|
||||
from ansible.module_utils.api import basic_auth_argument_spec
|
||||
from ansible.module_utils.six import string_types
|
||||
from ansible.module_utils.six import integer_types
|
||||
|
||||
|
||||
GITLAB_IMP_ERR = None
|
||||
try:
|
||||
import gitlab
|
||||
HAS_GITLAB_PACKAGE = True
|
||||
except Exception:
|
||||
GITLAB_IMP_ERR = traceback.format_exc()
|
||||
HAS_GITLAB_PACKAGE = False
|
||||
|
||||
from ansible_collections.community.general.plugins.module_utils.gitlab import gitlabAuthentication
|
||||
|
||||
|
||||
class GitlabProjectVariables(object):
|
||||
|
||||
def __init__(self, module, gitlab_instance):
|
||||
self.repo = gitlab_instance
|
||||
self.project = self.get_project(module.params['project'])
|
||||
self._module = module
|
||||
|
||||
def get_project(self, project_name):
|
||||
return self.repo.projects.get(project_name)
|
||||
|
||||
def list_all_project_variables(self):
|
||||
return self.project.variables.list()
|
||||
|
||||
def create_variable(self, key, value, masked, protected):
|
||||
if self._module.check_mode:
|
||||
return
|
||||
return self.project.variables.create({"key": key, "value": value,
|
||||
"masked": masked, "protected": protected})
|
||||
|
||||
def update_variable(self, key, var, value, masked, protected):
|
||||
if var.value == value and var.protected == protected and var.masked == masked:
|
||||
return False
|
||||
|
||||
if self._module.check_mode:
|
||||
return True
|
||||
|
||||
if var.protected == protected and var.masked == masked:
|
||||
var.value = value
|
||||
var.save()
|
||||
return True
|
||||
|
||||
self.delete_variable(key)
|
||||
self.create_variable(key, value, masked, protected)
|
||||
return True
|
||||
|
||||
def delete_variable(self, key):
|
||||
if self._module.check_mode:
|
||||
return
|
||||
return self.project.variables.delete(key)
|
||||
|
||||
|
||||
def native_python_main(this_gitlab, purge, var_list, state, module):
|
||||
|
||||
change = False
|
||||
return_value = dict(added=list(), updated=list(), removed=list(), untouched=list())
|
||||
|
||||
gitlab_keys = this_gitlab.list_all_project_variables()
|
||||
existing_variables = [x.get_id() for x in gitlab_keys]
|
||||
|
||||
for key in var_list:
|
||||
|
||||
if isinstance(var_list[key], string_types) or isinstance(var_list[key], (integer_types, float)):
|
||||
value = var_list[key]
|
||||
masked = False
|
||||
protected = False
|
||||
elif isinstance(var_list[key], dict):
|
||||
value = var_list[key].get('value')
|
||||
masked = var_list[key].get('masked', False)
|
||||
protected = var_list[key].get('protected', False)
|
||||
else:
|
||||
module.fail_json(msg="value must be of type string, integer or dict")
|
||||
|
||||
if key in existing_variables:
|
||||
index = existing_variables.index(key)
|
||||
existing_variables[index] = None
|
||||
|
||||
if state == 'present':
|
||||
single_change = this_gitlab.update_variable(key,
|
||||
gitlab_keys[index],
|
||||
value, masked,
|
||||
protected)
|
||||
change = single_change or change
|
||||
if single_change:
|
||||
return_value['updated'].append(key)
|
||||
else:
|
||||
return_value['untouched'].append(key)
|
||||
|
||||
elif state == 'absent':
|
||||
this_gitlab.delete_variable(key)
|
||||
change = True
|
||||
return_value['removed'].append(key)
|
||||
|
||||
elif key not in existing_variables and state == 'present':
|
||||
this_gitlab.create_variable(key, value, masked, protected)
|
||||
change = True
|
||||
return_value['added'].append(key)
|
||||
|
||||
existing_variables = list(filter(None, existing_variables))
|
||||
if purge:
|
||||
for item in existing_variables:
|
||||
this_gitlab.delete_variable(item)
|
||||
change = True
|
||||
return_value['removed'].append(item)
|
||||
else:
|
||||
return_value['untouched'].extend(existing_variables)
|
||||
|
||||
return change, return_value
|
||||
|
||||
|
||||
def main():
|
||||
argument_spec = basic_auth_argument_spec()
|
||||
argument_spec.update(
|
||||
api_token=dict(type='str', required=True, no_log=True),
|
||||
project=dict(type='str', required=True),
|
||||
purge=dict(type='bool', required=False, default=False),
|
||||
vars=dict(type='dict', required=False, default=dict(), no_log=True),
|
||||
state=dict(type='str', default="present", choices=["absent", "present"])
|
||||
)
|
||||
|
||||
module = AnsibleModule(
|
||||
argument_spec=argument_spec,
|
||||
mutually_exclusive=[
|
||||
['api_username', 'api_token'],
|
||||
['api_password', 'api_token'],
|
||||
],
|
||||
required_together=[
|
||||
['api_username', 'api_password'],
|
||||
],
|
||||
required_one_of=[
|
||||
['api_username', 'api_token']
|
||||
],
|
||||
supports_check_mode=True
|
||||
)
|
||||
|
||||
purge = module.params['purge']
|
||||
var_list = module.params['vars']
|
||||
state = module.params['state']
|
||||
|
||||
if not HAS_GITLAB_PACKAGE:
|
||||
module.fail_json(msg=missing_required_lib("python-gitlab"), exception=GITLAB_IMP_ERR)
|
||||
|
||||
gitlab_instance = gitlabAuthentication(module)
|
||||
|
||||
this_gitlab = GitlabProjectVariables(module=module, gitlab_instance=gitlab_instance)
|
||||
|
||||
change, return_value = native_python_main(this_gitlab, purge, var_list, state, module)
|
||||
|
||||
module.exit_json(changed=change, project_variable=return_value)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
353
plugins/modules/source_control/gitlab/gitlab_runner.py
Normal file
353
plugins/modules/source_control/gitlab/gitlab_runner.py
Normal file
|
@ -0,0 +1,353 @@
|
|||
#!/usr/bin/python
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# Copyright: (c) 2019, Guillaume Martinez (lunik@tiwabbit.fr)
|
||||
# Copyright: (c) 2018, Samy Coenen <samy.coenen@nubera.be>
|
||||
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
|
||||
from __future__ import absolute_import, division, print_function
|
||||
__metaclass__ = type
|
||||
|
||||
ANSIBLE_METADATA = {'metadata_version': '1.1',
|
||||
'status': ['preview'],
|
||||
'supported_by': 'community'}
|
||||
|
||||
DOCUMENTATION = '''
|
||||
---
|
||||
module: gitlab_runner
|
||||
short_description: Create, modify and delete GitLab Runners.
|
||||
description:
|
||||
- Register, update and delete runners with the GitLab API.
|
||||
- All operations are performed using the GitLab API v4.
|
||||
- For details, consult the full API documentation at U(https://docs.gitlab.com/ee/api/runners.html).
|
||||
- A valid private API token is required for all operations. You can create as many tokens as you like using the GitLab web interface at
|
||||
U(https://$GITLAB_URL/profile/personal_access_tokens).
|
||||
- A valid registration token is required for registering a new runner.
|
||||
To create shared runners, you need to ask your administrator to give you this token.
|
||||
It can be found at U(https://$GITLAB_URL/admin/runners/).
|
||||
notes:
|
||||
- To create a new runner at least the C(api_token), C(description) and C(api_url) options are required.
|
||||
- Runners need to have unique descriptions.
|
||||
author:
|
||||
- Samy Coenen (@SamyCoenen)
|
||||
- Guillaume Martinez (@Lunik)
|
||||
requirements:
|
||||
- python >= 2.7
|
||||
- python-gitlab >= 1.5.0
|
||||
extends_documentation_fragment:
|
||||
- community.general.auth_basic
|
||||
|
||||
options:
|
||||
api_token:
|
||||
description:
|
||||
- Your private token to interact with the GitLab API.
|
||||
required: True
|
||||
type: str
|
||||
description:
|
||||
description:
|
||||
- The unique name of the runner.
|
||||
required: True
|
||||
type: str
|
||||
aliases:
|
||||
- name
|
||||
state:
|
||||
description:
|
||||
- Make sure that the runner with the same name exists with the same configuration or delete the runner with the same name.
|
||||
required: False
|
||||
default: present
|
||||
choices: ["present", "absent"]
|
||||
type: str
|
||||
registration_token:
|
||||
description:
|
||||
- The registration token is used to register new runners.
|
||||
required: True
|
||||
type: str
|
||||
active:
|
||||
description:
|
||||
- Define if the runners is immediately active after creation.
|
||||
required: False
|
||||
default: yes
|
||||
type: bool
|
||||
locked:
|
||||
description:
|
||||
- Determines if the runner is locked or not.
|
||||
required: False
|
||||
default: False
|
||||
type: bool
|
||||
access_level:
|
||||
description:
|
||||
- Determines if a runner can pick up jobs from protected branches.
|
||||
required: False
|
||||
default: ref_protected
|
||||
choices: ["ref_protected", "not_protected"]
|
||||
type: str
|
||||
maximum_timeout:
|
||||
description:
|
||||
- The maximum timeout that a runner has to pick up a specific job.
|
||||
required: False
|
||||
default: 3600
|
||||
type: int
|
||||
run_untagged:
|
||||
description:
|
||||
- Run untagged jobs or not.
|
||||
required: False
|
||||
default: yes
|
||||
type: bool
|
||||
tag_list:
|
||||
description: The tags that apply to the runner.
|
||||
required: False
|
||||
default: []
|
||||
type: list
|
||||
'''
|
||||
|
||||
EXAMPLES = '''
|
||||
- name: "Register runner"
|
||||
gitlab_runner:
|
||||
api_url: https://gitlab.example.com/
|
||||
api_token: "{{ access_token }}"
|
||||
registration_token: 4gfdsg345
|
||||
description: Docker Machine t1
|
||||
state: present
|
||||
active: True
|
||||
tag_list: ['docker']
|
||||
run_untagged: False
|
||||
locked: False
|
||||
|
||||
- name: "Delete runner"
|
||||
gitlab_runner:
|
||||
api_url: https://gitlab.example.com/
|
||||
api_token: "{{ access_token }}"
|
||||
description: Docker Machine t1
|
||||
state: absent
|
||||
'''
|
||||
|
||||
RETURN = '''
|
||||
msg:
|
||||
description: Success or failure message
|
||||
returned: always
|
||||
type: str
|
||||
sample: "Success"
|
||||
|
||||
result:
|
||||
description: json parsed response from the server
|
||||
returned: always
|
||||
type: dict
|
||||
|
||||
error:
|
||||
description: the error message returned by the GitLab API
|
||||
returned: failed
|
||||
type: str
|
||||
sample: "400: path is already in use"
|
||||
|
||||
runner:
|
||||
description: API object
|
||||
returned: always
|
||||
type: dict
|
||||
'''
|
||||
|
||||
import traceback
|
||||
|
||||
GITLAB_IMP_ERR = None
|
||||
try:
|
||||
import gitlab
|
||||
HAS_GITLAB_PACKAGE = True
|
||||
except Exception:
|
||||
GITLAB_IMP_ERR = traceback.format_exc()
|
||||
HAS_GITLAB_PACKAGE = False
|
||||
|
||||
from ansible.module_utils.api import basic_auth_argument_spec
|
||||
from ansible.module_utils.basic import AnsibleModule, missing_required_lib
|
||||
from ansible.module_utils._text import to_native
|
||||
|
||||
from ansible_collections.community.general.plugins.module_utils.gitlab import gitlabAuthentication
|
||||
|
||||
try:
|
||||
cmp
|
||||
except NameError:
|
||||
def cmp(a, b):
|
||||
return (a > b) - (a < b)
|
||||
|
||||
|
||||
class GitLabRunner(object):
|
||||
def __init__(self, module, gitlab_instance):
|
||||
self._module = module
|
||||
self._gitlab = gitlab_instance
|
||||
self.runnerObject = None
|
||||
|
||||
def createOrUpdateRunner(self, description, options):
|
||||
changed = False
|
||||
|
||||
# Because we have already call userExists in main()
|
||||
if self.runnerObject is None:
|
||||
runner = self.createRunner({
|
||||
'description': description,
|
||||
'active': options['active'],
|
||||
'token': options['registration_token'],
|
||||
'locked': options['locked'],
|
||||
'run_untagged': options['run_untagged'],
|
||||
'maximum_timeout': options['maximum_timeout'],
|
||||
'tag_list': options['tag_list']})
|
||||
changed = True
|
||||
else:
|
||||
changed, runner = self.updateRunner(self.runnerObject, {
|
||||
'active': options['active'],
|
||||
'locked': options['locked'],
|
||||
'run_untagged': options['run_untagged'],
|
||||
'maximum_timeout': options['maximum_timeout'],
|
||||
'access_level': options['access_level'],
|
||||
'tag_list': options['tag_list']})
|
||||
|
||||
self.runnerObject = runner
|
||||
if changed:
|
||||
if self._module.check_mode:
|
||||
self._module.exit_json(changed=True, msg="Successfully created or updated the runner %s" % description)
|
||||
|
||||
try:
|
||||
runner.save()
|
||||
except Exception as e:
|
||||
self._module.fail_json(msg="Failed to update runner: %s " % to_native(e))
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
|
||||
'''
|
||||
@param arguments Attributes of the runner
|
||||
'''
|
||||
def createRunner(self, arguments):
|
||||
if self._module.check_mode:
|
||||
return True
|
||||
|
||||
try:
|
||||
runner = self._gitlab.runners.create(arguments)
|
||||
except (gitlab.exceptions.GitlabCreateError) as e:
|
||||
self._module.fail_json(msg="Failed to create runner: %s " % to_native(e))
|
||||
|
||||
return runner
|
||||
|
||||
'''
|
||||
@param runner Runner object
|
||||
@param arguments Attributes of the runner
|
||||
'''
|
||||
def updateRunner(self, runner, arguments):
|
||||
changed = False
|
||||
|
||||
for arg_key, arg_value in arguments.items():
|
||||
if arguments[arg_key] is not None:
|
||||
if isinstance(arguments[arg_key], list):
|
||||
list1 = getattr(runner, arg_key)
|
||||
list1.sort()
|
||||
list2 = arguments[arg_key]
|
||||
list2.sort()
|
||||
if cmp(list1, list2):
|
||||
setattr(runner, arg_key, arguments[arg_key])
|
||||
changed = True
|
||||
else:
|
||||
if getattr(runner, arg_key) != arguments[arg_key]:
|
||||
setattr(runner, arg_key, arguments[arg_key])
|
||||
changed = True
|
||||
|
||||
return (changed, runner)
|
||||
|
||||
'''
|
||||
@param description Description of the runner
|
||||
'''
|
||||
def findRunner(self, description):
|
||||
runners = self._gitlab.runners.all(as_list=False)
|
||||
for runner in runners:
|
||||
if (runner['description'] == description):
|
||||
return self._gitlab.runners.get(runner['id'])
|
||||
|
||||
'''
|
||||
@param description Description of the runner
|
||||
'''
|
||||
def existsRunner(self, description):
|
||||
# When runner exists, object will be stored in self.runnerObject.
|
||||
runner = self.findRunner(description)
|
||||
|
||||
if runner:
|
||||
self.runnerObject = runner
|
||||
return True
|
||||
return False
|
||||
|
||||
def deleteRunner(self):
|
||||
if self._module.check_mode:
|
||||
return True
|
||||
|
||||
runner = self.runnerObject
|
||||
|
||||
return runner.delete()
|
||||
|
||||
|
||||
def main():
|
||||
argument_spec = basic_auth_argument_spec()
|
||||
argument_spec.update(dict(
|
||||
api_token=dict(type='str', no_log=True),
|
||||
description=dict(type='str', required=True, aliases=["name"]),
|
||||
active=dict(type='bool', default=True),
|
||||
tag_list=dict(type='list', default=[]),
|
||||
run_untagged=dict(type='bool', default=True),
|
||||
locked=dict(type='bool', default=False),
|
||||
access_level=dict(type='str', default='ref_protected', choices=["not_protected", "ref_protected"]),
|
||||
maximum_timeout=dict(type='int', default=3600),
|
||||
registration_token=dict(type='str', required=True),
|
||||
state=dict(type='str', default="present", choices=["absent", "present"]),
|
||||
))
|
||||
|
||||
module = AnsibleModule(
|
||||
argument_spec=argument_spec,
|
||||
mutually_exclusive=[
|
||||
['api_username', 'api_token'],
|
||||
['api_password', 'api_token'],
|
||||
],
|
||||
required_together=[
|
||||
['api_username', 'api_password'],
|
||||
],
|
||||
required_one_of=[
|
||||
['api_username', 'api_token'],
|
||||
],
|
||||
supports_check_mode=True,
|
||||
)
|
||||
|
||||
state = module.params['state']
|
||||
runner_description = module.params['description']
|
||||
runner_active = module.params['active']
|
||||
tag_list = module.params['tag_list']
|
||||
run_untagged = module.params['run_untagged']
|
||||
runner_locked = module.params['locked']
|
||||
access_level = module.params['access_level']
|
||||
maximum_timeout = module.params['maximum_timeout']
|
||||
registration_token = module.params['registration_token']
|
||||
|
||||
if not HAS_GITLAB_PACKAGE:
|
||||
module.fail_json(msg=missing_required_lib("python-gitlab"), exception=GITLAB_IMP_ERR)
|
||||
|
||||
gitlab_instance = gitlabAuthentication(module)
|
||||
|
||||
gitlab_runner = GitLabRunner(module, gitlab_instance)
|
||||
runner_exists = gitlab_runner.existsRunner(runner_description)
|
||||
|
||||
if state == 'absent':
|
||||
if runner_exists:
|
||||
gitlab_runner.deleteRunner()
|
||||
module.exit_json(changed=True, msg="Successfully deleted runner %s" % runner_description)
|
||||
else:
|
||||
module.exit_json(changed=False, msg="Runner deleted or does not exists")
|
||||
|
||||
if state == 'present':
|
||||
if gitlab_runner.createOrUpdateRunner(runner_description, {
|
||||
"active": runner_active,
|
||||
"tag_list": tag_list,
|
||||
"run_untagged": run_untagged,
|
||||
"locked": runner_locked,
|
||||
"access_level": access_level,
|
||||
"maximum_timeout": maximum_timeout,
|
||||
"registration_token": registration_token}):
|
||||
module.exit_json(changed=True, runner=gitlab_runner.runnerObject._attrs,
|
||||
msg="Successfully created or updated the runner %s" % runner_description)
|
||||
else:
|
||||
module.exit_json(changed=False, runner=gitlab_runner.runnerObject._attrs,
|
||||
msg="No need to update the runner %s" % runner_description)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
477
plugins/modules/source_control/gitlab/gitlab_user.py
Normal file
477
plugins/modules/source_control/gitlab/gitlab_user.py
Normal file
|
@ -0,0 +1,477 @@
|
|||
#!/usr/bin/python
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# Copyright: (c) 2019, Guillaume Martinez (lunik@tiwabbit.fr)
|
||||
# Copyright: (c) 2015, Werner Dijkerman (ikben@werner-dijkerman.nl)
|
||||
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
|
||||
from __future__ import absolute_import, division, print_function
|
||||
__metaclass__ = type
|
||||
|
||||
ANSIBLE_METADATA = {'metadata_version': '1.1',
|
||||
'status': ['preview'],
|
||||
'supported_by': 'community'}
|
||||
|
||||
DOCUMENTATION = '''
|
||||
---
|
||||
module: gitlab_user
|
||||
short_description: Creates/updates/deletes GitLab Users
|
||||
description:
|
||||
- When the user does not exist in GitLab, it will be created.
|
||||
- When the user does exists and state=absent, the user will be deleted.
|
||||
- When changes are made to user, the user will be updated.
|
||||
notes:
|
||||
- From Ansible 2.10 and onwards, name, email and password are optional while deleting the user.
|
||||
author:
|
||||
- Werner Dijkerman (@dj-wasabi)
|
||||
- Guillaume Martinez (@Lunik)
|
||||
requirements:
|
||||
- python >= 2.7
|
||||
- python-gitlab python module
|
||||
- administrator rights on the GitLab server
|
||||
extends_documentation_fragment:
|
||||
- community.general.auth_basic
|
||||
|
||||
options:
|
||||
api_token:
|
||||
description:
|
||||
- GitLab token for logging in.
|
||||
type: str
|
||||
name:
|
||||
description:
|
||||
- Name of the user you want to create.
|
||||
- Required only if C(state) is set to C(present).
|
||||
type: str
|
||||
username:
|
||||
description:
|
||||
- The username of the user.
|
||||
required: true
|
||||
type: str
|
||||
password:
|
||||
description:
|
||||
- The password of the user.
|
||||
- GitLab server enforces minimum password length to 8, set this value with 8 or more characters.
|
||||
- Required only if C(state) is set to C(present).
|
||||
type: str
|
||||
email:
|
||||
description:
|
||||
- The email that belongs to the user.
|
||||
- Required only if C(state) is set to C(present).
|
||||
type: str
|
||||
sshkey_name:
|
||||
description:
|
||||
- The name of the sshkey
|
||||
type: str
|
||||
sshkey_file:
|
||||
description:
|
||||
- The ssh key itself.
|
||||
type: str
|
||||
group:
|
||||
description:
|
||||
- Id or Full path of parent group in the form of group/name.
|
||||
- Add user as an member to this group.
|
||||
type: str
|
||||
access_level:
|
||||
description:
|
||||
- The access level to the group. One of the following can be used.
|
||||
- guest
|
||||
- reporter
|
||||
- developer
|
||||
- master (alias for maintainer)
|
||||
- maintainer
|
||||
- owner
|
||||
default: guest
|
||||
type: str
|
||||
choices: ["guest", "reporter", "developer", "master", "maintainer", "owner"]
|
||||
state:
|
||||
description:
|
||||
- create or delete group.
|
||||
- Possible values are present and absent.
|
||||
default: present
|
||||
type: str
|
||||
choices: ["present", "absent"]
|
||||
confirm:
|
||||
description:
|
||||
- Require confirmation.
|
||||
type: bool
|
||||
default: yes
|
||||
isadmin:
|
||||
description:
|
||||
- Grant admin privileges to the user.
|
||||
type: bool
|
||||
default: no
|
||||
external:
|
||||
description:
|
||||
- Define external parameter for this user.
|
||||
type: bool
|
||||
default: no
|
||||
'''
|
||||
|
||||
EXAMPLES = '''
|
||||
- name: "Delete GitLab User"
|
||||
gitlab_user:
|
||||
api_url: https://gitlab.example.com/
|
||||
api_token: "{{ access_token }}"
|
||||
validate_certs: False
|
||||
username: myusername
|
||||
state: absent
|
||||
delegate_to: localhost
|
||||
|
||||
- name: "Create GitLab User"
|
||||
gitlab_user:
|
||||
api_url: https://gitlab.example.com/
|
||||
validate_certs: True
|
||||
api_username: dj-wasabi
|
||||
api_password: "MySecretPassword"
|
||||
name: My Name
|
||||
username: myusername
|
||||
password: mysecretpassword
|
||||
email: me@example.com
|
||||
sshkey_name: MySSH
|
||||
sshkey_file: ssh-rsa AAAAB3NzaC1yc...
|
||||
state: present
|
||||
group: super_group/mon_group
|
||||
access_level: owner
|
||||
delegate_to: localhost
|
||||
'''
|
||||
|
||||
RETURN = '''
|
||||
msg:
|
||||
description: Success or failure message
|
||||
returned: always
|
||||
type: str
|
||||
sample: "Success"
|
||||
|
||||
result:
|
||||
description: json parsed response from the server
|
||||
returned: always
|
||||
type: dict
|
||||
|
||||
error:
|
||||
description: the error message returned by the GitLab API
|
||||
returned: failed
|
||||
type: str
|
||||
sample: "400: path is already in use"
|
||||
|
||||
user:
|
||||
description: API object
|
||||
returned: always
|
||||
type: dict
|
||||
'''
|
||||
|
||||
import traceback
|
||||
|
||||
GITLAB_IMP_ERR = None
|
||||
try:
|
||||
import gitlab
|
||||
HAS_GITLAB_PACKAGE = True
|
||||
except Exception:
|
||||
GITLAB_IMP_ERR = traceback.format_exc()
|
||||
HAS_GITLAB_PACKAGE = False
|
||||
|
||||
from ansible.module_utils.api import basic_auth_argument_spec
|
||||
from ansible.module_utils.basic import AnsibleModule, missing_required_lib
|
||||
from ansible.module_utils._text import to_native
|
||||
|
||||
from ansible_collections.community.general.plugins.module_utils.gitlab import findGroup, gitlabAuthentication
|
||||
|
||||
|
||||
class GitLabUser(object):
|
||||
def __init__(self, module, gitlab_instance):
|
||||
self._module = module
|
||||
self._gitlab = gitlab_instance
|
||||
self.userObject = None
|
||||
self.ACCESS_LEVEL = {
|
||||
'guest': gitlab.GUEST_ACCESS,
|
||||
'reporter': gitlab.REPORTER_ACCESS,
|
||||
'developer': gitlab.DEVELOPER_ACCESS,
|
||||
'master': gitlab.MAINTAINER_ACCESS,
|
||||
'maintainer': gitlab.MAINTAINER_ACCESS,
|
||||
'owner': gitlab.OWNER_ACCESS}
|
||||
|
||||
'''
|
||||
@param username Username of the user
|
||||
@param options User options
|
||||
'''
|
||||
def createOrUpdateUser(self, username, options):
|
||||
changed = False
|
||||
|
||||
# Because we have already call userExists in main()
|
||||
if self.userObject is None:
|
||||
user = self.createUser({
|
||||
'name': options['name'],
|
||||
'username': username,
|
||||
'password': options['password'],
|
||||
'email': options['email'],
|
||||
'skip_confirmation': not options['confirm'],
|
||||
'admin': options['isadmin'],
|
||||
'external': options['external']})
|
||||
changed = True
|
||||
else:
|
||||
changed, user = self.updateUser(self.userObject, {
|
||||
'name': options['name'],
|
||||
'email': options['email'],
|
||||
'is_admin': options['isadmin'],
|
||||
'external': options['external']})
|
||||
|
||||
# Assign ssh keys
|
||||
if options['sshkey_name'] and options['sshkey_file']:
|
||||
key_changed = self.addSshKeyToUser(user, {
|
||||
'name': options['sshkey_name'],
|
||||
'file': options['sshkey_file']})
|
||||
changed = changed or key_changed
|
||||
|
||||
# Assign group
|
||||
if options['group_path']:
|
||||
group_changed = self.assignUserToGroup(user, options['group_path'], options['access_level'])
|
||||
changed = changed or group_changed
|
||||
|
||||
self.userObject = user
|
||||
if changed:
|
||||
if self._module.check_mode:
|
||||
self._module.exit_json(changed=True, msg="Successfully created or updated the user %s" % username)
|
||||
|
||||
try:
|
||||
user.save()
|
||||
except Exception as e:
|
||||
self._module.fail_json(msg="Failed to update user: %s " % to_native(e))
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
|
||||
'''
|
||||
@param group User object
|
||||
'''
|
||||
def getUserId(self, user):
|
||||
if user is not None:
|
||||
return user.id
|
||||
return None
|
||||
|
||||
'''
|
||||
@param user User object
|
||||
@param sshkey_name Name of the ssh key
|
||||
'''
|
||||
def sshKeyExists(self, user, sshkey_name):
|
||||
keyList = map(lambda k: k.title, user.keys.list())
|
||||
|
||||
return sshkey_name in keyList
|
||||
|
||||
'''
|
||||
@param user User object
|
||||
@param sshkey Dict containing sshkey infos {"name": "", "file": ""}
|
||||
'''
|
||||
def addSshKeyToUser(self, user, sshkey):
|
||||
if not self.sshKeyExists(user, sshkey['name']):
|
||||
if self._module.check_mode:
|
||||
return True
|
||||
|
||||
try:
|
||||
user.keys.create({
|
||||
'title': sshkey['name'],
|
||||
'key': sshkey['file']})
|
||||
except gitlab.exceptions.GitlabCreateError as e:
|
||||
self._module.fail_json(msg="Failed to assign sshkey to user: %s" % to_native(e))
|
||||
return True
|
||||
return False
|
||||
|
||||
'''
|
||||
@param group Group object
|
||||
@param user_id Id of the user to find
|
||||
'''
|
||||
def findMember(self, group, user_id):
|
||||
try:
|
||||
member = group.members.get(user_id)
|
||||
except gitlab.exceptions.GitlabGetError:
|
||||
return None
|
||||
return member
|
||||
|
||||
'''
|
||||
@param group Group object
|
||||
@param user_id Id of the user to check
|
||||
'''
|
||||
def memberExists(self, group, user_id):
|
||||
member = self.findMember(group, user_id)
|
||||
|
||||
return member is not None
|
||||
|
||||
'''
|
||||
@param group Group object
|
||||
@param user_id Id of the user to check
|
||||
@param access_level GitLab access_level to check
|
||||
'''
|
||||
def memberAsGoodAccessLevel(self, group, user_id, access_level):
|
||||
member = self.findMember(group, user_id)
|
||||
|
||||
return member.access_level == access_level
|
||||
|
||||
'''
|
||||
@param user User object
|
||||
@param group_path Complete path of the Group including parent group path. <parent_path>/<group_path>
|
||||
@param access_level GitLab access_level to assign
|
||||
'''
|
||||
def assignUserToGroup(self, user, group_identifier, access_level):
|
||||
group = findGroup(self._gitlab, group_identifier)
|
||||
|
||||
if self._module.check_mode:
|
||||
return True
|
||||
|
||||
if group is None:
|
||||
return False
|
||||
|
||||
if self.memberExists(group, self.getUserId(user)):
|
||||
member = self.findMember(group, self.getUserId(user))
|
||||
if not self.memberAsGoodAccessLevel(group, member.id, self.ACCESS_LEVEL[access_level]):
|
||||
member.access_level = self.ACCESS_LEVEL[access_level]
|
||||
member.save()
|
||||
return True
|
||||
else:
|
||||
try:
|
||||
group.members.create({
|
||||
'user_id': self.getUserId(user),
|
||||
'access_level': self.ACCESS_LEVEL[access_level]})
|
||||
except gitlab.exceptions.GitlabCreateError as e:
|
||||
self._module.fail_json(msg="Failed to assign user to group: %s" % to_native(e))
|
||||
return True
|
||||
return False
|
||||
|
||||
'''
|
||||
@param user User object
|
||||
@param arguments User attributes
|
||||
'''
|
||||
def updateUser(self, user, arguments):
|
||||
changed = False
|
||||
|
||||
for arg_key, arg_value in arguments.items():
|
||||
if arguments[arg_key] is not None:
|
||||
if getattr(user, arg_key) != arguments[arg_key]:
|
||||
setattr(user, arg_key, arguments[arg_key])
|
||||
changed = True
|
||||
|
||||
return (changed, user)
|
||||
|
||||
'''
|
||||
@param arguments User attributes
|
||||
'''
|
||||
def createUser(self, arguments):
|
||||
if self._module.check_mode:
|
||||
return True
|
||||
|
||||
try:
|
||||
user = self._gitlab.users.create(arguments)
|
||||
except (gitlab.exceptions.GitlabCreateError) as e:
|
||||
self._module.fail_json(msg="Failed to create user: %s " % to_native(e))
|
||||
|
||||
return user
|
||||
|
||||
'''
|
||||
@param username Username of the user
|
||||
'''
|
||||
def findUser(self, username):
|
||||
users = self._gitlab.users.list(search=username)
|
||||
for user in users:
|
||||
if (user.username == username):
|
||||
return user
|
||||
|
||||
'''
|
||||
@param username Username of the user
|
||||
'''
|
||||
def existsUser(self, username):
|
||||
# When user exists, object will be stored in self.userObject.
|
||||
user = self.findUser(username)
|
||||
if user:
|
||||
self.userObject = user
|
||||
return True
|
||||
return False
|
||||
|
||||
def deleteUser(self):
|
||||
if self._module.check_mode:
|
||||
return True
|
||||
|
||||
user = self.userObject
|
||||
|
||||
return user.delete()
|
||||
|
||||
|
||||
def main():
|
||||
argument_spec = basic_auth_argument_spec()
|
||||
argument_spec.update(dict(
|
||||
api_token=dict(type='str', no_log=True),
|
||||
name=dict(type='str'),
|
||||
state=dict(type='str', default="present", choices=["absent", "present"]),
|
||||
username=dict(type='str', required=True),
|
||||
password=dict(type='str', no_log=True),
|
||||
email=dict(type='str'),
|
||||
sshkey_name=dict(type='str'),
|
||||
sshkey_file=dict(type='str'),
|
||||
group=dict(type='str'),
|
||||
access_level=dict(type='str', default="guest", choices=["developer", "guest", "maintainer", "master", "owner", "reporter"]),
|
||||
confirm=dict(type='bool', default=True),
|
||||
isadmin=dict(type='bool', default=False),
|
||||
external=dict(type='bool', default=False),
|
||||
))
|
||||
|
||||
module = AnsibleModule(
|
||||
argument_spec=argument_spec,
|
||||
mutually_exclusive=[
|
||||
['api_username', 'api_token'],
|
||||
['api_password', 'api_token'],
|
||||
],
|
||||
required_together=[
|
||||
['api_username', 'api_password'],
|
||||
],
|
||||
required_one_of=[
|
||||
['api_username', 'api_token']
|
||||
],
|
||||
supports_check_mode=True,
|
||||
required_if=(
|
||||
('state', 'present', ['name', 'email', 'password']),
|
||||
)
|
||||
)
|
||||
|
||||
user_name = module.params['name']
|
||||
state = module.params['state']
|
||||
user_username = module.params['username'].lower()
|
||||
user_password = module.params['password']
|
||||
user_email = module.params['email']
|
||||
user_sshkey_name = module.params['sshkey_name']
|
||||
user_sshkey_file = module.params['sshkey_file']
|
||||
group_path = module.params['group']
|
||||
access_level = module.params['access_level']
|
||||
confirm = module.params['confirm']
|
||||
user_isadmin = module.params['isadmin']
|
||||
user_external = module.params['external']
|
||||
|
||||
if not HAS_GITLAB_PACKAGE:
|
||||
module.fail_json(msg=missing_required_lib("python-gitlab"), exception=GITLAB_IMP_ERR)
|
||||
|
||||
gitlab_instance = gitlabAuthentication(module)
|
||||
|
||||
gitlab_user = GitLabUser(module, gitlab_instance)
|
||||
user_exists = gitlab_user.existsUser(user_username)
|
||||
|
||||
if state == 'absent':
|
||||
if user_exists:
|
||||
gitlab_user.deleteUser()
|
||||
module.exit_json(changed=True, msg="Successfully deleted user %s" % user_username)
|
||||
else:
|
||||
module.exit_json(changed=False, msg="User deleted or does not exists")
|
||||
|
||||
if state == 'present':
|
||||
if gitlab_user.createOrUpdateUser(user_username, {
|
||||
"name": user_name,
|
||||
"password": user_password,
|
||||
"email": user_email,
|
||||
"sshkey_name": user_sshkey_name,
|
||||
"sshkey_file": user_sshkey_file,
|
||||
"group_path": group_path,
|
||||
"access_level": access_level,
|
||||
"confirm": confirm,
|
||||
"isadmin": user_isadmin,
|
||||
"external": user_external}):
|
||||
module.exit_json(changed=True, msg="Successfully created or updated the user %s" % user_username, user=gitlab_user.userObject._attrs)
|
||||
else:
|
||||
module.exit_json(changed=False, msg="No need to update the user %s" % user_username, user=gitlab_user.userObject._attrs)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
Loading…
Add table
Add a link
Reference in a new issue