def hashivault_k8s_auth_config(module): params = module.params client = hashivault_auth_client(params) mount_point = params.get('mount_point').strip('/') desired_state = dict() desired_state['kubernetes_host'] = params.get('kubernetes_host') desired_state['token_reviewer_jwt'] = params.get('token_reviewer_jwt') desired_state['kubernetes_ca_cert'] = params.get('kubernetes_ca_cert') desired_state['pem_keys'] = params.get('pem_keys') if params.get('issuer'): desired_state['issuer'] = params.get('issuer') desired_state['mount_point'] = mount_point keys_updated = desired_state.keys() try: current_state = client.auth.kubernetes.read_config( mount_point=mount_point) keys_updated = get_keys_updated(current_state, desired_state) if not keys_updated: return {'changed': False} except InvalidPath: pass if not module.check_mode: client.auth.kubernetes.configure(**desired_state) return {'changed': True, 'keys_updated': keys_updated}
def hashivault_consul_secret_engine_config(module): params = module.params client = hashivault_auth_client(params) mount_point = params.get('mount_point').strip('/') consul_address = params.get('consul_address') scheme = params.get('scheme') token = params.get('consul_token') if (mount_point + "/") not in client.sys.list_mounted_secrets_engines()['data']: return { 'failed': True, 'msg': 'Consul secret engine is not enabled', 'rc': 1 } if module.check_mode: return {'changed': True} response = client.secrets.consul.configure_access(consul_address, token, scheme=scheme, mount_point=mount_point) if response.ok: return {'changed': True} return {'failed': True, 'msg': response.text}
def hashivault_token_create(params): client = hashivault_auth_client(params) role = params.get('role') token_id = params.get('id') policies = params.get('policies') metadata = params.get('metadata') no_parent = params.get('no_parent') lease = params.get('lease') display_name = params.get('display_name') num_uses = params.get('num_uses') no_default_policy = params.get('no_default_policy') ttl = params.get('ttl') wrap_ttl = params.get('wrap_ttl') orphan = params.get('orphan') renewable = params.get('renewable') period = params.get('period') explicit_max_ttl = params.get('explicit_max_ttl') token = client.create_token(role=role, token_id=token_id, policies=policies, meta=metadata, no_parent=no_parent, lease=lease, display_name=display_name, num_uses=num_uses, no_default_policy=no_default_policy, ttl=ttl, wrap_ttl=wrap_ttl, orphan=orphan, renewable=renewable, explicit_max_ttl=explicit_max_ttl, period=period) return {'changed': True, 'token': token}
def hashivault_aws_auth_role_create(params): state = params.get('state') name = params.get('name').strip('/') mount_point = params.get('mount_point').strip('/') desired_state = { 'auth_type': params.get('auth_type'), 'resolve_aws_unique_ids': params.get('resolve_aws_unique_ids'), 'bound_ami_id': params.get('bound_ami_id'), 'bound_account_id': params.get('bound_account_id'), 'bound_region': params.get('bound_region'), 'bound_vpc_id': params.get('bound_vpc_id'), 'bound_subnet_id': params.get('bound_subnet_id'), 'bound_iam_role_arn': params.get('bound_iam_role_arn'), 'bound_iam_instance_profile_arn': params.get('bound_iam_instance_profile_arn'), 'bound_ec2_instance_id': params.get('bound_ec2_instance_id'), 'role_tag': params.get('role_tag'), 'bound_iam_principal_arn': params.get('bound_iam_principal_arn'), 'inferred_entity_type': params.get('inferred_entity_type'), 'inferred_aws_region': params.get('inferred_aws_region'), 'ttl': params.get('ttl'), 'max_ttl': params.get('max_ttl'), 'period': params.get('period'), 'policies': params.get('policies'), 'allow_instance_migration': params.get('allow_instance_migration'), 'disallow_reauthentication': params.get('disallow_reauthentication'), } client = hashivault_auth_client(params) if not name: name = mount_point if state == 'present': client.auth.aws.create_role(name, mount_point=mount_point, **desired_state) return {'changed': True} client.auth.aws.delete_role(name, mount_point) return {'changed': True}
def hashivault_pki_cert_issue(module): params = module.params client = hashivault_auth_client(params) role = params.get('role').strip('/') common_name = params.get('common_name') extra_params = params.get('extra_params') mount_point = params.get('mount_point').strip('/') # check if engine is enabled _, err = check_secrets_engines(module, client) if err: return err if not check_pki_role(name=role, mount_point=mount_point, client=client): return { 'failed': True, 'rc': 1, 'msg': 'role not found or permission denied' } result = {"changed": False, "rc": 0} try: result['data'] = client.secrets.pki.generate_certificate( name=role, common_name=common_name, extra_params=extra_params, mount_point=mount_point).get('data') except Exception as e: result['rc'] = 1 result['failed'] = True result['msg'] = u"Exception: " + str(e) return result
def hashivault_secret_engine(module): params = module.params client = hashivault_auth_client(params) name = params.get('name') state = params.get('state') current_state = dict() exists = False changed = False try: # does the ns exist already? current_state = client.sys.list_namespaces()['data']['keys'] if (name + '/') in current_state: exists = True except Exception: # doesnt exist pass # doesnt exist and should or does exist and shouldnt if (exists and state == 'absent') or (not exists and state == 'present'): changed = True # create if changed and not exists and state == 'present' and not module.check_mode: client.sys.create_namespace(path=name) # delete elif changed and (state == 'absent' or state == 'disabled') and not module.check_mode: client.sys.delete_namespace(path=name) return {'changed': changed}
def hashivault_k8s_auth_config(module): params = module.params client = hashivault_auth_client(params) mount_point = params.get('mount_point') if mount_point[-1]: mount_point = mount_point.strip('/') desired_state = dict() desired_state['kubernetes_host'] = params.get('kubernetes_host') desired_state['token_reviewer_jwt'] = params.get('token_reviewer_jwt') desired_state['kubernetes_ca_cert'] = params.get('kubernetes_ca_cert') desired_state['mount_point'] = mount_point # check if engine is enabled try: if (mount_point + "/") not in client.sys.list_auth_methods(): return { 'failed': True, 'msg': (mount_point + ' auth metod not enabled'), 'rc': 1 } except: return { 'failed': True, 'msg': (mount_point + ' error getting auth method'), 'rc': 1 } if not module.check_mode: client.auth.kubernetes.configure(**desired_state) return {'changed': True}
def hashivault_pki_ca_set(module): params = module.params client = hashivault_auth_client(params) mount_point = params.get('mount_point').strip('/') pem_bundle = params.get('pem_bundle') # check if engine is enabled changed, err = check_secrets_engines(module, client) if err: return err result = {'changed': changed} if module.check_mode: return result data = client.secrets.pki.submit_ca_information(pem_bundle=pem_bundle, mount_point=mount_point) if data: from requests.models import Response if isinstance(data, Response): result['data'] = data.text else: result['data'] = data return result
def hashivault_userpass(params): client = hashivault_auth_client(params) state = params.get('state') name = params.get('name') password = params.get('pass') password_update = params.get('pass_update') policies = params.get('policies') token_bound_cidrs = params.get('token_bound_cidrs') mount_point = params.get('mount_point') if state == 'present': try: user_details = client.read_userpass(name, mount_point=mount_point) except Exception: if password is not None: client.create_userpass(name, password, policies, token_bound_cidrs=token_bound_cidrs, mount_point=mount_point) return {'changed': True} else: return {'failed': True, 'msg': 'pass must be provided for new users'} else: return hashivault_userpass_update(client, user_details, user_name=name, user_pass=password, user_pass_update=password_update, user_policies=policies, mount_point=mount_point, token_bound_cidrs=token_bound_cidrs) elif state == 'absent': try: client.read_userpass(name, mount_point=mount_point) except Exception: return {'changed': False} else: client.delete_userpass(name, mount_point=mount_point) return {'changed': True} else: return {'failed': True, 'msg': 'Unkown state type'}
def hashivault_list(params): result = {"changed": False, "rc": 0} client = hashivault_auth_client(params) version = params.get('version') mount_point = params.get('mount_point') secret = params.get('secret') if secret.startswith('/'): secret = secret.lstrip('/') listo = secret.split('/') if listo: mount_point = next(iter(listo), mount_point) secret = '/'.join(listo[1:]) # for backwards compatibiltiy with old hashivault_list module if secret.startswith('metadata/'): version = 2 secret = secret.lstrip('metadata/') response = None with warnings.catch_warnings(): warnings.simplefilter("ignore") try: if version == 2: response = client.secrets.kv.v2.list_secrets( path=secret, mount_point=mount_point) else: response = client.secrets.kv.v1.list_secrets( path=secret, mount_point=mount_point) except Exception as e: if response is None: response = {} else: return {'failed': True, 'msg': str(e)} result['secrets'] = response.get('data', {}).get('keys', []) return result
def hashivault_seal(params): client = hashivault_auth_client(params) if not client.sys.is_sealed(): status = client.sys.seal().ok return {'status': status, 'changed': True} else: return {'changed': False}
def hashivault_policy(params): client = hashivault_auth_client(params) state = params.get('state') name = params.get('name') if state == 'present': rules_file = params.get('rules_file') if rules_file: try: rules = open(rules_file, 'r').read() except Exception as e: return { 'changed': False, 'failed': True, 'msg': 'Error opening rules file <%s>: %s' % (rules_file, str(e)) } else: rules = params.get('rules') current = client.get_policy(name) if current == rules: return {'changed': False} client.sys.create_or_update_policy(name, rules) return {'changed': True} current_policies = client.sys.list_policies() if isinstance(current_policies, dict): current_policies = current_policies.get('data', current_policies) current_policies = current_policies.get('policies', current_policies) if name not in current_policies: return {'changed': False} client.sys.delete_policy(name) return {'changed': True}
def hashivault_pki_url(module): params = module.params client = hashivault_auth_client(params) mount_point = params.get('mount_point').strip('/') desired_state = { 'issuing_certificates': params.get('issuing_certificates'), 'crl_distribution_points': params.get('crl_distribution_points'), 'ocsp_servers': params.get('ocsp_servers') } # check if engine is enabled changed, err = check_secrets_engines(module, client) if err: return err # check if config exists current_state = {} try: current_state = client.secrets.pki.read_urls(mount_point=mount_point).get('data') except Exception: # not configured yet. changed = True # compare current_state to desired_state if not changed: changed = not compare_state(desired_state, current_state) # make the changes! if changed and not module.check_mode: client.secrets.pki.set_urls(mount_point=mount_point, params=desired_state) return {'changed': changed}
def hashivault_userpass(params): client = hashivault_auth_client(params) state = params.get('state') name = params.get('name') password = params.get('pass') password_update = params.get('pass_update') policies = params.get('policies') mount_point = params.get('mount_point') if state == 'present': try: user_details = client.read_userpass(name, mount_point=mount_point) except Exception: if password is not None: client.create_userpass(name, password, policies) return {'changed': True} else: return {'failed': True, 'msg': 'pass must be provided for new users'} else: return hashivault_userpass_update(client, user_details, user_name=name, user_pass=password, user_pass_update=password_update, user_policies=policies, mount_point=mount_point) elif state == 'absent': try: client.read_userpass(name, mount_point=mount_point) except Exception: return {'changed': False} else: client.delete_userpass(name, mount_point=mount_point) return {'changed': True} else: return {'failed': True, 'msg': 'Unkown state type'}
def hashivault_seal(params): client = hashivault_auth_client(params) if not client.sys.is_sealed(): status = client.sys.seal().ok return {'status': status, 'changed': True} else: return {'changed': False}
def hashivault_approle_role_secret_accessor_get(params): name = params.get('name') accessor = params.get('accessor') client = hashivault_auth_client(params) return { 'secret': client.get_role_secret_id_accessor(name, accessor)['data'] }
def hashivault_policy_list(params): client = hashivault_auth_client(params) current_policies = client.sys.list_policies() if isinstance(current_policies, dict): current_policies = current_policies.get('data', current_policies) current_policies = current_policies.get('policies', current_policies) return {'policies': current_policies}
def hashivault_auth_method(module): params = module.params client = hashivault_auth_client(params) method_type = params.get('method_type') description = params.get('description') mount_point = params.get('mount_point') config = params.get('config') state = params.get('state') exists = False changed = False if mount_point == None: mount_point = method_type auth_methods = client.sys.list_auth_methods() path = (mount_point or method_type) + u"/" # Is auth method enabled already? if path in auth_methods['data'].keys(): exists = True # if its off and we want it on if (state == 'enabled' or state == 'enable') and exists == False: changed = True # if its on and we want it off elif (state == 'disabled' or state == 'disable') and exists == True: changed = True # its on, we want it on, need to check current config vs desired if not changed and exists and (state == 'enabled' or state == 'enable'): current_state = client.sys.read_auth_method_tuning(path=mount_point) if 'default_lease_ttl' not in config: config['default_lease_ttl'] = DEFAULT_TTL if 'max_lease_ttl' not in config: config['max_lease_ttl'] = DEFAULT_TTL if 'force_no_cache' not in config: config['force_no_cache'] = False if 'token_type' not in config: config['token_type'] = 'default-service' if current_state['data'] != config: changed = True # brand new if changed and not exists and not module.check_mode and ( state == 'enabled' or state == 'enable'): client.sys.enable_auth_method(method_type, description=description, path=mount_point, config=config) # delete existing if changed and not module.check_mode and (state == 'disabled' or state == 'disable'): client.sys.disable_auth_method(path=mount_point) # update existing if changed and exists and not module.check_mode and (state == 'enabled' or state == 'enable'): client.sys.tune_auth_method(description=description, path=mount_point, **config) return {'changed': changed}
def hashivault_delete(params): result = {"changed": False, "rc": 0} client = hashivault_auth_client(params) version = params.get('version') mount_point = params.get('mount_point') secret = params.get('secret') if secret.startswith('/'): secret = secret.lstrip('/') mount_point = '' if mount_point: secret_path = '%s/%s' % (mount_point, secret) else: secret_path = secret with warnings.catch_warnings(): warnings.simplefilter("ignore") returned_data = None try: if version == 2: returned_data = client.secrets.kv.v2.delete_latest_version_of_secret(secret, mount_point=mount_point) else: returned_data = client.delete(secret_path) except InvalidPath: read_data = None except Exception as e: result['rc'] = 1 result['failed'] = True error_string = "%s(%s)" % (e.__class__.__name__, e) result['msg'] = u"Error %s deleting %s" % (error_string, secret_path) return result if returned_data: result['data'] = returned_data.text result['msg'] = u"Secret %s deleted" % secret_path result['changed'] = True return result
def hashivault_delete(params): result = {"changed": False, "rc": 0} client = hashivault_auth_client(params) version = params.get('version') mount_point = params.get('mount_point') secret = params.get('secret') if secret.startswith('/'): secret = secret.lstrip('/') mount_point = '' if mount_point: secret_path = '%s/%s' % (mount_point, secret) else: secret_path = secret with warnings.catch_warnings(): warnings.simplefilter("ignore") returned_data = None try: if version == 2: returned_data = client.secrets.kv.v2.delete_latest_version_of_secret(secret, mount_point=mount_point) else: returned_data = client.delete(secret_path) except InvalidPath: pass except Exception as e: result['rc'] = 1 result['failed'] = True error_string = "%s(%s)" % (e.__class__.__name__, e) result['msg'] = u"Error %s deleting %s" % (error_string, secret_path) return result if returned_data: result['data'] = returned_data.text result['msg'] = u"Secret %s deleted" % secret_path result['changed'] = True return result
def hashivault_pki_url_get(module): params = module.params client = hashivault_auth_client(params) mount_point = params.get('mount_point').strip('/') # check if engine is enabled _, err = check_secrets_engines(module, client) if err: return err result = {"changed": False, "rc": 0} from hvac.exceptions import InvalidPath try: result['data'] = client.secrets.pki.read_urls( mount_point=mount_point).get('data') except InvalidPath: result['rc'] = 1 result['failed'] = True result['msg'] = u"URLs must be configured before beeng read" except Exception as e: result['rc'] = 1 result['failed'] = True result['msg'] = u"Exception: " + str(e) return result
def hashivault_approle_role_create(params): args = [ 'mount_point', 'bind_secret_id', 'bound_cidr_list', 'secret_id_num_uses', 'secret_id_ttl', 'token_num_uses', 'token_ttl', 'token_max_ttl', 'period', 'enable_local_secret_ids', ] name = params.get('name') policies = params.get('policies') client = hashivault_auth_client(params) kwargs = { 'policies': policies, } for arg in args: value = params.get(arg) if value is not None: kwargs[arg] = value client.create_role(name, **kwargs) return {'changed': True}
def hashivault_db_secret_engine_config(module): params = module.params client = hashivault_auth_client(params) config_file = params.get('config_file') mount_point = params.get('mount_point').strip('/') state = params.get('state') name = params.get('name') desired_state = dict() # if config_file is set value from file # else set from passed args if config_file: desired_state = json.loads(open(params.get('config_file'), 'r').read()) else: desired_state['plugin_name'] = params.get('plugin_name') desired_state['allowed_roles'] = params.get('allowed_roles') desired_state['verify_connection'] = params.get('verify_connection') desired_state['root_credentials_rotate_statements'] = params.get('root_credentials_rotate_statements') connection_details = params.get('connection_details') desired_state.update(connection_details) del connection_details["password"] # not a required param but must ensure a value for current vs desired object comparison if 'root_credentials_rotate_statements' not in desired_state: desired_state['root_credentials_rotate_statements'] = [] exists = False current_state = {} try: current_state = client.secrets.database.read_connection(name=name) exists = True except Exception: # does not exist pass changed = False if exists: if state == 'absent': changed = True else: for k, v in current_state.get('data', {}).items(): # connection_url is passed as a nested item if k == 'connection_details': if v['username'] != desired_state['username']: changed = True if v['connection_url'] != desired_state['connection_url']: changed = True else: if v != desired_state[k]: changed = True elif state == 'present': changed = True # if configs dont match and checkmode is off, complete the change if changed and state == 'present' and not module.check_mode: client.secrets.database.configure(name=name, mount_point=mount_point, **desired_state) elif changed and state == 'absent' and not module.check_mode: client.secrets.database.delete_connection(name=name, mount_point=mount_point) return {'changed': changed}
def hashivault_policy_list(params): client = hashivault_auth_client(params) current_policies = client.sys.list_policies() if isinstance(current_policies, dict): current_policies = current_policies.get('data', current_policies) current_policies = current_policies.get('policies', current_policies) return {'policies': current_policies}
def hashivault_audit(params): client = hashivault_auth_client(params) device_type = params.get('device_type') description = params.get('description') options = params.get('options') path = params.get('path') state = params.get('state') if state in ['enabled', 'enable', 'present']: state = 'enabled' else: state = 'disabled' result = client.sys.list_enabled_audit_devices() backends = result.get('data', result) if not path: path = device_type + "/" if path[-1] != "/": path = path + "/" if state == 'enabled': if path in backends: return { 'changed': False, 'msg': 'Backend exists and Vault does not support update' } client.sys.enable_audit_device(device_type=device_type, description=description, options=options, path=path) elif state == 'disabled': if path not in backends: return {'changed': False, 'msg': 'Backend does not exist'} client.sys.disable_audit_device(path=path) return {'changed': True}
def hashivault_pki_crl(module): params = module.params client = hashivault_auth_client(params) mount_point = params.get('mount_point').strip('/') desired_state = { 'disable': params.get('disable'), 'expiry': params.get('expiry') } # compare current_state to desired_state from hvac.exceptions import InvalidPath try: current_state = client.secrets.pki.read_crl_configuration( mount_point=mount_point).get('data') changed = is_state_changed(desired_state, current_state) except InvalidPath: changed = True # make the changes! if changed and not module.check_mode: client.secrets.pki.set_crl_configuration(mount_point=mount_point, extra_params=desired_state) return {'changed': changed}
def hashivault_policy_set_from_file(module): params = module.params client = hashivault_auth_client(params) name = params.get('name') rules = open(params.get('rules_file'), 'r').read() changed = False exists = False current = str() # does policy exit try: current = client.get_policy(name) exists = True except: if module.check_mode: changed = True else: return { 'failed': True, 'msg': 'auth mount is not enabled', 'rc': 1 } # does current policy match desired if exists: if current != rules: changed = True if exists and changed and not module.check_mode: client.sys.create_or_update_policy(name, rules) return {'changed': changed}
def hashivault_identity_entity_create_or_update(params): client = hashivault_auth_client(params) entity_name = params.get('name') entity_id = params.get('id') entity_metadata = params.get('metadata') entity_disabled = params.get('disabled') entity_policies = params.get('policies') if entity_id is not None: try: entity_details = client.secrets.identity.read_entity(entity_id=entity_id) except Exception as e: return {'failed': True, 'msg': str(e)} return hashivault_identity_entity_update(entity_details['data'], client, entity_name, entity_id, entity_metadata, entity_disabled, entity_policies) elif entity_name is not None: try: entity_details = client.secrets.identity.read_entity_by_name(name=entity_name) except Exception: response = client.secrets.identity.create_or_update_entity_by_name( name=entity_name, metadata=entity_metadata, policies=entity_policies, disabled=entity_disabled ) return {'changed': True, 'data': response['data']} return hashivault_identity_entity_update(entity_details['data'], client, entity_name=entity_name, entity_id=entity_details['data']['id'], entity_metadata=entity_metadata, entity_disabled=entity_disabled, entity_policies=entity_policies) return {'failed': True, 'msg': "Either name or id must be provided"}
def hashivault_k8s_auth_config(module): params = module.params client = hashivault_auth_client(params) mount_point = params.get('mount_point').strip('/') desired_state = dict() desired_state['kubernetes_host'] = params.get('kubernetes_host') desired_state['token_reviewer_jwt'] = params.get('token_reviewer_jwt') desired_state['kubernetes_ca_cert'] = params.get('kubernetes_ca_cert') desired_state['pem_keys'] = params.get('pem_keys') if params.get('issuer'): desired_state['issuer'] = params.get('issuer') desired_state['mount_point'] = mount_point try: current_state = client.auth.kubernetes.read_config( mount_point=mount_point) except InvalidPath: current_state = {} ignore_list = [ 'mount_point', 'token_reviewer_jwt', ] keys_updated = get_keys_updated(desired_state, current_state, ignore_list) if 'pem_keys' in keys_updated: if current_state.get('pem_keys', []) == []: keys_updated.remove('pem_keys') if not keys_updated: return {'changed': False} if not module.check_mode: client.auth.kubernetes.configure(**desired_state) return {'changed': True, 'keys_updated': keys_updated}
def hashivault_pki_role(module): params = module.params client = hashivault_auth_client(params) name = params.get('name').strip('/') mount_point = params.get('mount_point').strip('/') state = params.get('state') role_file = params.get('role_file') config = params.get('config') desired_state = {} exists = False if role_file: import json desired_state = json.loads(open(role_file, 'r').read()) elif config: import yaml doc = yaml.safe_load(DOCUMENTATION) args = doc.get('options').get('config').get('suboptions').items() for key, value in args: arg = config.get(key) if arg is not None: try: desired_state[key] = normalize[value.get('type')](arg) except Exception: return { 'changed': False, 'failed': True, 'msg': 'config item \'{}\' has wrong data fromat'.format(key) } changed = False current_state = check_pki_role(name=name, mount_point=mount_point, client=client) if current_state: exists = True if (exists and state == 'absent') or (not exists and state == 'present'): changed = True # compare current_state to desired_state if exists and state == 'present' and not changed: changed = not compare_state(desired_state, current_state) # make the changes! if changed and state == 'present' and not module.check_mode: client.secrets.pki.create_or_update_role(name=name, mount_point=mount_point, extra_params=desired_state) elif changed and state == 'absent' and not module.check_mode: client.secrets.pki.delete_role(name=name, mount_point=mount_point) return {'changed': changed}
def hashivault_userpass_create(params): client = hashivault_auth_client(params) name = params.get('name') password = params.get('pass') policies = params.get('policies') mount_point = params.get('mount_point') client.create_userpass(name, password, policies, mount_point=mount_point) return {'changed': True}
def hashivault_userpass_create(params): client = hashivault_auth_client(params) name = params.get('name') password = params.get('pass') policies = params.get('policies') mount_point = params.get('mount_point') client.create_userpass(name, password, policies, mount_point=mount_point) return {'changed': True}
def hashivault_approle_role(module): params = module.params state = params.get('state') mount_point = params.get('mount_point') name = params.get('name') client = hashivault_auth_client(params) if state == 'present': args = [ 'policies', 'bind_secret_id', 'bound_cidr_list', 'secret_id_num_uses', 'secret_id_ttl', 'token_num_uses', 'token_ttl', 'token_max_ttl', 'period', 'enable_local_secret_ids', ] desired_state = {} for arg in args: value = params.get(arg) if value is not None: desired_state[arg] = value try: current_state = client.get_role(name, mount_point=mount_point) changed = False missing = [] for key in desired_state: if key in current_state: if current_state[key] != desired_state[key]: changed = True else: missing.append(key) if changed: if not module.check_mode: client.update_role(name, mount_point=mount_point, **desired_state) return {'changed': True, 'missing': missing} return {'changed': False, 'missing': missing} except Exception: if not module.check_mode: client.create_role(name, mount_point=mount_point, **desired_state) return {'changed': True} elif state == 'absent': if module.check_mode: try: client.get_role(name, mount_point=mount_point) except Exception: return {'changed': False} return {'changed': True} else: client.delete_role(name, mount_point=mount_point) return {'changed': True} return {'failed': True, 'msg': 'Unkown state value: {}'.format(state)}
def hashivault_approle_role_secret_create(module): params = module.params state = params.get('state') name = params.get('name') mount_point = params.get('mount_point') client = hashivault_auth_client(params) if state == 'present': custom_secret_id = params.get('secret_id') cidr_list = params.get('cidr_list') metadata = params.get('metadata') wrap_ttl = params.get('wrap_ttl') if custom_secret_id is not None: if module.check_mode: try: client.get_role_secret_id(name, custom_secret_id, mount_point=mount_point) except Exception: return {'changed': True} return {'changed': False} result = client.create_role_custom_secret_id( role_name=name, mount_point=mount_point, secret_id=custom_secret_id, meta=metadata, cidr_list=cidr_list, wrap_ttl=wrap_ttl) else: if module.check_mode: return {'changed': True} result = client.create_role_secret_id(role_name=name, mount_point=mount_point, meta=metadata, cidr_list=cidr_list, wrap_ttl=wrap_ttl) if wrap_ttl is None: response_key = 'data' else: response_key = 'wrap_info' return {'changed': True, response_key: result.get(response_key, {})} elif state == 'absent': secret = params.get('secret') if module.check_mode: try: client.get_role_secret_id(name, secret, mount_point=mount_point) except Exception: return {'changed': False} return {'changed': True} else: client.delete_role_secret_id(name, secret, mount_point=mount_point) return {'changed': True} else: return {'failed': True, 'msg': 'Unkown state value: {}'.format(state)}
def hashivault_oidc_auth_role(module): params = module.params mount_point = params.get('mount_point').strip('/') name = params.get('name').strip('/') state = params.get('state') client = hashivault_auth_client(params) parameters = [ 'allowed_redirect_uris', 'bound_audiences', 'bound_claims', 'bound_subject', 'claim_mappings', 'groups_claim', 'oidc_scopes', 'token_bound_cidrs', 'token_explicit_max_ttl', 'token_ttl', 'token_max_ttl', 'token_no_default_policy', 'token_policies', 'policies', 'token_type', 'user_claim', 'token_period', 'token_num_uses', 'clock_skew_leeway', 'expiration_leeway', 'not_before_leeway', ] desired_state = dict() for parameter in parameters: if params.get(parameter) is not None: desired_state[parameter] = params.get(parameter) desired_state['role_type'] = "oidc" desired_state['verbose_oidc_logging'] = False if not desired_state['token_policies'] and desired_state['policies']: desired_state['token_policies'] = desired_state['policies'] desired_state.pop('policies', None) desired_state['path'] = mount_point changed = False current_state = {} try: current_state = client.auth.oidc.read_role(name=name, path=mount_point)['data'] except Exception: changed = True for key in desired_state.keys(): current_value = current_state.get(key, None) if current_value is not None and current_value != desired_state[key]: changed = True break if changed and not module.check_mode: if not current_state and state == 'present': client.auth.oidc.create_role(name=name, **desired_state) elif current_state and state == 'absent': client.auth.oidc.delete_role(name=name) return {'changed': changed, 'old_state': current_state, 'new_state': desired_state}
def hashivault_token_renew(params): client = hashivault_auth_client(params) renew_token = params.get('renew_token') increment = params.get('increment') if renew_token is None: renew_token = params.get('token') wrap_ttl = params.get('wrap_ttl') renew = client.renew_token(token=renew_token, increment=increment, wrap_ttl=wrap_ttl) return {'changed': True, 'renew': renew}
def hashivault_policy_set_from_file(params): client = hashivault_auth_client(params) name = params.get('name') rules = open(params.get('rules_file'), 'r').read() current = client.get_policy(name) if current == rules: return {'changed': False} client.sys.create_or_update_policy(name, rules) return {'changed': True}
def hashivault_policy_set(params): client = hashivault_auth_client(params) name = params.get('name') rules = params.get('rules') current = client.get_policy(name) if current == rules: return {'changed': False} client.sys.create_or_update_policy(name, rules) return {'changed': True}
def hashivault_token_revoke(params): client = hashivault_auth_client(params) accessor = params.get('accessor') orphan = params.get('orphan') revoke_token = params.get('revoke_token') if revoke_token is None: revoke_token = params.get('token') revoke = client.revoke_token(token=revoke_token, orphan=orphan, accessor=accessor) return {'changed': True, 'revoke': revoke}
def hashivault_policy_get(params): name = params.get('name') client = hashivault_auth_client(params) policy = client.get_policy(name) if policy is None: result = {"changed": False, "rc": 1, "failed": True} result['msg'] = u"Policy \"%s\" does not exist." % name return result else: return {'rules': policy}
def hashivault_policy_delete(params): name = params.get('name') client = hashivault_auth_client(params) current_policies = client.sys.list_policies() if isinstance(current_policies, dict): current_policies = current_policies.get('data', current_policies) current_policies = current_policies.get('policies', current_policies) if name not in current_policies: return {'changed': False} client.sys.delete_policy(name) return {'changed': True}
def hashivault_auth_enable(params): client = hashivault_auth_client(params) name = params.get('name') description = params.get('description') mount_point = params.get('mount_point') backends = client.sys.list_auth_methods() path = (mount_point or name) + u"/" if path in backends: return {'changed': False} client.sys.enable_auth_method(name, description=description, path=mount_point) return {'changed': True}
def hashivault_secret_enable(params): client = hashivault_auth_client(params) name = params.get('name') backend = params.get('backend') description = params.get('description') config = params.get('config') options = params.get('options') secrets = client.sys.list_mounted_secrets_engines() secrets = secrets.get('data', secrets) path = name + "/" if path in secrets: return {'changed': False} client.sys.enable_secrets_engine(backend, description=description, path=name, config=config, options=options) return {'changed': True}
def hashivault_approle_role_secret_create(params): name = params.get('name') cidr_list = params.get('cidr_list') metadata = params.get('metadata') wrap_ttl = params.get('wrap_ttl') kwargs = {} if cidr_list is not None: kwargs['cidr_list'] = cidr_list if metadata is not None: kwargs['meta'] = metadata if wrap_ttl is not None: kwargs['wrap_ttl'] = wrap_ttl client = hashivault_auth_client(params) result = client.create_role_secret_id(name, **kwargs) return result['data']
def hashivault_list(params): result = {"changed": False, "rc": 0} client = hashivault_auth_client(params) secret = params.get('secret') if secret.startswith('/'): secret = secret.lstrip('/') else: secret = 'secret/' + secret with warnings.catch_warnings(): warnings.simplefilter("ignore") response = client.list(secret) if not response: response = {} result['secrets'] = response.get('data', {}).get('keys', []) return result
def hashivault_identity_entity_alias(params): client = hashivault_auth_client(params) alias_name = params.get('name') alias_id = params.get('alias_id') state = params.get('state') mount_accessor = params.get('mount_accessor') authtype = params.get('authtype') entity_name = params.get('entity_name') canonical_id = params.get('canonical_id') # Get mount_accessor if not provided if mount_accessor is None: auth_method_details = client.read(path="/sys/auth/") try: mount_accessor = auth_method_details['data'][authtype + "/"]['accessor'] except Exception: return {'failed': True, 'msg': 'Auth method %s not found. Use mount_accessor?' % authtype} # Get canonical_id if not provided if canonical_id is None: if entity_name is None: return {'failed': True, 'msg': 'Either canonical_id or entity_name must be provided'} else: try: entity_details = client.secrets.identity.read_entity_by_name( name=entity_name ) except Exception: return {'failed': True, 'msg': 'No entity with name %s' % entity_name} canonical_id = entity_details['data']['id'] if state == 'present': if alias_id is not None: return hashivault_identity_entity_alias_update(client, alias_id=alias_id, alias_name=alias_name, mount_accessor=mount_accessor, canonical_id=canonical_id) elif alias_name is not None: return hashivault_identity_entity_alias_create(client, alias_name=alias_name, mount_accessor=mount_accessor, canonical_id=canonical_id) else: return {'failed': True, 'msg': 'Either alias_id or name must be provided'} elif state == 'absent': return hashivault_identity_entity_alias_delete(client, alias_id=alias_id, alias_name=alias_name, mount_accessor=mount_accessor, canonical_id=canonical_id) return {'failed': True, 'msg': 'Unknown state'}
def hashivault_identity_entity_delete(params): client = hashivault_auth_client(params) entity_id = params.get('id') entity_name = params.get('name') if entity_id is not None: try: client.secrets.identity.read_entity(entity_id=entity_id) except Exception: return {'changed': False} client.secrets.identity.delete_entity(entity_id=entity_id) return {'changed': True} elif entity_name is not None: try: client.secrets.identity.read_entity_by_name(name=entity_name) except Exception: return {'changed': False} client.secrets.identity.delete_entity_by_name(name=entity_name) return {'changed': True} return {'failed': True, 'msg': "Either name or id must be provided"}
def hashivault_mount_tune(module): client = hashivault_auth_client(module.params) mount_point = module.params.get('mount_point') default_lease_ttl = module.params.get('default_lease_ttl') max_lease_ttl = module.params.get('max_lease_ttl') changed = False current_tuning = client.sys.read_mount_configuration(mount_point) current_tuning = current_tuning.get('data', current_tuning) current_default_lease_ttl = current_tuning.get('default_lease_ttl') current_max_lease_ttl = current_tuning.get('max_lease_ttl') if (current_default_lease_ttl != default_lease_ttl) or (current_max_lease_ttl != max_lease_ttl): changed = True if not module.check_mode: client.sys.tune_mount_configuration(mount_point, default_lease_ttl=default_lease_ttl, max_lease_ttl=max_lease_ttl) return {'changed': changed}
def hashivault_token_create(params): client = hashivault_auth_client(params) role = params.get('role') token_id = params.get('id') policies = params.get('policies') metadata = params.get('metadata') no_parent = params.get('no_parent') lease = params.get('lease') display_name = params.get('display_name') num_uses = params.get('num_uses') no_default_policy = params.get('no_default_policy') ttl = params.get('ttl') wrap_ttl = params.get('wrap_ttl') orphan = params.get('orphan') renewable = params.get('renewable') period = params.get('period') explicit_max_ttl = params.get('explicit_max_ttl') token = client.create_token( role=role, token_id=token_id, policies=policies, meta=metadata, no_parent=no_parent, lease=lease, display_name=display_name, num_uses=num_uses, no_default_policy=no_default_policy, ttl=ttl, wrap_ttl=wrap_ttl, orphan=orphan, renewable=renewable, explicit_max_ttl=explicit_max_ttl, period=period ) return {'changed': True, 'token': token}
def hashivault_aws_ec2_role_create(params): args = [ 'bound_ami_id', 'bound_vpc_id', 'inferred_entity_type', 'inferred_aws_region', 'bound_account_id', 'bound_iam_role_arn', 'bound_iam_instance_profile_arn', 'auth_type' 'bound_ec2_instance_id', 'allow_instance_migration', 'disallow_reauthentication', 'token_ttl', 'token_max_ttl', ] name = params.get('name') policies = params.get('policies') client = hashivault_auth_client(params) kwargs = { 'policies': policies, } for arg in args: value = params.get(arg) if value is not None: kwargs[arg] = value if 'aws/' not in client.sys.list_auth_methods().keys(): return {'failed': True, 'msg': 'aws auth backend is not enabled', 'rc': 1} try: if client.get_role(name, 'aws'): return {'changed': False} except InvalidPath: client.create_role(name, mount_point='aws', **kwargs) return {'changed': True}
def hashivault_approle_role_create(params): args = [ 'bind_secret_id', 'bound_cidr_list', 'secret_id_num_uses', 'secret_id_ttl', 'token_num_uses', 'token_ttl', 'token_max_ttl', 'period', 'enable_local_secret_ids', ] name = params.get('name') policies = params.get('policies') client = hashivault_auth_client(params) kwargs = { 'policies': policies, } for arg in args: value = params.get(arg) if value is not None: kwargs[arg] = value client.create_role(name, **kwargs) return {'changed': True}
def hashivault_userpass_delete(params): client = hashivault_auth_client(params) username = params.get('name') mount_point = params.get('mount_point') client.delete_userpass(username, mount_point=mount_point) return {'changed': True}
def hashivault_approle_role_secret_accessor_get(params): name = params.get('name') accessor = params.get('accessor') client = hashivault_auth_client(params) return {'secret': client.get_role_secret_id_accessor(name, accessor)['data']}
def hashivault_approle_role_secret_delete(params): name = params.get('name') secret = params.get('secret') client = hashivault_auth_client(params) client.delete_role_secret_id(name, secret) return {'changed': True}
def hashivault_secret_disable(params): client = hashivault_auth_client(params) name = params.get('name') client.sys.disable_secrets_engine(name) return {'changed': True}
def hashivault_approle_role_secret_get(params): name = params.get('name') secret = params.get('secret') client = hashivault_auth_client(params) return {'secret': client.get_role_secret_id(name, secret)['data']}
def hashivault_approle_role_get(params): name = params.get('name') client = hashivault_auth_client(params) return {'role': client.get_role(name)}
def hashivault_approle_role_list(params): client = hashivault_auth_client(params) roles = client.list_roles() roles = roles.get('data', {}).get('keys', []) return {'roles': roles}
def hashivault_audit_list(params): client = hashivault_auth_client(params) backends = client.sys.list_enabled_audit_devices() backends = backends.get('data', backends) return {'changed': True, 'backends': backends}
def hashivault_approle_role_secret_list(params): name = params.get('name') client = hashivault_auth_client(params) secrets = client.list_role_secrets(name) secrets = secrets.get('data', {}).get('keys', []) return {'secrets': secrets}