def __init__(self): argument_spec = basic_auth_argument_spec() argument_spec.update(dict( api_username=dict(type='str', required=True), api_password=dict(type='str', required=True, no_log=True), api_url=dict(type='str', required=True), ssid=dict(type='str', required=True), snapshot_image_id=dict(type='str', required=True), full_threshold=dict(type='int', default=85), name=dict(type='str', required=True), view_mode=dict(type='str', default='readOnly', choices=['readOnly', 'readWrite', 'modeUnknown', '__Undefined']), repo_percentage=dict(type='int', default=20), storage_pool_name=dict(type='str', required=True), state=dict(type='str', required=True, choices=['absent', 'present']) )) self.module = AnsibleModule(argument_spec=argument_spec) args = self.module.params self.state = args['state'] self.ssid = args['ssid'] self.snapshot_image_id = args['snapshot_image_id'] self.full_threshold = args['full_threshold'] self.name = args['name'] self.view_mode = args['view_mode'] self.repo_percentage = args['repo_percentage'] self.storage_pool_name = args['storage_pool_name'] self.url = args['api_url'] self.user = args['api_username'] self.pwd = args['api_password'] self.certs = args['validate_certs'] if not self.url.endswith('/'): self.url += '/'
def __init__(self): argument_spec = basic_auth_argument_spec() argument_spec.update(dict( api_username=dict(type='str', required=True), api_password=dict(type='str', required=True, no_log=True), api_url=dict(type='str', required=True), name=dict(required=True, type='str'), ssid=dict(required=True, type='str'), state=dict(required=True, type='str', choices=['running', 'suspended']), delete_recovery_point=dict(required=False, type='bool', default=False) )) self.module = AnsibleModule(argument_spec=argument_spec) args = self.module.params self.name = args['name'] self.ssid = args['ssid'] self.state = args['state'] self.delete_recovery_point = args['delete_recovery_point'] try: self.user = args['api_username'] self.pwd = args['api_password'] self.url = args['api_url'] except KeyError: self.module.fail_json(msg="You must pass in api_username" "and api_password and api_url to the module.") self.certs = args['validate_certs'] self.post_headers = { "Accept": "application/json", "Content-Type": "application/json" } self.amg_id, self.amg_obj = self.get_amg()
def test_validate_basic_auth_arg(mocker, stdin): kwargs = dict(argument_spec=basic_auth_argument_spec()) am = basic.AnsibleModule(**kwargs) assert isinstance(am.params['api_username'], string_types) assert isinstance(am.params['api_password'], string_types) assert isinstance(am.params['api_url'], string_types) assert isinstance(am.params['validate_certs'], bool)
def __init__(self): argument_spec = basic_auth_argument_spec() argument_spec.update(dict( api_username=dict(type='str', required=True), api_password=dict(type='str', required=True, no_log=True), api_url=dict(type='str', required=True), ssid=dict(type='str', required=True), state=dict(type='str', required=True, choices=['absent', 'present']), group=dict(type='str', required=False), ports=dict(type='list', required=False), force_port=dict(type='bool', default=False), name=dict(type='str', required=True), host_type_index=dict(type='int', required=True) )) self.module = AnsibleModule(argument_spec=argument_spec) args = self.module.params self.group = args['group'] self.ports = args['ports'] self.force_port = args['force_port'] self.name = args['name'] self.host_type_index = args['host_type_index'] self.state = args['state'] self.ssid = args['ssid'] self.url = args['api_url'] self.user = args['api_username'] self.pwd = args['api_password'] self.certs = args['validate_certs'] self.ports = args['ports'] self.post_body = dict() if not self.url.endswith('/'): self.url += '/'
def eseries_proxy_argument_spec(): """Retrieve a base argument specification common to all NetApp E-Series modules for proxy specific tasks""" argument_spec = basic_auth_argument_spec() argument_spec.update( dict(api_username=dict(type="str", required=True), api_password=dict(type="str", required=True, no_log=True), api_url=dict(type="str", required=True), validate_certs=dict(type="bool", required=False, default=True))) return argument_spec
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), name=dict(type='str', required=True), merge_access_levels=dict(type='str', default="maintainer", choices=["maintainer", "developer", "nobody"]), push_access_level=dict(type='str', default="maintainer", choices=["maintainer", "developer", "nobody"]), 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 ) project = module.params['project'] name = module.params['name'] merge_access_levels = module.params['merge_access_levels'] push_access_level = module.params['push_access_level'] state = module.params['state'] if not HAS_GITLAB_PACKAGE: module.fail_json(msg=missing_required_lib("python-gitlab"), exception=GITLAB_IMP_ERR) gitlab_version = gitlab.__version__ if LooseVersion(gitlab_version) < LooseVersion('2.3.0'): module.fail_json(msg="community.general.gitlab_proteched_branch requires python-gitlab Python module >= 2.3.0 (installed version: [%s])." " Please upgrade python-gitlab to version 2.3.0 or above." % gitlab_version) gitlab_instance = gitlabAuthentication(module) this_gitlab = GitlabProtectedBranch(module=module, project=project, gitlab_instance=gitlab_instance) p_branch = this_gitlab.protected_branch_exist(name=name) if not p_branch and state == "present": this_gitlab.create_protected_branch(name=name, merge_access_levels=merge_access_levels, push_access_level=push_access_level) module.exit_json(changed=True, msg="Created the proteched branch.") elif p_branch and state == "present": if not this_gitlab.compare_protected_branch(name, merge_access_levels, push_access_level): this_gitlab.delete_protected_branch(name=name) this_gitlab.create_protected_branch(name=name, merge_access_levels=merge_access_levels, push_access_level=push_access_level) module.exit_json(changed=True, msg="Recreated the proteched branch.") elif p_branch and state == "absent": this_gitlab.delete_protected_branch(name=name) module.exit_json(changed=True, msg="Deleted the proteched branch.") module.exit_json(changed=False, msg="No changes are needed.")
def main(): argument_spec = basic_auth_argument_spec() argument_spec.update(dict( api_username=dict(type='str', required=True), api_password=dict(type='str', required=True, no_log=True), api_url=dict(type='str', required=True), name=dict(required=True, type='str'), new_name=dict(required=False, type='str'), secondaryArrayId=dict(required=True, type='str'), syncIntervalMinutes=dict(required=False, default=10, type='int'), manualSync=dict(required=False, default=False, type='bool'), recoveryWarnThresholdMinutes=dict(required=False, default=20, type='int'), repoUtilizationWarnThreshold=dict(required=False, default=80, type='int'), interfaceType=dict(required=False, choices=['fibre', 'iscsi'], type='str'), ssid=dict(required=True, type='str'), state=dict(required=True, choices=['present', 'absent']), syncWarnThresholdMinutes=dict(required=False, default=10, type='int') )) module = AnsibleModule(argument_spec=argument_spec) p = module.params ssid = p.pop('ssid') api_url = p.pop('api_url') user = p.pop('api_username') pwd = p.pop('api_password') new_name = p.pop('new_name') state = p.pop('state') if not api_url.endswith('/'): api_url += '/' name_exists, spec_matches, api_data, async_id = has_match(module, ssid, api_url, pwd, user, p) if state == 'present': if name_exists and spec_matches: module.exit_json(changed=False, msg="Desired state met", **api_data) elif name_exists and not spec_matches: results = update_async(module, ssid, api_url, pwd, user, p, new_name, async_id) module.exit_json(changed=True, msg="Async mirror group updated", async_id=async_id, **results) elif not name_exists: results = create_async(module, ssid, api_url, user, pwd, p) module.exit_json(changed=True, **results) elif state == 'absent': if name_exists: remove_amg(module, ssid, api_url, pwd, user, async_id) module.exit_json(changed=True, msg="Async mirror group removed.", async_id=async_id) else: module.exit_json(changed=False, msg="Async Mirror group: %s already absent" % p['name'])
def main(): argument_spec = basic_auth_argument_spec() argument_spec.update( dict(name=dict(required=False, type='str'), ssid=dict(required=False, type='str'), current_password=dict(required=False, no_log=True), new_password=dict(required=True, no_log=True), set_admin=dict(required=True, type='bool'), api_url=dict(required=True), api_username=dict(required=False), api_password=dict(required=False, no_log=True))) module = AnsibleModule(argument_spec=argument_spec, mutually_exclusive=[['name', 'ssid']], required_one_of=[['name', 'ssid']]) name = module.params['name'] ssid = module.params['ssid'] current_password = module.params['current_password'] new_password = module.params['new_password'] set_admin = module.params['set_admin'] user = module.params['api_username'] pwd = module.params['api_password'] api_url = module.params['api_url'] module.validate_certs = module.params['validate_certs'] if not api_url.endswith('/'): api_url += '/' if name: ssid = get_ssid(module, name, api_url, user, pwd) ro_pwd, admin_pwd = get_pwd_status(module, ssid, api_url, user, pwd) if admin_pwd and not current_password: module.fail_json( msg="Admin account has a password set. " + "You must supply current_password in order to update the RO or Admin passwords" ) if len(new_password) > 30: module.fail_json( msg="Passwords must not be greater than 30 characters in length") result = set_password(module, ssid, api_url, user, pwd, current_password=current_password, new_password=new_password, set_admin=set_admin) module.exit_json(changed=True, msg="Password Updated Successfully", password_set=result['passwordSet'], password_status=result['passwordStatus'])
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) api_url = module.params['api_url'] gitlab_token = module.params['api_token'] 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) try: gitlab_instance = gitlab.Gitlab(url=api_url, private_token=gitlab_token) gitlab_instance.auth() except (gitlab.exceptions.GitlabAuthenticationError, gitlab.exceptions.GitlabGetError) as e: module.fail_json(msg="Failed to connect to GitLab server: %s" % to_native(e)) except (gitlab.exceptions.GitlabHttpError) as e: module.fail_json(msg="Failed to connect to GitLab server: %s. \ GitLab remove Session API now that private tokens are removed from user API endpoints since version 10.2" % to_native(e)) this_gitlab = GitlabProjectVariables(module=module, gitlab_instance=gitlab_instance) change, return_value = native_python_main(this_gitlab, purge, var_list, state) module.exit_json(changed=change, project_variable=return_value)
def eseries_host_argument_spec(): """Retrieve a base argument specification common to all NetApp E-Series modules""" argument_spec = basic_auth_argument_spec() argument_spec.update( dict(api_username=dict(type='str', required=True), api_password=dict(type='str', required=True, no_log=True), api_url=dict(type='str', required=True), ssid=dict(type='str', required=False, default='1'), validate_certs=dict(type='bool', required=False, default=True))) return argument_spec
def eseries_host_argument_spec(): """Retrieve a base argument specifiation common to all NetApp E-Series modules""" argument_spec = basic_auth_argument_spec() argument_spec.update(dict( api_username=dict(type='str', required=True), api_password=dict(type='str', required=True, no_log=True), api_url=dict(type='str', required=True), ssid=dict(type='str', required=True), validate_certs=dict(type='bool', required=False, default=True), )) return argument_spec
def main(): argument_spec = basic_auth_argument_spec() argument_spec.update( dict( snapshot_group=dict(required=True, type='str'), ssid=dict(required=True, type='str'), api_url=dict(required=True), api_username=dict(required=False), api_password=dict(required=False, no_log=True), validate_certs=dict(required=False, default=True), state=dict(required=True, choices=['create', 'remove'], type='str'), )) module = AnsibleModule(argument_spec) p = module.params ssid = p.pop('ssid') api_url = p.pop('api_url') user = p.pop('api_username') pwd = p.pop('api_password') snapshot_group = p.pop('snapshot_group') desired_state = p.pop('state') if not api_url.endswith('/'): api_url += '/' if desired_state == 'create': created_status, snapshot_id = create_image(module, ssid, api_url, pwd, user, p, snapshot_group) if created_status: module.exit_json(changed=True, msg='Created snapshot image', image_id=snapshot_id) else: module.fail_json( msg= "Could not create snapshot image on system %s, in snapshot group %s" % (ssid, snapshot_group)) else: deleted, error_msg = delete_image(module, ssid, api_url, pwd, user, snapshot_group) if deleted: module.exit_json( changed=True, msg='Deleted snapshot image for snapshot group [%s]' % (snapshot_group)) else: module.fail_json( msg= "Could not create snapshot image on system %s, in snapshot group %s --- %s" % (ssid, snapshot_group, error_msg))
def main(): argument_spec = basic_auth_argument_spec() argument_spec.update(auth_argument_spec()) argument_spec.update(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_username', 'api_oauth_token'], ['api_username', 'api_job_token'], ['api_token', 'api_oauth_token'], ['api_token', 'api_job_token'], ], required_together=[ ['api_username', 'api_password'], ], required_one_of=[[ 'api_username', 'api_token', 'api_oauth_token', 'api_job_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 = gitlab_authentication(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)
def main(): argument_spec = basic_auth_argument_spec() argument_spec.update(dict( name=dict(required=False, type='str'), ssid=dict(required=False, type='str'), current_password=dict(required=False, no_log=True), new_password=dict(required=True, no_log=True), set_admin=dict(required=True, type='bool'), api_url=dict(required=True), api_username=dict(required=False), api_password=dict(required=False, no_log=True) ) ) module = AnsibleModule(argument_spec=argument_spec, mutually_exclusive=[['name', 'ssid']], required_one_of=[['name', 'ssid']]) name = module.params['name'] ssid = module.params['ssid'] current_password = module.params['current_password'] new_password = module.params['new_password'] set_admin = module.params['set_admin'] user = module.params['api_username'] pwd = module.params['api_password'] api_url = module.params['api_url'] if not api_url.endswith('/'): api_url += '/' if name: ssid = get_ssid(module, name, api_url, user, pwd) ro_pwd, admin_pwd = get_pwd_status(module, ssid, api_url, user, pwd) if admin_pwd and not current_password: module.fail_json( msg="Admin account has a password set. " + "You must supply current_password in order to update the RO or Admin passwords") if len(new_password) > 30: module.fail_json(msg="Passwords must not be greater than 30 characters in length") success = set_password(module, ssid, api_url, user, pwd, current_password=current_password, new_password=new_password, set_admin=set_admin) module.exit_json(changed=True, msg="Password Updated Successfully", **success)
def __init__(self): argument_spec = basic_auth_argument_spec() argument_spec.update( api_username=dict(type='str', required=True), api_password=dict(type='str', required=True, no_log=True), api_url=dict(type='str', required=True), state=dict(required=True, choices=['present', 'absent']), base_volume_name=dict(required=True), name=dict(required=True), repo_pct=dict(default=20, type='int'), warning_threshold=dict(default=80, type='int'), delete_limit=dict(default=30, type='int'), full_policy=dict(default='purgepit', choices=['unknown', 'failbasewrites', 'purgepit']), rollback_priority=dict( default='medium', choices=['highest', 'high', 'medium', 'low', 'lowest']), storage_pool_name=dict(type='str'), ssid=dict(required=True), ) self.module = AnsibleModule(argument_spec=argument_spec) self.post_data = dict() self.warning_threshold = self.module.params['warning_threshold'] self.base_volume_name = self.module.params['base_volume_name'] self.name = self.module.params['name'] self.repo_pct = self.module.params['repo_pct'] self.delete_limit = self.module.params['delete_limit'] self.full_policy = self.module.params['full_policy'] self.rollback_priority = self.module.params['rollback_priority'] self.storage_pool_name = self.module.params['storage_pool_name'] self.state = self.module.params['state'] self.url = self.module.params['api_url'] self.user = self.module.params['api_username'] self.pwd = self.module.params['api_password'] self.certs = self.module.params['validate_certs'] self.ssid = self.module.params['ssid'] if not self.url.endswith('/'): self.url += '/' self.changed = False
def main(): argument_spec = basic_auth_argument_spec() argument_spec.update( api_username=dict(type='str', required=True), api_password=dict(type='str', required=True, no_log=True), api_url=dict(type='str', required=True), ssid=dict(required=True) ) module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=True ) p = module.params ssid = p['ssid'] validate_certs = p['validate_certs'] api_usr = p['api_username'] api_pwd = p['api_password'] api_url = p['api_url'] facts = dict() # fetch the list of drive objects try: (rc, resp) = request(api_url + "/storage-systems/%s/drives" % ssid, headers=dict(Accept="application/json"), url_username=api_usr, url_password=api_pwd, validate_certs=validate_certs) except: error = get_exception() module.fail_json( msg="Failed to obtain facts from storage array with id [%s]. Error [%s]" % (ssid, str(error))) # Define a counter using a composite key of the media type (ssd, hdd), spindle speed, and the capacity counter = collections.Counter( ["_".join([ d['driveMediaType'], str(d['spindleSpeed']), str(int(int(d['rawCapacity'])/(1024*1024*1024))) ]) for d in resp] ) facts['disks_by_type'] = [{'tag': key, 'count': counter[key], } for key in counter] result = dict(ansible_facts=facts, changed=False) module.exit_json(msg="Gathered facts for %s." % ssid, **result)
def __init__(self): argument_spec = basic_auth_argument_spec() argument_spec.update( api_username=dict(type='str', required=True), api_password=dict(type='str', required=True, no_log=True), api_url=dict(type='str', required=True), state=dict(required=True, choices=['present', 'absent']), base_volume_name=dict(required=True), name=dict(required=True), repo_pct=dict(default=20, type='int'), warning_threshold=dict(default=80, type='int'), delete_limit=dict(default=30, type='int'), full_policy=dict(default='purgepit', choices=['unknown', 'failbasewrites', 'purgepit']), rollback_priority=dict(default='medium', choices=['highest', 'high', 'medium', 'low', 'lowest']), storage_pool_name=dict(type='str'), ssid=dict(required=True), ) self.module = AnsibleModule(argument_spec=argument_spec) self.post_data = dict() self.warning_threshold = self.module.params['warning_threshold'] self.base_volume_name = self.module.params['base_volume_name'] self.name = self.module.params['name'] self.repo_pct = self.module.params['repo_pct'] self.delete_limit = self.module.params['delete_limit'] self.full_policy = self.module.params['full_policy'] self.rollback_priority = self.module.params['rollback_priority'] self.storage_pool_name = self.module.params['storage_pool_name'] self.state = self.module.params['state'] self.url = self.module.params['api_url'] self.user = self.module.params['api_username'] self.pwd = self.module.params['api_password'] self.certs = self.module.params['validate_certs'] self.ssid = self.module.params['ssid'] if not self.url.endswith('/'): self.url += '/' self.changed = False
def main(): argument_spec = basic_auth_argument_spec() argument_spec.update(dict( snapshot_group=dict(required=True, type='str'), ssid=dict(required=True, type='str'), api_url=dict(required=True), api_username=dict(required=False), api_password=dict(required=False, no_log=True), validate_certs=dict(required=False, default=True), state=dict(required=True, choices=['create', 'remove'], type='str'), )) module = AnsibleModule(argument_spec) p = module.params ssid = p.pop('ssid') api_url = p.pop('api_url') user = p.pop('api_username') pwd = p.pop('api_password') snapshot_group = p.pop('snapshot_group') desired_state = p.pop('state') if not api_url.endswith('/'): api_url += '/' if desired_state == 'create': created_status, snapshot_id = create_image(module, ssid, api_url, pwd, user, p, snapshot_group) if created_status: module.exit_json(changed=True, msg='Created snapshot image', image_id=snapshot_id) else: module.fail_json( msg="Could not create snapshot image on system %s, in snapshot group %s" % (ssid, snapshot_group)) else: deleted, error_msg = delete_image(module, ssid, api_url, pwd, user, snapshot_group) if deleted: module.exit_json(changed=True, msg='Deleted snapshot image for snapshot group [%s]' % (snapshot_group)) else: module.fail_json( msg="Could not create snapshot image on system %s, in snapshot group %s --- %s" % ( ssid, snapshot_group, error_msg))
def main(): argument_spec = basic_auth_argument_spec() argument_spec.update( dict( name=dict(required=True, type='str'), role=dict(required=True, choices=['primary', 'secondary']), noSync=dict(required=False, type='bool', default=False), force=dict(required=False, type='bool', default=False), ssid=dict(required=True, type='str'), api_url=dict(required=True), api_username=dict(required=False), api_password=dict(required=False, no_log=True), )) module = AnsibleModule(argument_spec=argument_spec) p = module.params ssid = p.pop('ssid') api_url = p.pop('api_url') user = p.pop('api_username') pwd = p.pop('api_password') name = p.pop('name') if not api_url.endswith('/'): api_url += '/' agm_exists, has_desired_role, async_id, amg_data = has_match( module, ssid, api_url, pwd, user, p, name) if not agm_exists: module.fail_json( msg="No Async Mirror Group with the name: '%s' was found" % name) elif has_desired_role: module.exit_json(changed=False, **amg_data) else: amg_data = update_amg(module, ssid, api_url, user, pwd, p, async_id) if amg_data: module.exit_json(changed=True, **amg_data) else: module.exit_json(changed=True, msg="AMG role changed.")
def __init__(self): argument_spec = basic_auth_argument_spec() argument_spec.update( api_username=dict(type="str", required=True), api_password=dict(type="str", required=True, no_log=True), api_url=dict(type="str", required=True), state=dict(required=True, choices=["present", "absent"]), base_volume_name=dict(required=True), name=dict(required=True), repo_pct=dict(default=20, type="int"), warning_threshold=dict(default=80, type="int"), delete_limit=dict(default=30, type="int"), full_policy=dict(default="purgepit", choices=["unknown", "failbasewrites", "purgepit"]), rollback_priority=dict(default="medium", choices=["highest", "high", "medium", "low", "lowest"]), storage_pool_name=dict(type="str"), ssid=dict(required=True), ) self.module = AnsibleModule(argument_spec=argument_spec) self.post_data = dict() self.warning_threshold = self.module.params["warning_threshold"] self.base_volume_name = self.module.params["base_volume_name"] self.name = self.module.params["name"] self.repo_pct = self.module.params["repo_pct"] self.delete_limit = self.module.params["delete_limit"] self.full_policy = self.module.params["full_policy"] self.rollback_priority = self.module.params["rollback_priority"] self.storage_pool_name = self.module.params["storage_pool_name"] self.state = self.module.params["state"] self.url = self.module.params["api_url"] self.user = self.module.params["api_username"] self.pwd = self.module.params["api_password"] self.certs = self.module.params["validate_certs"] self.ssid = self.module.params["ssid"] if not self.url.endswith("/"): self.url += "/" self.changed = False
def main(): argument_spec = basic_auth_argument_spec() argument_spec.update(dict( name=dict(required=True, type='str'), role=dict(required=True, choices=['primary', 'secondary']), noSync=dict(required=False, type='bool', default=False), force=dict(required=False, type='bool', default=False), ssid=dict(required=True, type='str'), api_url=dict(required=True), api_username=dict(required=False), api_password=dict(required=False, no_log=True), )) module = AnsibleModule(argument_spec=argument_spec) p = module.params ssid = p.pop('ssid') api_url = p.pop('api_url') user = p.pop('api_username') pwd = p.pop('api_password') name = p.pop('name') if not api_url.endswith('/'): api_url += '/' agm_exists, has_desired_role, async_id, amg_data = has_match(module, ssid, api_url, pwd, user, p, name) if not agm_exists: module.fail_json(msg="No Async Mirror Group with the name: '%s' was found" % name) elif has_desired_role: module.exit_json(changed=False, **amg_data) else: amg_data = update_amg(module, ssid, api_url, user, pwd, p, async_id) if amg_data: module.exit_json(changed=True, **amg_data) else: module.exit_json(changed=True, msg="AMG role changed.")
def __init__(self): self._size_unit_map = dict(bytes=1, b=1, kb=1024, mb=1024**2, gb=1024**3, tb=1024**4, pb=1024**5, eb=1024**6, zb=1024**7, yb=1024**8) self._post_headers = dict(Accept="application/json") self._post_headers['Content-Type'] = 'application/json' argument_spec = basic_auth_argument_spec() argument_spec.update( dict( state=dict(required=True, choices=['present', 'absent']), ssid=dict(required=True, type='str'), name=dict(required=True, type='str'), storage_pool_name=dict(type='str'), size_unit=dict(default='gb', choices=[ 'bytes', 'b', 'kb', 'mb', 'gb', 'tb', 'pb', 'eb', 'zb', 'yb' ], type='str'), size=dict(type='int'), segment_size_kb=dict(default=128, choices=[8, 16, 32, 64, 128, 256, 512], type='int'), ssd_cache_enabled=dict( type='bool'), # no default, leave existing setting alone data_assurance_enabled=dict(default=False, type='bool'), thin_provision=dict(default=False, type='bool'), thin_volume_repo_size=dict(type='int'), thin_volume_max_repo_size=dict(type='int'), # TODO: add cache, owning controller support, thin expansion policy, etc log_path=dict(type='str'), api_url=dict(type='str'), api_username=dict(type='str'), api_password=dict(type='str', no_log=True), validate_certs=dict(type='bool'), )) self.module = AnsibleModule(argument_spec=argument_spec, required_if=[ ('state', 'present', ['storage_pool_name', 'size']), ('thin_provision', 'true', ['thin_volume_repo_size']) ], supports_check_mode=True) p = self.module.params log_path = p['log_path'] # logging setup self._logger = logging.getLogger(self.__class__.__name__) self.debug = self._logger.debug if log_path: logging.basicConfig(level=logging.DEBUG, filename=log_path) self.state = p['state'] self.ssid = p['ssid'] self.name = p['name'] self.storage_pool_name = p['storage_pool_name'] self.size_unit = p['size_unit'] self.size = p['size'] self.segment_size_kb = p['segment_size_kb'] self.ssd_cache_enabled = p['ssd_cache_enabled'] self.data_assurance_enabled = p['data_assurance_enabled'] self.thin_provision = p['thin_provision'] self.thin_volume_repo_size = p['thin_volume_repo_size'] self.thin_volume_max_repo_size = p['thin_volume_max_repo_size'] if not self.thin_volume_max_repo_size: self.thin_volume_max_repo_size = self.size self.validate_certs = p['validate_certs'] try: self.api_usr = p['api_username'] self.api_pwd = p['api_password'] self.api_url = p['api_url'] except KeyError: self.module.fail_json( msg="You must pass in api_username " "and api_password and api_url to the module.")
def main(): argument_spec = basic_auth_argument_spec() argument_spec.update( dict(state=dict(required=True, choices=['present', 'absent']), ssid=dict(required=True, type='str'), controller_addresses=dict(type='list'), array_wwn=dict(required=False, type='str'), array_password=dict(required=False, type='str', no_log=True), array_status_timeout_sec=dict(default=60, type='int'), enable_trace=dict(default=False, type='bool'), meta_tags=dict(type='list'))) module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=True, mutually_exclusive=[['controller_addresses', 'array_wwn']], required_if=[('state', 'present', ['controller_addresses'])]) p = module.params state = p['state'] ssid = p['ssid'] controller_addresses = p['controller_addresses'] array_wwn = p['array_wwn'] array_password = p['array_password'] array_status_timeout_sec = p['array_status_timeout_sec'] validate_certs = p['validate_certs'] meta_tags = p['meta_tags'] enable_trace = p['enable_trace'] api_usr = p['api_username'] api_pwd = p['api_password'] api_url = p['api_url'] changed = False array_exists = False try: (rc, resp) = request(api_url + "/storage-systems/%s" % ssid, headers=dict(Accept="application/json"), url_username=api_usr, url_password=api_pwd, validate_certs=validate_certs, ignore_errors=True) except: err = get_exception() module.fail_json( msg="Error accessing storage-system with id [%s]. Error [%s]" % (ssid, str(err))) array_exists = True array_detail = resp if rc == 200: if state == 'absent': changed = True array_exists = False elif state == 'present': current_addresses = frozenset(i for i in (array_detail['ip1'], array_detail['ip2']) if i) if set(controller_addresses) != current_addresses: changed = True if array_detail['wwn'] != array_wwn and array_wwn is not None: module.fail_json( msg= 'It seems you may have specified a bad WWN. The storage system ID you specified, %s, currently has the WWN of %s' % (ssid, array_detail['wwn'])) elif rc == 404: if state == 'present': changed = True array_exists = False else: changed = False module.exit_json(changed=changed, msg="Storage system was not present.") if changed and not module.check_mode: if state == 'present': if not array_exists: # add the array array_add_req = dict(id=ssid, controllerAddresses=controller_addresses, metaTags=meta_tags, enableTrace=enable_trace) if array_wwn: array_add_req['wwn'] = array_wwn if array_password: array_add_req['password'] = array_password post_headers = dict(Accept="application/json") post_headers['Content-Type'] = 'application/json' request_data = json.dumps(array_add_req) try: (rc, resp) = do_post(ssid, api_url, post_headers, api_usr, api_pwd, validate_certs, request_data, array_status_timeout_sec) except: err = get_exception() module.fail_json( msg= "Failed to add storage system. Id[%s]. Request body [%s]. Error[%s]." % (ssid, request_data, str(err))) else: # array exists, modify... post_headers = dict(Accept="application/json") post_headers['Content-Type'] = 'application/json' post_body = dict(controllerAddresses=controller_addresses, removeAllTags=True, enableTrace=enable_trace, metaTags=meta_tags) try: (rc, resp) = do_post(ssid, api_url, post_headers, api_usr, api_pwd, validate_certs, post_body, array_status_timeout_sec) except: err = get_exception() module.fail_json( msg= "Failed to update storage system. Id[%s]. Request body [%s]. Error[%s]." % (ssid, post_body, str(err))) elif state == 'absent': # delete the array try: (rc, resp) = request(api_url + "/storage-systems/%s" % ssid, method='DELETE', url_username=api_usr, url_password=api_pwd, validate_certs=validate_certs) except: err = get_exception() module.fail_json( msg="Failed to remove storage array. Id[%s]. Error[%s]." % (ssid, str(err))) if rc == 422: module.exit_json(changed=changed, msg="Storage system was not presnt.") if rc == 204: module.exit_json(changed=changed, msg="Storage system removed.") module.exit_json(changed=changed, **resp)
def main(): argument_spec = basic_auth_argument_spec() argument_spec.update(dict( api_username=dict(type='str', required=True), api_password=dict(type='str', required=True, no_log=True), api_url=dict(type='str', required=True), state=dict(required=True, choices=['present', 'absent']), target=dict(required=False, default=None), target_type=dict(required=False, choices=['host', 'group']), lun=dict(required=False, type='int', default=0), ssid=dict(required=False), volume_name=dict(required=True), )) module = AnsibleModule(argument_spec=argument_spec) state = module.params['state'] target = module.params['target'] target_type = module.params['target_type'] lun = module.params['lun'] ssid = module.params['ssid'] vol_name = module.params['volume_name'] user = module.params['api_username'] pwd = module.params['api_password'] api_url = module.params['api_url'] if not api_url.endswith('/'): api_url += '/' volume_map = get_volumes(module, ssid, api_url, user, pwd, "volumes") thin_volume_map = get_volumes(module, ssid, api_url, user, pwd, "thin-volumes") volref = None for vol in volume_map: if vol['label'] == vol_name: volref = vol['volumeRef'] if not volref: for vol in thin_volume_map: if vol['label'] == vol_name: volref = vol['volumeRef'] if not volref: module.fail_json(changed=False, msg="No volume with the name %s was found" % vol_name) host_and_group_mapping = get_host_and_group_map(module, ssid, api_url, user, pwd) desired_lun_mapping = dict( mapRef=host_and_group_mapping[target_type][target], lun=lun, volumeRef=volref ) lun_mappings = get_lun_mappings(ssid, api_url, user, pwd) if state == 'present': if desired_lun_mapping in lun_mappings: module.exit_json(changed=False, msg="Mapping exists") else: result = create_mapping(module, ssid, desired_lun_mapping, vol_name, api_url, user, pwd) module.exit_json(changed=True, **result) elif state == 'absent': if desired_lun_mapping in lun_mappings: result = remove_mapping(module, ssid, desired_lun_mapping, api_url, user, pwd) module.exit_json(changed=True, msg="Mapping removed") else: module.exit_json(changed=False, msg="Mapping absent")
def main(): argument_spec = basic_auth_argument_spec() argument_spec.update( api_username=dict(type='str', required=True), api_password=dict(type='str', required=True, no_log=True), api_url=dict(type='str', required=True), ssid=dict(required=True)) module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=True ) p = module.params ssid = p['ssid'] validate_certs = p['validate_certs'] api_usr = p['api_username'] api_pwd = p['api_password'] api_url = p['api_url'] facts = dict(ssid=ssid) # fetch the list of storage-pool objects and look for one with a matching name try: (rc, resp) = request(api_url + "/storage-systems/%s/graph" % ssid, headers=dict(Accept="application/json"), url_username=api_usr, url_password=api_pwd, validate_certs=validate_certs) except Exception as e: module.fail_json( msg="Failed to obtain facts from storage array with id [%s]. Error [%s]" % (ssid, to_native(e))) facts['snapshot_images'] = [ dict( id=d['id'], status=d['status'], pit_capacity=d['pitCapacity'], creation_method=d['creationMethod'], reposity_cap_utilization=d['repositoryCapacityUtilization'], active_cow=d['activeCOW'], rollback_source=d['isRollbackSource'] ) for d in resp['highLevelVolBundle']['pit']] facts['netapp_disks'] = [ dict( id=d['id'], available=d['available'], media_type=d['driveMediaType'], status=d['status'], usable_bytes=d['usableCapacity'], tray_ref=d['physicalLocation']['trayRef'], product_id=d['productID'], firmware_version=d['firmwareVersion'], serial_number=d['serialNumber'].lstrip() ) for d in resp['drive']] facts['netapp_storage_pools'] = [ dict( id=sp['id'], name=sp['name'], available_capacity=sp['freeSpace'], total_capacity=sp['totalRaidedSpace'], used_capacity=sp['usedSpace'] ) for sp in resp['volumeGroup']] all_volumes = list(resp['volume']) # all_volumes.extend(resp['thinVolume']) # TODO: exclude thin-volume repo volumes (how to ID?) facts['netapp_volumes'] = [ dict( id=v['id'], name=v['name'], parent_storage_pool_id=v['volumeGroupRef'], capacity=v['capacity'], is_thin_provisioned=v['thinProvisioned'] ) for v in all_volumes] features = [f for f in resp['sa']['capabilities']] features.extend([f['capability'] for f in resp['sa']['premiumFeatures'] if f['isEnabled']]) features = list(set(features)) # ensure unique features.sort() facts['netapp_enabled_features'] = features # TODO: include other details about the storage pool (size, type, id, etc) result = dict(ansible_facts=facts, changed=False) module.exit_json(msg="Gathered facts for %s." % ssid, **result)
def main(): argument_spec = basic_auth_argument_spec() argument_spec.update(dict( state=dict(required=True, choices=['present', 'absent']), ssid=dict(required=True, type='str'), controller_addresses=dict(type='list'), array_wwn=dict(required=False, type='str'), array_password=dict(required=False, type='str', no_log=True), array_status_timeout_sec=dict(default=60, type='int'), enable_trace=dict(default=False, type='bool'), meta_tags=dict(type='list') )) module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=True, mutually_exclusive=[['controller_addresses', 'array_wwn']], required_if=[('state', 'present', ['controller_addresses'])] ) p = module.params state = p['state'] ssid = p['ssid'] controller_addresses = p['controller_addresses'] array_wwn = p['array_wwn'] array_password = p['array_password'] array_status_timeout_sec = p['array_status_timeout_sec'] validate_certs = p['validate_certs'] meta_tags = p['meta_tags'] enable_trace = p['enable_trace'] api_usr = p['api_username'] api_pwd = p['api_password'] api_url = p['api_url'] changed = False array_exists = False try: (rc, resp) = request(api_url + "/storage-systems/%s" % ssid, headers=dict(Accept="application/json"), url_username=api_usr, url_password=api_pwd, validate_certs=validate_certs, ignore_errors=True) except: err = get_exception() module.fail_json(msg="Error accessing storage-system with id [%s]. Error [%s]" % (ssid, str(err))) array_exists = True array_detail = resp if rc == 200: if state == 'absent': changed = True array_exists = False elif state == 'present': current_addresses = frozenset(i for i in (array_detail['ip1'], array_detail['ip2']) if i) if set(controller_addresses) != current_addresses: changed = True if array_detail['wwn'] != array_wwn and array_wwn is not None: module.fail_json( msg='It seems you may have specified a bad WWN. The storage system ID you specified, %s, currently has the WWN of %s' % (ssid, array_detail['wwn']) ) elif rc == 404: if state == 'present': changed = True array_exists = False else: changed = False module.exit_json(changed=changed, msg="Storage system was not present.") if changed and not module.check_mode: if state == 'present': if not array_exists: # add the array array_add_req = dict( id=ssid, controllerAddresses=controller_addresses, metaTags=meta_tags, enableTrace=enable_trace ) if array_wwn: array_add_req['wwn'] = array_wwn if array_password: array_add_req['password'] = array_password post_headers = dict(Accept="application/json") post_headers['Content-Type'] = 'application/json' request_data = json.dumps(array_add_req) try: (rc, resp) = do_post(ssid, api_url, post_headers, api_usr, api_pwd, validate_certs, request_data, array_status_timeout_sec) except: err = get_exception() module.fail_json(msg="Failed to add storage system. Id[%s]. Request body [%s]. Error[%s]." % (ssid, request_data, str(err))) else: # array exists, modify... post_headers = dict(Accept="application/json") post_headers['Content-Type'] = 'application/json' post_body = dict( controllerAddresses=controller_addresses, removeAllTags=True, enableTrace=enable_trace, metaTags=meta_tags ) try: (rc, resp) = do_post(ssid, api_url, post_headers, api_usr, api_pwd, validate_certs, post_body, array_status_timeout_sec) except: err = get_exception() module.fail_json(msg="Failed to update storage system. Id[%s]. Request body [%s]. Error[%s]." % (ssid, post_body, str(err))) elif state == 'absent': # delete the array try: (rc, resp) = request(api_url + "/storage-systems/%s" % ssid, method='DELETE', url_username=api_usr, url_password=api_pwd, validate_certs=validate_certs) except: err = get_exception() module.fail_json(msg="Failed to remove storage array. Id[%s]. Error[%s]." % (ssid, str(err))) if rc == 422: module.exit_json(changed=changed, msg="Storage system was not presnt.") if rc == 204: module.exit_json(changed=changed, msg="Storage system removed.") module.exit_json(changed=changed, **resp)
def __init__(self): self.name = None self.log_mode = None self.log_path = None self.api_url = None self.api_username = None self.api_password = None self.ssid = None self.validate_certs = None self.disk_count = None self.size_unit = None self.cache_size_min = None self.io_type = None self.driveRefs = None self.state = None self._size_unit_map = dict( bytes=1, b=1, kb=1024, mb=1024 ** 2, gb=1024 ** 3, tb=1024 ** 4, pb=1024 ** 5, eb=1024 ** 6, zb=1024 ** 7, yb=1024 ** 8 ) argument_spec = basic_auth_argument_spec() argument_spec.update(dict( api_username=dict(type='str', required=True), api_password=dict(type='str', required=True, no_log=True), api_url=dict(type='str', required=True), state=dict(default='present', choices=['present', 'absent'], type='str'), ssid=dict(required=True, type='str'), name=dict(required=True, type='str'), disk_count=dict(type='int'), disk_refs=dict(type='list'), cache_size_min=dict(type='int'), io_type=dict(default='filesystem', choices=['filesystem', 'database', 'media']), size_unit=dict(default='gb', choices=['bytes', 'b', 'kb', 'mb', 'gb', 'tb', 'pb', 'eb', 'zb', 'yb'], type='str'), criteria_disk_phy_type=dict(choices=['sas', 'sas4k', 'fibre', 'fibre520b', 'scsi', 'sata', 'pata'], type='str'), log_mode=dict(type='str'), log_path=dict(type='str'), )) self.module = AnsibleModule( argument_spec=argument_spec, required_if=[ ], mutually_exclusive=[ ], # TODO: update validation for various selection criteria supports_check_mode=True ) self.__dict__.update(self.module.params) # logging setup self._logger = logging.getLogger(self.__class__.__name__) self.debug = self._logger.debug if self.log_mode == 'file' and self.log_path: logging.basicConfig(level=logging.DEBUG, filename=self.log_path) elif self.log_mode == 'stderr': logging.basicConfig(level=logging.DEBUG, stream=sys.stderr) self.post_headers = dict(Accept="application/json") self.post_headers['Content-Type'] = 'application/json'
def __init__(self): self._sp_drives_cached = None self._size_unit_map = dict( bytes=1, b=1, kb=1024, mb=1024 ** 2, gb=1024 ** 3, tb=1024 ** 4, pb=1024 ** 5, eb=1024 ** 6, zb=1024 ** 7, yb=1024 ** 8 ) argument_spec = basic_auth_argument_spec() argument_spec.update(dict( api_username=dict(type='str', required=True), api_password=dict(type='str', required=True, no_log=True), api_url=dict(type='str', required=True), state=dict(required=True, choices=['present', 'absent'], type='str'), ssid=dict(required=True, type='str'), name=dict(required=True, type='str'), criteria_size_unit=dict(default='gb', type='str'), criteria_drive_count=dict(type='int'), criteria_drive_interface_type=dict(choices=['sas', 'sas4k', 'fibre', 'fibre520b', 'scsi', 'sata', 'pata'], type='str'), criteria_drive_type=dict(choices=['ssd', 'hdd'], type='str'), criteria_drive_min_size=dict(type='int'), criteria_drive_require_fde=dict(type='bool'), criteria_min_usable_capacity=dict(type='int'), raid_level=dict( choices=['raidUnsupported', 'raidAll', 'raid0', 'raid1', 'raid3', 'raid5', 'raid6', 'raidDiskPool']), erase_secured_drives=dict(type='bool'), log_path=dict(type='str'), remove_drives=dict(type='list'), secure_pool=dict(type='bool', default=False), reserve_drive_count=dict(type='int'), remove_volumes=dict(type='bool', default=False) )) self.module = AnsibleModule( argument_spec=argument_spec, required_if=[ ('state', 'present', ['raid_level']) ], mutually_exclusive=[ ], # TODO: update validation for various selection criteria supports_check_mode=True ) p = self.module.params log_path = p['log_path'] # logging setup self._logger = logging.getLogger(self.__class__.__name__) self.debug = self._logger.debug if log_path: logging.basicConfig(level=logging.DEBUG, filename=log_path) self.state = p['state'] self.ssid = p['ssid'] self.name = p['name'] self.validate_certs = p['validate_certs'] self.criteria_drive_count = p['criteria_drive_count'] self.criteria_drive_type = p['criteria_drive_type'] self.criteria_size_unit = p['criteria_size_unit'] self.criteria_drive_min_size = p['criteria_drive_min_size'] self.criteria_min_usable_capacity = p['criteria_min_usable_capacity'] self.criteria_drive_interface_type = p['criteria_drive_interface_type'] self.criteria_drive_require_fde = p['criteria_drive_require_fde'] self.raid_level = p['raid_level'] self.erase_secured_drives = p['erase_secured_drives'] self.remove_drives = p['remove_drives'] self.secure_pool = p['secure_pool'] self.reserve_drive_count = p['reserve_drive_count'] self.remove_volumes = p['remove_volumes'] try: self.api_usr = p['api_username'] self.api_pwd = p['api_password'] self.api_url = p['api_url'] except KeyError: self.module.fail_json(msg="You must pass in api_username " "and api_password and api_url to the module.") self.post_headers = dict(Accept="application/json") self.post_headers['Content-Type'] = 'application/json'
def main(): argument_spec = basic_auth_argument_spec() argument_spec.update( dict(api_token=dict(type='str', required=True, no_log=True), gitlab_group=dict(type='str', required=True), gitlab_user=dict(type='str', required=True), state=dict(type='str', default='present', choices=['present', 'absent']), access_level=dict(type='str', required=False, choices=[ 'guest', 'reporter', 'developer', 'maintainer', 'owner' ]))) 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'], ], required_if=[ ['state', 'present', ['access_level']], ], supports_check_mode=True, ) if not HAS_PY_GITLAB: module.fail_json(msg=missing_required_lib( 'python-gitlab', url='https://python-gitlab.readthedocs.io/en/stable/'), exception=GITLAB_IMP_ERR) gitlab_group = module.params['gitlab_group'] gitlab_user = module.params['gitlab_user'] state = module.params['state'] access_level = module.params['access_level'] # convert access level string input to int if access_level: access_level_int = { 'guest': gitlab.GUEST_ACCESS, 'reporter': gitlab.REPORTER_ACCESS, 'developer': gitlab.DEVELOPER_ACCESS, 'maintainer': gitlab.MAINTAINER_ACCESS, 'owner': gitlab.OWNER_ACCESS } access_level = access_level_int[access_level] # connect to gitlab server gl = gitlabAuthentication(module) group = GitLabGroup(module, gl) gitlab_user_id = group.get_user_id(gitlab_user) gitlab_group_id = group.get_group_id(gitlab_group) # group doesn't exist if not gitlab_group_id: module.fail_json(msg="group '%s' not found." % gitlab_group) # user doesn't exist if not gitlab_user_id: if state == 'absent': module.exit_json( changed=False, result= "user '%s' not found, and thus also not part of the group" % gitlab_user) else: module.fail_json(msg="user '%s' not found." % gitlab_user) members = group.get_members_in_a_group(gitlab_group_id) is_user_a_member = group.is_user_a_member(members, gitlab_user_id) # check if the user is a member in the group if not is_user_a_member: if state == 'present': # add user to the group if not module.check_mode: group.add_member_to_group(gitlab_user_id, gitlab_group_id, access_level) module.exit_json( changed=True, result="Successfully added user '%s' to the group." % gitlab_user) # state as absent else: module.exit_json( changed=False, result= "User, '%s', is not a member in the group. No change to report" % gitlab_user) # in case that a user is a member else: if state == 'present': # compare the access level user_access_level = group.get_user_access_level( members, gitlab_user_id) if user_access_level == access_level: module.exit_json( changed=False, result= "User, '%s', is already a member in the group. No change to report" % gitlab_user) else: # update the access level for the user if not module.check_mode: group.update_user_access_level(members, gitlab_user_id, access_level) module.exit_json( changed=True, result= "Successfully updated the access level for the user, '%s'" % gitlab_user) else: # remove the user from the group if not module.check_mode: group.remove_user_from_group(gitlab_user_id, gitlab_group_id) module.exit_json( changed=True, result="Successfully removed user, '%s', from the group" % gitlab_user)
def __init__(self): self._size_unit_map = dict( bytes=1, b=1, kb=1024, mb=1024 ** 2, gb=1024 ** 3, tb=1024 ** 4, pb=1024 ** 5, eb=1024 ** 6, zb=1024 ** 7, yb=1024 ** 8, ) self._post_headers = dict(Accept="application/json") self._post_headers["Content-Type"] = "application/json" argument_spec = basic_auth_argument_spec() argument_spec.update( dict( state=dict(required=True, choices=["present", "absent"]), ssid=dict(required=True, type="str"), name=dict(required=True, type="str"), storage_pool_name=dict(type="str"), size_unit=dict( default="gb", choices=["bytes", "b", "kb", "mb", "gb", "tb", "pb", "eb", "zb", "yb"], type="str" ), size=dict(type="int"), segment_size_kb=dict(default=128, choices=[8, 16, 32, 64, 128, 256, 512], type="int"), ssd_cache_enabled=dict(type="bool"), # no default, leave existing setting alone data_assurance_enabled=dict(default=False, type="bool"), thin_provision=dict(default=False, type="bool"), thin_volume_repo_size=dict(type="int"), thin_volume_max_repo_size=dict(type="int"), # TODO: add cache, owning controller support, thin expansion policy, etc log_path=dict(type="str"), api_url=dict(type="str"), api_username=dict(type="str"), api_password=dict(type="str"), validate_certs=dict(type="bool"), ) ) self.module = AnsibleModule( argument_spec=argument_spec, required_if=[ ("state", "present", ["storage_pool_name", "size"]), ("thin_provision", "true", ["thin_volume_repo_size"]), ], supports_check_mode=True, ) p = self.module.params log_path = p["log_path"] # logging setup self._logger = logging.getLogger(self.__class__.__name__) self.debug = self._logger.debug if log_path: logging.basicConfig(level=logging.DEBUG, filename=log_path) self.state = p["state"] self.ssid = p["ssid"] self.name = p["name"] self.storage_pool_name = p["storage_pool_name"] self.size_unit = p["size_unit"] self.size = p["size"] self.segment_size_kb = p["segment_size_kb"] self.ssd_cache_enabled = p["ssd_cache_enabled"] self.data_assurance_enabled = p["data_assurance_enabled"] self.thin_provision = p["thin_provision"] self.thin_volume_repo_size = p["thin_volume_repo_size"] self.thin_volume_max_repo_size = p["thin_volume_max_repo_size"] if not self.thin_volume_max_repo_size: self.thin_volume_max_repo_size = self.size self.validate_certs = p["validate_certs"] try: self.api_usr = p["api_username"] self.api_pwd = p["api_password"] self.api_url = p["api_url"] except KeyError: self.module.fail_json(msg="You must pass in api_username " "and api_password and api_url to the module.")
''' from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.basic import env_fallback from ansible.module_utils.api import basic_auth_argument_spec from ansible.module_utils.common.dict_transformations import dict_merge import ansible.module_utils.alvao as alvao auth_argument_spec_mod = dict( api_username=dict(required=True, fallback=(env_fallback, ['ALVAO_USERNAME'])), api_password=dict(required=True, fallback=(env_fallback, ['ALVAO_PASSWORD'])), api_url=dict(required=True, fallback=(env_fallback, ['ALVAO_URL'])), validate_certs=dict(required=False)) auth_argument_spec = dict_merge(basic_auth_argument_spec(), auth_argument_spec_mod) def main(): module = AnsibleModule(argument_spec=auth_argument_spec, supports_check_mode=True) auth_data = { 'grant_type': 'password', 'username': module.params.get('api_username'), 'password': module.params.get('api_password'), } auth_token_data = alvao.auth_token(module, auth_data) for key in ('validate_certs', 'api_url'):
def __init__(self): self.name = None self.log_mode = None self.log_path = None self.api_url = None self.api_username = None self.api_password = None self.ssid = None self.validate_certs = None self.disk_count = None self.size_unit = None self.cache_size_min = None self.io_type = None self.driveRefs = None self.state = None self._size_unit_map = dict(bytes=1, b=1, kb=1024, mb=1024**2, gb=1024**3, tb=1024**4, pb=1024**5, eb=1024**6, zb=1024**7, yb=1024**8) argument_spec = basic_auth_argument_spec() argument_spec.update( dict( api_username=dict(type='str', required=True), api_password=dict(type='str', required=True, no_log=True), api_url=dict(type='str', required=True), state=dict(default='present', choices=['present', 'absent'], type='str'), ssid=dict(required=True, type='str'), name=dict(required=True, type='str'), disk_count=dict(type='int'), disk_refs=dict(type='list'), cache_size_min=dict(type='int'), io_type=dict(default='filesystem', choices=['filesystem', 'database', 'media']), size_unit=dict(default='gb', choices=[ 'bytes', 'b', 'kb', 'mb', 'gb', 'tb', 'pb', 'eb', 'zb', 'yb' ], type='str'), criteria_disk_phy_type=dict(choices=[ 'sas', 'sas4k', 'fibre', 'fibre520b', 'scsi', 'sata', 'pata' ], type='str'), log_mode=dict(type='str'), log_path=dict(type='str'), )) self.module = AnsibleModule( argument_spec=argument_spec, required_if=[], mutually_exclusive=[], # TODO: update validation for various selection criteria supports_check_mode=True) self.__dict__.update(self.module.params) # logging setup self._logger = logging.getLogger(self.__class__.__name__) self.debug = self._logger.debug if self.log_mode == 'file' and self.log_path: logging.basicConfig(level=logging.DEBUG, filename=self.log_path) elif self.log_mode == 'stderr': logging.basicConfig(level=logging.DEBUG, stream=sys.stderr) self.post_headers = dict(Accept="application/json") self.post_headers['Content-Type'] = 'application/json'
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)
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)
def main(): argument_spec = basic_auth_argument_spec() argument_spec.update(auth_argument_spec()) argument_spec.update( project=dict(type='str', required=True), branch=dict(type='str', required=True), ref_branch=dict(type='str', required=False), 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'], ], required_together=[ ['api_username', 'api_password'], ], required_one_of=[[ 'api_username', 'api_token', 'api_oauth_token', 'api_job_token' ]], required_if=[ ['state', 'present', ['ref_branch'], True], ], supports_check_mode=False) project = module.params['project'] branch = module.params['branch'] ref_branch = module.params['ref_branch'] state = module.params['state'] if not HAS_GITLAB_PACKAGE: module.fail_json(msg=missing_required_lib("python-gitlab"), exception=GITLAB_IMP_ERR) gitlab_version = gitlab.__version__ if LooseVersion(gitlab_version) < LooseVersion('2.3.0'): module.fail_json( msg= "community.general.gitlab_proteched_branch requires python-gitlab Python module >= 2.3.0 (installed version: [%s])." " Please upgrade python-gitlab to version 2.3.0 or above." % gitlab_version) gitlab_instance = gitlab_authentication(module) this_gitlab = GitlabBranch(module=module, project=project, gitlab_instance=gitlab_instance) this_branch = this_gitlab.get_branch(branch) if not this_branch and state == "present": r_branch = this_gitlab.get_branch(ref_branch) if not r_branch: module.fail_json(msg="Ref branch {b} not exist.".format( b=ref_branch)) this_gitlab.create_branch(branch, ref_branch) module.exit_json(changed=True, msg="Created the branch {b}.".format(b=branch)) elif this_branch and state == "present": module.exit_json(changed=False, msg="Branch {b} already exist".format(b=branch)) elif this_branch and state == "absent": try: this_gitlab.delete_branch(this_branch) module.exit_json(changed=True, msg="Branch {b} deleted.".format(b=branch)) except Exception as e: module.fail_json(msg="Error delete branch.", exception=traceback.format_exc()) else: module.exit_json(changed=False, msg="No changes are needed.")
def main(): argument_spec = basic_auth_argument_spec() argument_spec.update( dict( server_url=dict(type='str', required=True, removed_in_version=2.10), login_user=dict(type='str', no_log=True, removed_in_version=2.10), login_password=dict(type='str', no_log=True, removed_in_version=2.10), api_token=dict(type='str', no_log=True, aliases=["login_token"]), 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_url', 'server_url'], ['api_username', 'login_user'], ['api_password', 'login_password'], ['api_username', 'api_token'], ['api_password', 'api_token'], ['login_user', 'login_token'], ['login_password', 'login_token']], required_together=[ ['api_username', 'api_password'], ['login_user', 'login_password'], ], required_one_of=[[ 'api_username', 'api_token', 'login_user', 'login_token' ]], supports_check_mode=True, ) deprecation_warning(module) server_url = module.params['server_url'] login_user = module.params['login_user'] login_password = module.params['login_password'] api_url = module.params['api_url'] validate_certs = module.params['validate_certs'] api_user = module.params['api_username'] api_password = module.params['api_password'] gitlab_url = server_url if api_url is None else api_url gitlab_user = login_user if api_user is None else api_user gitlab_password = login_password if api_password is None else api_password gitlab_token = module.params['api_token'] 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) try: gitlab_instance = gitlab.Gitlab(url=gitlab_url, ssl_verify=validate_certs, email=gitlab_user, password=gitlab_password, private_token=gitlab_token, api_version=4) gitlab_instance.auth() except (gitlab.exceptions.GitlabAuthenticationError, gitlab.exceptions.GitlabGetError) as e: module.fail_json(msg="Failed to connect to Gitlab server: %s" % to_native(e)) except (gitlab.exceptions.GitlabHttpError) as e: module.fail_json(msg="Failed to connect to Gitlab server: %s. \ Gitlab remove Session API now that private tokens are removed from user API endpoints since version 10.2." % to_native(e)) # 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)
def main(): argument_spec = basic_auth_argument_spec() argument_spec.update( dict(api_username=dict(type='str', required=True), api_password=dict(type='str', required=True, no_log=True), api_url=dict(type='str', required=True), name=dict(required=True, type='str'), new_name=dict(required=False, type='str'), secondaryArrayId=dict(required=True, type='str'), syncIntervalMinutes=dict(required=False, default=10, type='int'), manualSync=dict(required=False, default=False, type='bool'), recoveryWarnThresholdMinutes=dict(required=False, default=20, type='int'), repoUtilizationWarnThreshold=dict(required=False, default=80, type='int'), interfaceType=dict(required=False, choices=['fibre', 'iscsi'], type='str'), ssid=dict(required=True, type='str'), state=dict(required=True, choices=['present', 'absent']), syncWarnThresholdMinutes=dict(required=False, default=10, type='int'))) module = AnsibleModule(argument_spec=argument_spec) p = module.params ssid = p.pop('ssid') api_url = p.pop('api_url') user = p.pop('api_username') pwd = p.pop('api_password') new_name = p.pop('new_name') state = p.pop('state') if not api_url.endswith('/'): api_url += '/' name_exists, spec_matches, api_data, async_id = has_match( module, ssid, api_url, pwd, user, p) if state == 'present': if name_exists and spec_matches: module.exit_json(changed=False, msg="Desired state met", **api_data) elif name_exists and not spec_matches: results = update_async(module, ssid, api_url, pwd, user, p, new_name, async_id) module.exit_json(changed=True, msg="Async mirror group updated", async_id=async_id, **results) elif not name_exists: results = create_async(module, ssid, api_url, user, pwd, p) module.exit_json(changed=True, **results) elif state == 'absent': if name_exists: remove_amg(module, ssid, api_url, pwd, user, async_id) module.exit_json(changed=True, msg="Async mirror group removed.", async_id=async_id) else: module.exit_json(changed=False, msg="Async Mirror group: %s already absent" % p['name'])
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, no_log=False), 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)
def main(): argument_spec = basic_auth_argument_spec() argument_spec.update( dict( url=dict(type='str', required=True, removed_in_version="2.10"), api_token=dict(type='str', no_log=True, aliases=["private_token"]), 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_url', 'url'], ['api_username', 'api_token'], ['api_password', 'api_token'], ], required_together=[ ['api_username', 'api_password'], ['login_user', 'login_password'], ], required_one_of=[['api_username', 'api_token']], supports_check_mode=True, ) deprecation_warning(module) url = re.sub('/api.*', '', module.params['url']) api_url = module.params['api_url'] validate_certs = module.params['validate_certs'] gitlab_url = url if api_url is None else api_url gitlab_user = module.params['api_username'] gitlab_password = module.params['api_password'] gitlab_token = module.params['api_token'] 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) try: gitlab_instance = gitlab.Gitlab(url=gitlab_url, ssl_verify=validate_certs, email=gitlab_user, password=gitlab_password, private_token=gitlab_token, api_version=4) gitlab_instance.auth() except (gitlab.exceptions.GitlabAuthenticationError, gitlab.exceptions.GitlabGetError) as e: module.fail_json(msg="Failed to connect to Gitlab server: %s" % to_native(e)) except (gitlab.exceptions.GitlabHttpError) as e: module.fail_json(msg="Failed to connect to Gitlab server: %s. \ Gitlab remove Session API now that private tokens are removed from user API endpoints since version 10.2" % to_native(e)) 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)
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)
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"]), project_creation_level=dict( type='str', choices=['developer', 'maintainer', 'noone']), auto_devops_enabled=dict(type='bool'), subgroup_creation_level=dict(type='str', choices=['maintainer', 'owner']), require_two_factor_authentication=dict(type='bool'), avatar_path=dict(type='path'), )) 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'] project_creation_level = module.params['project_creation_level'] auto_devops_enabled = module.params['auto_devops_enabled'] subgroup_creation_level = module.params['subgroup_creation_level'] require_two_factor_authentication = module.params[ 'require_two_factor_authentication'] avatar_path = module.params['avatar_path'] if not HAS_GITLAB_PACKAGE: module.fail_json(msg=missing_required_lib("python-gitlab"), exception=GITLAB_IMP_ERR) gitlab_instance = gitlab_authentication(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 = find_group(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.exists_group(parent_group.full_path + '/' + group_path) else: group_exists = gitlab_group.exists_group(group_path) if state == 'absent': if group_exists: gitlab_group.delete_group() 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.create_or_update_group( group_name, parent_group, { "path": group_path, "description": description, "visibility": group_visibility, "project_creation_level": project_creation_level, "auto_devops_enabled": auto_devops_enabled, "subgroup_creation_level": subgroup_creation_level, "require_two_factor_authentication": require_two_factor_authentication, "avatar_path": avatar_path, }): module.exit_json( changed=True, msg="Successfully created or updated the group %s" % group_name, group=gitlab_group.group_object._attrs) else: module.exit_json(changed=False, msg="No need to update the group %s" % group_name, group=gitlab_group.group_object._attrs)
def main(): argument_spec = basic_auth_argument_spec() argument_spec.update( dict( server_url=dict(type='str', removed_in_version="2.10"), login_user=dict(type='str', no_log=True, removed_in_version="2.10"), login_password=dict(type='str', no_log=True, removed_in_version="2.10"), api_token=dict(type='str', no_log=True, aliases=["login_token"]), name=dict(type='str', required=True), state=dict(type='str', default="present", choices=["absent", "present"]), username=dict(type='str', required=True), password=dict(type='str', required=True, no_log=True), email=dict(type='str', required=True), 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_url', 'server_url'], ['api_username', 'login_user'], ['api_password', 'login_password'], ['api_username', 'api_token'], ['api_password', 'api_token'], ['login_user', 'login_token'], ['login_password', 'login_token']], required_together=[ ['api_username', 'api_password'], ['login_user', 'login_password'], ], required_one_of=[[ 'api_username', 'api_token', 'login_user', 'login_token' ], ['server_url', 'api_url']], supports_check_mode=True, ) deprecation_warning(module) server_url = module.params['server_url'] login_user = module.params['login_user'] login_password = module.params['login_password'] api_url = module.params['api_url'] validate_certs = module.params['validate_certs'] api_user = module.params['api_username'] api_password = module.params['api_password'] gitlab_url = server_url if api_url is None else api_url gitlab_user = login_user if api_user is None else api_user gitlab_password = login_password if api_password is None else api_password gitlab_token = module.params['api_token'] 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) try: gitlab_instance = gitlab.Gitlab(url=gitlab_url, ssl_verify=validate_certs, email=gitlab_user, password=gitlab_password, private_token=gitlab_token, api_version=4) gitlab_instance.auth() except (gitlab.exceptions.GitlabAuthenticationError, gitlab.exceptions.GitlabGetError) as e: module.fail_json(msg="Failed to connect to GitLab server: %s" % to_native(e)) except (gitlab.exceptions.GitlabHttpError) as e: module.fail_json(msg="Failed to connect to GitLab server: %s. \ GitLab remove Session API now that private tokens are removed from user API endpoints since version 10.2." % to_native(e)) 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)
def __init__(self): self._size_unit_map = dict( bytes=1, b=1, kb=1024, mb=1024 ** 2, gb=1024 ** 3, tb=1024 ** 4, pb=1024 ** 5, eb=1024 ** 6, zb=1024 ** 7, yb=1024 ** 8 ) self._post_headers = dict(Accept="application/json") self._post_headers['Content-Type'] = 'application/json' argument_spec = basic_auth_argument_spec() argument_spec.update(dict( state=dict(required=True, choices=['present', 'absent']), ssid=dict(required=True, type='str'), name=dict(required=True, type='str'), storage_pool_name=dict(type='str'), size_unit=dict(default='gb', choices=['bytes', 'b', 'kb', 'mb', 'gb', 'tb', 'pb', 'eb', 'zb', 'yb'], type='str'), size=dict(type='int'), segment_size_kb=dict(default=128, choices=[8, 16, 32, 64, 128, 256, 512], type='int'), ssd_cache_enabled=dict(type='bool'), # no default, leave existing setting alone data_assurance_enabled=dict(default=False, type='bool'), thin_provision=dict(default=False, type='bool'), thin_volume_repo_size=dict(type='int'), thin_volume_max_repo_size=dict(type='int'), # TODO: add cache, owning controller support, thin expansion policy, etc log_path=dict(type='str'), api_url=dict(type='str'), api_username=dict(type='str'), api_password=dict(type='str'), validate_certs=dict(type='bool'), )) self.module = AnsibleModule(argument_spec=argument_spec, required_if=[ ('state', 'present', ['storage_pool_name', 'size']), ('thin_provision', 'true', ['thin_volume_repo_size']) ], supports_check_mode=True) p = self.module.params log_path = p['log_path'] # logging setup self._logger = logging.getLogger(self.__class__.__name__) self.debug = self._logger.debug if log_path: logging.basicConfig(level=logging.DEBUG, filename=log_path) self.state = p['state'] self.ssid = p['ssid'] self.name = p['name'] self.storage_pool_name = p['storage_pool_name'] self.size_unit = p['size_unit'] self.size = p['size'] self.segment_size_kb = p['segment_size_kb'] self.ssd_cache_enabled = p['ssd_cache_enabled'] self.data_assurance_enabled = p['data_assurance_enabled'] self.thin_provision = p['thin_provision'] self.thin_volume_repo_size = p['thin_volume_repo_size'] self.thin_volume_max_repo_size = p['thin_volume_max_repo_size'] if not self.thin_volume_max_repo_size: self.thin_volume_max_repo_size = self.size self.validate_certs = p['validate_certs'] try: self.api_usr = p['api_username'] self.api_pwd = p['api_password'] self.api_url = p['api_url'] except KeyError: self.module.fail_json(msg="You must pass in api_username " "and api_password and api_url to the module.")