Beispiel #1
0
def main():
    argument_spec = basic_auth_argument_spec()
    argument_spec.update(auth_argument_spec())
    argument_spec.update(dict(
        description=dict(type='str', required=True, aliases=["name"]),
        active=dict(type='bool', default=True),
        owned=dict(type='bool', default=False),
        tag_list=dict(type='list', elements='str', 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', no_log=True),
        project=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_username', 'api_oauth_token'],
            ['api_username', 'api_job_token'],
            ['api_token', 'api_oauth_token'],
            ['api_token', 'api_job_token'],
            ['project', 'owned'],
        ],
        required_together=[
            ['api_username', 'api_password'],
        ],
        required_one_of=[
            ['api_username', 'api_token', 'api_oauth_token', 'api_job_token'],
        ],
        required_if=[
            ('state', 'present', ['registration_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']
    project = module.params['project']

    if not HAS_GITLAB_PACKAGE:
        module.fail_json(msg=missing_required_lib("python-gitlab"), exception=GITLAB_IMP_ERR)

    gitlab_instance = gitlab_authentication(module)
    gitlab_project = None
    if project:
        try:
            gitlab_project = gitlab_instance.projects.get(project)
        except gitlab.exceptions.GitlabGetError as e:
            module.fail_json(msg='No such a project %s' % project, exception=to_native(e))

    gitlab_runner = GitLabRunner(module, gitlab_instance, gitlab_project)
    runner_exists = gitlab_runner.exists_runner(runner_description)

    if state == 'absent':
        if runner_exists:
            gitlab_runner.delete_runner()
            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.create_or_update_runner(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.runner_object._attrs,
                             msg="Successfully created or updated the runner %s" % runner_description)
        else:
            module.exit_json(changed=False, runner=gitlab_runner.runner_object._attrs,
                             msg="No need to update the runner %s" % runner_description)
Beispiel #2
0
def main():

    module = AnsibleModule(
        argument_spec=dict(
            host=dict(type='str', required=True),
            login=dict(type='str', default='Administrator'),
            password=dict(type='str', default='admin', no_log=True),
            ssl_version=dict(type='str', default='TLSv1', choices=['SSLv3', 'SSLv23', 'TLSv1', 'TLSv1_1', 'TLSv1_2']),
        ),
        supports_check_mode=True,
    )

    if not HAS_HPILO:
        module.fail_json(msg=missing_required_lib('python-hpilo'), exception=HPILO_IMP_ERR)

    host = module.params['host']
    login = module.params['login']
    password = module.params['password']
    ssl_version = getattr(hpilo.ssl, 'PROTOCOL_' + module.params.get('ssl_version').upper().replace('V', 'v'))

    ilo = hpilo.Ilo(host, login=login, password=password, ssl_version=ssl_version)

    info = {
        'module_hw': True,
    }

    # TODO: Count number of CPUs, DIMMs and total memory
    try:
        data = ilo.get_host_data()
        power_state = ilo.get_host_power_status()
    except hpilo.IloCommunicationError as e:
        module.fail_json(msg=to_native(e))

    for entry in data:
        if 'type' not in entry:
            continue
        elif entry['type'] == 0:  # BIOS Information
            info['hw_bios_version'] = entry['Family']
            info['hw_bios_date'] = entry['Date']
        elif entry['type'] == 1:  # System Information
            info['hw_uuid'] = entry['UUID']
            info['hw_system_serial'] = entry['Serial Number'].rstrip()
            info['hw_product_name'] = entry['Product Name']
            info['hw_product_uuid'] = entry['cUUID']
        elif entry['type'] == 209:  # Embedded NIC MAC Assignment
            if 'fields' in entry:
                for (name, value) in [(e['name'], e['value']) for e in entry['fields']]:
                    if name.startswith('Port'):
                        try:
                            infoname = 'hw_eth' + str(int(value) - 1)
                        except Exception:
                            infoname = 'hw_eth_ilo'
                    elif name.startswith('MAC'):
                        info[infoname] = {
                            'macaddress': value.replace('-', ':'),
                            'macaddress_dash': value
                        }
            else:
                (infoname, entry_info) = parse_flat_interface(entry, 'hw_eth_ilo')
                info[infoname] = entry_info
        elif entry['type'] == 209:  # HPQ NIC iSCSI MAC Info
            for (name, value) in [(e['name'], e['value']) for e in entry['fields']]:
                if name.startswith('Port'):
                    try:
                        infoname = 'hw_iscsi' + str(int(value) - 1)
                    except Exception:
                        infoname = 'hw_iscsi_ilo'
                elif name.startswith('MAC'):
                    info[infoname] = {
                        'macaddress': value.replace('-', ':'),
                        'macaddress_dash': value
                    }
        elif entry['type'] == 233:  # Embedded NIC MAC Assignment (Alternate data format)
            (infoname, entry_info) = parse_flat_interface(entry, 'hw_eth_ilo')
            info[infoname] = entry_info

    # Collect health (RAM/CPU data)
    health = ilo.get_embedded_health()
    info['hw_health'] = health

    memory_details_summary = health.get('memory', {}).get('memory_details_summary')
    # RAM as reported by iLO 2.10 on ProLiant BL460c Gen8
    if memory_details_summary:
        info['hw_memory_details_summary'] = memory_details_summary
        info['hw_memory_total'] = 0
        for cpu, details in memory_details_summary.items():
            cpu_total_memory_size = details.get('total_memory_size')
            if cpu_total_memory_size:
                ram = re.search(r'(\d+)\s+(\w+)', cpu_total_memory_size)
                if ram:
                    if ram.group(2) == 'GB':
                        info['hw_memory_total'] = info['hw_memory_total'] + int(ram.group(1))

        # reformat into a text friendly format
        info['hw_memory_total'] = "{0} GB".format(info['hw_memory_total'])

    # Report host state
    info['host_power_status'] = power_state or 'UNKNOWN'

    module.exit_json(**info)
def main():
    module = AnsibleModule(
        argument_spec=dict(repository=dict(type='str',
                                           required=True,
                                           aliases=['repo']),
                           url=dict(type='str', required=True),
                           content_type=dict(type='str',
                                             choices=('json', 'form'),
                                             required=False,
                                             default='form'),
                           secret=dict(type='str', required=False,
                                       no_log=True),
                           insecure_ssl=dict(type='bool',
                                             required=False,
                                             default=False),
                           events=dict(type='list',
                                       elements='str',
                                       required=False),
                           active=dict(type='bool',
                                       required=False,
                                       default=True),
                           state=dict(type='str',
                                      required=False,
                                      choices=('absent', 'present'),
                                      default='present'),
                           user=dict(type='str', required=True),
                           password=dict(type='str',
                                         required=False,
                                         no_log=True),
                           token=dict(type='str', required=False, no_log=True),
                           github_url=dict(type='str',
                                           required=False,
                                           default="https://api.github.com")),
        mutually_exclusive=(('password', 'token'), ),
        required_one_of=(("password", "token"), ),
        required_if=(("state", "present", ("events", )), ),
    )

    if not HAS_GITHUB:
        module.fail_json(msg=missing_required_lib('PyGithub'),
                         exception=GITHUB_IMP_ERR)

    try:
        github_conn = github.Github(module.params["user"],
                                    module.params.get("password")
                                    or module.params.get("token"),
                                    base_url=module.params["github_url"])
    except github.GithubException as err:
        module.fail_json(msg="Could not connect to GitHub at %s: %s" %
                         (module.params["github_url"], to_native(err)))

    try:
        repo = github_conn.get_repo(module.params["repository"])
    except github.BadCredentialsException as err:
        module.fail_json(msg="Could not authenticate to GitHub at %s: %s" %
                         (module.params["github_url"], to_native(err)))
    except github.UnknownObjectException as err:
        module.fail_json(
            msg="Could not find repository %s in GitHub at %s: %s" %
            (module.params["repository"], module.params["github_url"],
             to_native(err)))
    except Exception as err:
        module.fail_json(
            msg="Could not fetch repository %s from GitHub at %s: %s" %
            (module.params["repository"], module.params["github_url"],
             to_native(err)),
            exception=traceback.format_exc())

    hook = None
    try:
        for hook in repo.get_hooks():
            if hook.config.get("url") == module.params["url"]:
                break
        else:
            hook = None
    except github.GithubException as err:
        module.fail_json(msg="Unable to get hooks from repository %s: %s" %
                         (module.params["repository"], to_native(err)))

    changed = False
    data = {}
    if hook is None and module.params["state"] == "present":
        changed, data = create_hook(repo, module)
    elif hook is not None and module.params["state"] == "absent":
        try:
            hook.delete()
        except github.GithubException as err:
            module.fail_json(
                msg="Unable to delete hook from repository %s: %s" %
                (repo.full_name, to_native(err)))
        else:
            changed = True
    elif hook is not None and module.params["state"] == "present":
        changed, data = update_hook(repo, hook, module)
    # else, there is no hook and we want there to be no hook

    module.exit_json(changed=changed, **data)
    def legacy_plugin_dir_to_plugin_type(legacy_plugin_dir_name):
        """
        Utility method to convert from a PluginLoader dir name to a plugin ref_type
        :param legacy_plugin_dir_name: PluginLoader dir name (eg, 'action_plugins', 'library')
        :return: the corresponding plugin ref_type (eg, 'action', 'role')
        """
        legacy_plugin_dir_name = to_text(legacy_plugin_dir_name)

        plugin_type = legacy_plugin_dir_name.removesuffix(u'_plugins')

        if plugin_type == u'library':
            plugin_type = u'modules'

        if plugin_type not in AnsibleCollectionRef.VALID_REF_TYPES:
            raise ValueError('{0} cannot be mapped to a valid collection ref type'.format(to_native(legacy_plugin_dir_name)))

        return plugin_type
Beispiel #5
0
    def run(self, terms, variables=None, **kwargs):
        if len(terms) != 3:
            raise AnsibleError("dig_srv: three arguments expected")

        myres = dns.resolver.Resolver(configure=True)
        edns_size = 4096
        myres.use_edns(0, ednsflags=dns.flags.DO, payload=edns_size)

        domain = terms[0]
        default_domain = terms[1]
        default_port = terms[2]
        qtype = 'SRV'
        rdclass = dns.rdataclass.from_text('IN')

        ret = []

        try:
            answers = myres.query(domain, qtype, rdclass=rdclass)
            for rdata in answers:
                try:
                    rd = make_rdata_dict(rdata)
                    rd['owner'] = answers.canonical_name.to_text().rstrip('.')
                    rd['type'] = dns.rdatatype.to_text(rdata.rdtype)
                    rd['ttl'] = answers.rrset.ttl
                    rd['class'] = dns.rdataclass.to_text(rdata.rdclass)
                    rd['dig_srv_src'] = 'dns'
                    ret.append(rd)

                except Exception as e:
                    raise AnsibleError("dig_srv: can't parse response %s" %
                                       to_native(e))

        except (dns.resolver.NXDOMAIN, dns.resolver.NoAnswer):
            ret.append({
                "class": "IN",
                "owner": domain.rstrip('.'),
                "port": default_port,
                "priority": 0,
                "target": default_domain,
                "ttl": 0,
                "type": "SRV",
                "weight": 0,
                "dig_srv_src": "fallback"
            })
        except dns.resolver.Timeout:
            raise AnsibleError("dig_srv: timeout")
        except dns.exception.DNSException as e:
            raise AnsibleError("dig_srv: unhandled exception %s" %
                               to_native(e))

        for r in ret:
            r.update({"target_port": r["target"] + ":" + str(r["port"])})

        # This is in reverse order of importance, i.e. least important first.
        # Note that the TTL field shows the remaining TTL when a RR is cached,
        # so sorting on that field is not a good idea.
        ret.sort(key=itemgetter("port"))
        ret.sort(key=itemgetter("target"))
        ret.sort(key=itemgetter("weight"), reverse=True)
        ret.sort(key=itemgetter("priority"))

        return ret
Beispiel #6
0
def run_module():
    # define the available arguments/parameters that a user can pass to
    # the module
    module_args = dict(
        key=dict(type='str', required=True, no_log=False),
        value=dict(type='str', required=True),
        host=dict(type='str', default='localhost'),
        port=dict(type='int', default=2379),
        state=dict(type='str', required=True, choices=['present', 'absent']),
        user=dict(type='str'),
        password=dict(type='str', no_log=True),
        ca_cert=dict(type='path'),
        client_cert=dict(type='path'),
        client_key=dict(type='path'),
        timeout=dict(type='int'),
    )

    # seed the result dict in the object
    # we primarily care about changed and state
    # change is if this module effectively modified the target
    # state will include any data that you want your module to pass back
    # for consumption, for example, in a subsequent task
    result = dict(
        changed=False,
    )

    # the AnsibleModule object will be our abstraction working with Ansible
    # this includes instantiation, a couple of common attr would be the
    # args/params passed to the execution, as well as if the module
    # supports check mode
    module = AnsibleModule(
        argument_spec=module_args,
        supports_check_mode=True,
        required_together=[['client_cert', 'client_key'], ['user', 'password']],
    )

    # It is possible to set `ca_cert` to verify the server identity without
    # setting `client_cert` or `client_key` to authenticate the client
    # so required_together is enough
    # Due to `required_together=[['client_cert', 'client_key']]`, checking the presence
    # of either `client_cert` or `client_key` is enough
    if module.params['ca_cert'] is None and module.params['client_cert'] is not None:
        module.fail_json(msg="The 'ca_cert' parameter must be defined when 'client_cert' and 'client_key' are present.")

    result['key'] = module.params.get('key')
    module.params['cert_cert'] = module.params.pop('client_cert')
    module.params['cert_key'] = module.params.pop('client_key')

    if not HAS_ETCD:
        module.fail_json(msg=missing_required_lib('etcd3'), exception=ETCD_IMP_ERR)

    allowed_keys = ['host', 'port', 'ca_cert', 'cert_cert', 'cert_key',
                    'timeout', 'user', 'password']
    # TODO(evrardjp): Move this back to a dict comprehension when python 2.7 is
    # the minimum supported version
    # client_params = {key: value for key, value in module.params.items() if key in allowed_keys}
    client_params = dict()
    for key, value in module.params.items():
        if key in allowed_keys:
            client_params[key] = value
    try:
        etcd = etcd3.client(**client_params)
    except Exception as exp:
        module.fail_json(msg='Cannot connect to etcd cluster: %s' % (to_native(exp)),
                         exception=traceback.format_exc())
    try:
        cluster_value = etcd.get(module.params['key'])
    except Exception as exp:
        module.fail_json(msg='Cannot reach data: %s' % (to_native(exp)),
                         exception=traceback.format_exc())

    # Make the cluster_value[0] a string for string comparisons
    result['old_value'] = to_native(cluster_value[0])

    if module.params['state'] == 'absent':
        if cluster_value[0] is not None:
            if module.check_mode:
                result['changed'] = True
            else:
                try:
                    etcd.delete(module.params['key'])
                except Exception as exp:
                    module.fail_json(msg='Cannot delete %s: %s' % (module.params['key'], to_native(exp)),
                                     exception=traceback.format_exc())
                else:
                    result['changed'] = True
    elif module.params['state'] == 'present':
        if result['old_value'] != module.params['value']:
            if module.check_mode:
                result['changed'] = True
            else:
                try:
                    etcd.put(module.params['key'], module.params['value'])
                except Exception as exp:
                    module.fail_json(msg='Cannot add or edit key %s: %s' % (module.params['key'], to_native(exp)),
                                     exception=traceback.format_exc())
                else:
                    result['changed'] = True
    else:
        module.fail_json(msg="State not recognized")

    # manipulate or modify the state as needed (this is going to be the
    # part where your module will do what it needs to do)

    # during the execution of the module, if there is an exception or a
    # conditional state that effectively causes a failure, run
    # AnsibleModule.fail_json() to pass in the message and the result

    # in the event of a successful module execution, you will want to
    # simple AnsibleModule.exit_json(), passing the key/value results
    module.exit_json(**result)
Beispiel #7
0
 def __init__(self, error):
     self.status = to_native(error.get("status", None))
     self.errors = [
         to_native(err.get("message")) for err in error.get("errors", {})
     ]
     self.message = to_native(" ".join(self.errors))
Beispiel #8
0
    def _set_config(self, name, **kwargs):
        headers = {
            "Content-Type": "application/json",
            "Connection": "keep-alive",
        }
        self.request = Request(headers=headers, timeout=60)

        configurators = [self._read_config_vars]
        for configurator in configurators:
            self._config = configurator(name, **kwargs)
            if self._config:
                break
        if self._config is None:
            raise SessionConfigurationException(
                to_native("No Configuration Found."))

        # set up auth if passed
        entrust_api_user = self.get_config("entrust_api_user")
        entrust_api_key = self.get_config("entrust_api_key")
        if entrust_api_user and entrust_api_key:
            self.request.url_username = entrust_api_user
            self.request.url_password = entrust_api_key
        else:
            raise SessionConfigurationException(
                to_native("User and key must be provided."))

        # set up client certificate if passed (support all-in one or cert + key)
        entrust_api_cert = self.get_config("entrust_api_cert")
        entrust_api_cert_key = self.get_config("entrust_api_cert_key")
        if entrust_api_cert:
            self.request.client_cert = entrust_api_cert
            if entrust_api_cert_key:
                self.request.client_key = entrust_api_cert_key
        else:
            raise SessionConfigurationException(
                to_native(
                    "Client certificate for authentication to the API must be provided."
                ))

        # set up the spec
        entrust_api_specification_path = self.get_config(
            "entrust_api_specification_path")

        if not entrust_api_specification_path.startswith(
                "http") and not os.path.isfile(entrust_api_specification_path):
            raise SessionConfigurationException(
                to_native(
                    "OpenAPI specification was not found at location {0}.".
                    format(entrust_api_specification_path)))
        if not valid_file_format.match(entrust_api_specification_path):
            raise SessionConfigurationException(
                to_native(
                    "OpenAPI specification filename must end in .json, .yml or .yaml"
                ))

        self.verify = True

        if entrust_api_specification_path.startswith("http"):
            try:
                http_response = Request().open(
                    method="GET", url=entrust_api_specification_path)
                http_response_contents = http_response.read()
                if entrust_api_specification_path.endswith(".json"):
                    self._spec = json.load(http_response_contents)
                elif entrust_api_specification_path.endswith(
                        ".yml") or entrust_api_specification_path.endswith(
                            ".yaml"):
                    self._spec = yaml.safe_load(http_response_contents)
            except HTTPError as e:
                raise SessionConfigurationException(
                    to_native(
                        "Error downloading specification from address '{0}', received error code '{1}'"
                        .format(entrust_api_specification_path, e.getcode())))
        else:
            with open(entrust_api_specification_path) as f:
                if ".json" in entrust_api_specification_path:
                    self._spec = json.load(f)
                elif ".yml" in entrust_api_specification_path or ".yaml" in entrust_api_specification_path:
                    self._spec = yaml.safe_load(f)
Beispiel #9
0
def main():
    argument_spec = basic_auth_argument_spec()
    argument_spec.update(auth_argument_spec())
    argument_spec.update(
        dict(
            group=dict(type='str'),
            name=dict(type='str', required=True),
            path=dict(type='str'),
            description=dict(type='str'),
            initialize_with_readme=dict(type='bool', default=False),
            default_branch=dict(type='str'),
            issues_enabled=dict(type='bool', default=True),
            merge_requests_enabled=dict(type='bool', default=True),
            merge_method=dict(type='str',
                              default='merge',
                              choices=["merge", "rebase_merge", "ff"]),
            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"]),
            lfs_enabled=dict(default=False, type='bool'),
            username=dict(type='str'),
            allow_merge_on_skipped_pipeline=dict(type='bool'),
            only_allow_merge_if_all_discussions_are_resolved=dict(type='bool'),
            only_allow_merge_if_pipeline_succeeds=dict(type='bool'),
            packages_enabled=dict(type='bool'),
            remove_source_branch_after_merge=dict(type='bool'),
            squash_option=dict(
                type='str',
                choices=['never', 'always', 'default_off', 'default_on']),
            ci_config_path=dict(type='str'),
            shared_runners_enabled=dict(type='bool'),
            avatar_path=dict(type='path'),
        ))

    module = AnsibleModule(
        argument_spec=argument_spec,
        mutually_exclusive=[
            ['api_username', 'api_token'],
            ['api_username', 'api_oauth_token'],
            ['api_username', 'api_job_token'],
            ['api_token', 'api_oauth_token'],
            ['api_token', 'api_job_token'],
            ['group', 'username'],
        ],
        required_together=[
            ['api_username', 'api_password'],
        ],
        required_one_of=[[
            'api_username', 'api_token', 'api_oauth_token', 'api_job_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']
    initialize_with_readme = module.params['initialize_with_readme']
    issues_enabled = module.params['issues_enabled']
    merge_requests_enabled = module.params['merge_requests_enabled']
    merge_method = module.params['merge_method']
    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']
    lfs_enabled = module.params['lfs_enabled']
    username = module.params['username']
    allow_merge_on_skipped_pipeline = module.params[
        'allow_merge_on_skipped_pipeline']
    only_allow_merge_if_all_discussions_are_resolved = module.params[
        'only_allow_merge_if_all_discussions_are_resolved']
    only_allow_merge_if_pipeline_succeeds = module.params[
        'only_allow_merge_if_pipeline_succeeds']
    packages_enabled = module.params['packages_enabled']
    remove_source_branch_after_merge = module.params[
        'remove_source_branch_after_merge']
    squash_option = module.params['squash_option']
    ci_config_path = module.params['ci_config_path']
    shared_runners_enabled = module.params['shared_runners_enabled']
    avatar_path = module.params['avatar_path']
    default_branch = module.params['default_branch']

    if default_branch and not initialize_with_readme:
        module.fail_json(
            msg=
            "Param default_branch need param initialize_with_readme set to true"
        )

    if not HAS_GITLAB_PACKAGE:
        module.fail_json(msg=missing_required_lib("python-gitlab"),
                         exception=GITLAB_IMP_ERR)

    gitlab_instance = gitlab_authentication(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)

    namespace = None
    namespace_id = None
    if group_identifier:
        group = find_group(gitlab_instance, group_identifier)
        if group is None:
            module.fail_json(
                msg="Failed to create project: group %s doesn't exists" %
                group_identifier)

        namespace_id = group.id
    else:
        if username:
            namespace = gitlab_instance.namespaces.list(search=username)[0]
        else:
            namespace = gitlab_instance.namespaces.list(
                search=gitlab_instance.user.username)[0]
        namespace_id = namespace.id

    if not namespace_id:
        module.fail_json(
            msg=
            "Failed to find the namespace or group ID which is required to look up the namespace"
        )

    try:
        namespace = gitlab_instance.namespaces.get(namespace_id)
    except gitlab.exceptions.GitlabGetError as e:
        module.fail_json(
            msg="Failed to find the namespace for the given user: %s" %
            to_native(e))

    if not namespace:
        module.fail_json(msg="Failed to find the namespace for the project")
    project_exists = gitlab_project.exists_project(namespace, project_path)

    if state == 'absent':
        if project_exists:
            gitlab_project.delete_project()
            module.exit_json(changed=True,
                             msg="Successfully deleted project %s" %
                             project_name)
        module.exit_json(changed=False,
                         msg="Project deleted or does not exists")

    if state == 'present':

        if gitlab_project.create_or_update_project(
                project_name, namespace, {
                    "path": project_path,
                    "description": project_description,
                    "initialize_with_readme": initialize_with_readme,
                    "default_branch": default_branch,
                    "issues_enabled": issues_enabled,
                    "merge_requests_enabled": merge_requests_enabled,
                    "merge_method": merge_method,
                    "wiki_enabled": wiki_enabled,
                    "snippets_enabled": snippets_enabled,
                    "visibility": visibility,
                    "import_url": import_url,
                    "lfs_enabled": lfs_enabled,
                    "allow_merge_on_skipped_pipeline":
                    allow_merge_on_skipped_pipeline,
                    "only_allow_merge_if_all_discussions_are_resolved":
                    only_allow_merge_if_all_discussions_are_resolved,
                    "only_allow_merge_if_pipeline_succeeds":
                    only_allow_merge_if_pipeline_succeeds,
                    "packages_enabled": packages_enabled,
                    "remove_source_branch_after_merge":
                    remove_source_branch_after_merge,
                    "squash_option": squash_option,
                    "ci_config_path": ci_config_path,
                    "shared_runners_enabled": shared_runners_enabled,
                    "avatar_path": avatar_path,
                }):

            module.exit_json(
                changed=True,
                msg="Successfully created or updated the project %s" %
                project_name,
                project=gitlab_project.project_object._attrs)
        module.exit_json(changed=False,
                         msg="No need to update the project %s" % project_name,
                         project=gitlab_project.project_object._attrs)
Beispiel #10
0
def _validate_argument_values(argument_spec,
                              parameters,
                              options_context=None,
                              errors=None):
    """Ensure all arguments have the requested values, and there are no stray arguments"""

    if errors is None:
        errors = AnsibleValidationErrorMultiple()

    for param, spec in argument_spec.items():
        choices = spec.get('choices')
        if choices is None:
            continue

        if isinstance(choices,
                      (frozenset, KeysView,
                       Sequence)) and not isinstance(choices,
                                                     (binary_type, text_type)):
            if param in parameters:
                # Allow one or more when type='list' param with choices
                if isinstance(parameters[param], list):
                    diff_list = ", ".join([
                        item for item in parameters[param]
                        if item not in choices
                    ])
                    if diff_list:
                        choices_str = ", ".join(
                            [to_native(c) for c in choices])
                        msg = "value of %s must be one or more of: %s. Got no match for: %s" % (
                            param, choices_str, diff_list)
                        if options_context:
                            msg = "{0} found in {1}".format(
                                msg, " -> ".join(options_context))
                        errors.append(ArgumentValueError(msg))
                elif parameters[param] not in choices:
                    # PyYaml converts certain strings to bools. If we can unambiguously convert back, do so before checking
                    # the value. If we can't figure this out, module author is responsible.
                    if parameters[param] == 'False':
                        overlap = BOOLEANS_FALSE.intersection(choices)
                        if len(overlap) == 1:
                            # Extract from a set
                            (parameters[param], ) = overlap

                    if parameters[param] == 'True':
                        overlap = BOOLEANS_TRUE.intersection(choices)
                        if len(overlap) == 1:
                            (parameters[param], ) = overlap

                    if parameters[param] not in choices:
                        choices_str = ", ".join(
                            [to_native(c) for c in choices])
                        msg = "value of %s must be one of: %s, got: %s" % (
                            param, choices_str, parameters[param])
                        if options_context:
                            msg = "{0} found in {1}".format(
                                msg, " -> ".join(options_context))
                        errors.append(ArgumentValueError(msg))
        else:
            msg = "internal error: choices for argument %s are not iterable: %s" % (
                param, choices)
            if options_context:
                msg = "{0} found in {1}".format(msg,
                                                " -> ".join(options_context))
            errors.append(ArgumentTypeError(msg))
Beispiel #11
0
def _to_native_ascii(s):
    return to_native(s, errors='surrogate_or_strict', encoding='ascii')