def _generate_retry_callback(retry_action):
        '''returns a Retry callback function for plugins'''
        dummy = HashiVaultModule(argument_spec=argspec)
        original = dummy._generate_retry_callback(retry_action)

        def _on_retry(retry_obj):
            if retry_obj.total > 0:
                this['_retry_count'] += 1

            original(retry_obj)

        return _on_retry
def run_module():
    argspec = HashiVaultModule.generate_argspec(
        # we override this from the shared argspec in order to turn off no_log
        # otherwise we would not be able to return the input token value
        token=dict(type='str', no_log=False, default=None)
    )

    module = HashiVaultModule(
        argument_spec=argspec,
        supports_check_mode=True
    )

    # a login is technically a write operation, using storage and resources
    changed = True
    auth_method = module.params.get('auth_method')

    if auth_method == 'none':
        module.fail_json(msg="The 'none' auth method is not valid for this module.")

    if auth_method == 'token':
        # with the token auth method, we don't actually perform a login operation
        # nor change the state of Vault; it's read-only (to lookup the token's info)
        changed = False

    module.connection_options.process_connection_options()
    client_args = module.connection_options.get_hvac_connection_options()
    client = module.helper.get_vault_client(**client_args)

    try:
        module.authenticator.validate()
        if module.check_mode:
            response = {'auth': {'client_token': None}}
        else:
            response = module.authenticator.authenticate(client)
    except (NotImplementedError, HashiVaultValueError) as e:
        module.fail_json(msg=to_native(e), exception=traceback.format_exc())

    module.exit_json(changed=changed, login=response)
def run_module():
    argspec = HashiVaultModule.generate_argspec(
        want_exception=dict(type='bool'), )

    strip_no_log(argspec)

    module = HashiVaultModule(argument_spec=argspec, supports_check_mode=False)

    options = module.adapter

    module.connection_options.process_connection_options()
    client_args = module.connection_options.get_hvac_connection_options()
    client = module.helper.get_vault_client(**client_args)

    err = msg = response = None
    try:
        try:
            module.authenticator.validate()
            response = module.authenticator.authenticate(client)
        except NotImplementedError as e:
            module.fail_json(msg=str(e), exception=e)
    except Exception as e:
        msg = str(e)
        if options.get_option('want_exception'):
            err = dictify(e)
        else:
            module.fail_json(msg=msg, exception=e)

    rob = {'login': response, 'failed': False, 'inner': {'failed': False}}

    if err is not None:
        rob['inner']['failed'] = True
        rob['exception'] = err
        rob['msg'] = msg

    module.exit_json(**rob)
def run_module():
    argspec = HashiVaultModule.generate_argspec(
        role_name=dict(type='str', required=True),
        common_name=dict(type='str', required=True),
        alt_names=dict(type='list', elements='str', required=False,
                       default=[]),
        ip_sans=dict(type='list', elements='str', required=False, default=[]),
        uri_sans=dict(type='list', elements='str', required=False, default=[]),
        other_sans=dict(type='list',
                        elements='str',
                        required=False,
                        default=[]),
        ttl=dict(type='str', required=False, default=None),
        format=dict(type='str',
                    required=False,
                    choices=['pem', 'der', 'pem_bundle'],
                    default='pem'),
        private_key_format=dict(type='str',
                                required=False,
                                choices=['der', 'pkcs8'],
                                default='der'),
        exclude_cn_from_sans=dict(type='bool', required=False, default=False),
        engine_mount_point=dict(type='str', required=False))

    module = HashiVaultModule(argument_spec=argspec, supports_check_mode=True)

    if not HAS_HVAC:
        module.fail_json(msg=missing_required_lib('hvac'),
                         exception=HVAC_IMPORT_ERROR)

    role_name = module.params.get('role_name')
    common_name = module.params.get('common_name')
    engine_mount_point = module.params.get(
        'engine_mount_point') or DEFAULT_MOUNT_POINT

    extra_params = {
        'alt_names': ','.join(module.params.get('alt_names')),
        'ip_sans': ','.join(module.params.get('ip_sans')),
        'uri_sans': ','.join(module.params.get('uri_sans')),
        'other_sans': ','.join(module.params.get('other_sans')),
        'ttl': module.params.get('ttl'),
        'format': module.params.get('format'),
        'private_key_format': module.params.get('private_key_format'),
        'exclude_cn_from_sans': module.params.get('exclude_cn_from_sans')
    }

    module.connection_options.process_connection_options()
    client_args = module.connection_options.get_hvac_connection_options()
    client = module.helper.get_vault_client(**client_args)

    try:
        module.authenticator.validate()
        module.authenticator.authenticate(client)
    except (NotImplementedError, HashiVaultValueError) as e:
        module.fail_json(msg=to_native(e), exception=traceback.format_exc())

    try:
        if module.check_mode:
            data = {}
        else:
            data = client.secrets.pki.generate_certificate(
                name=role_name,
                common_name=common_name,
                extra_params=extra_params,
                mount_point=engine_mount_point)
    except hvac.exceptions.VaultError as e:
        module.fail_json(msg=to_native(e), exception=traceback.format_exc())

    # generate_certificate is a write operation which always return a new certificate
    module.exit_json(changed=True, data=data)
def run_module():
    argspec = HashiVaultModule.generate_argspec(
        orphan=dict(type='bool', default=False),
        no_parent=dict(type='bool'),
        no_default_policy=dict(type='bool'),
        policies=dict(type='list', elements='str'),
        id=dict(type='str'),
        role_name=dict(type='str'),
        meta=dict(type='dict'),
        renewable=dict(type='bool'),
        ttl=dict(type='str'),
        type=dict(type='str', choices=['batch', 'service']),
        explicit_max_ttl=dict(type='str'),
        display_name=dict(type='str'),
        num_uses=dict(type='int'),
        period=dict(type='str'),
        entity_alias=dict(type='str'),
        wrap_ttl=dict(type='str'),
    )

    module = HashiVaultModule(argument_spec=argspec, supports_check_mode=True)

    module.connection_options.process_connection_options()
    client_args = module.connection_options.get_hvac_connection_options()
    client = module.helper.get_vault_client(**client_args)

    try:
        module.authenticator.validate()
        module.authenticator.authenticate(client)
    except (NotImplementedError, HashiVaultValueError) as e:
        module.fail_json(msg=to_native(e), exception=traceback.format_exc())

    pass_thru_options = module.adapter.get_filled_options(
        *PASS_THRU_OPTION_NAMES)

    if module.adapter.get_option('orphan'):
        pass_thru_options['no_parent'] = True

    legacy_options = pass_thru_options.copy()

    for key in pass_thru_options.keys():
        if key in LEGACY_OPTION_TRANSLATION:
            legacy_options[
                LEGACY_OPTION_TRANSLATION[key]] = legacy_options.pop(key)

    # token creation is a write operation, using storage and resources
    changed = True
    response = None

    if module.check_mode:
        module.exit_json(changed=changed,
                         login={'auth': {
                             'client_token': None
                         }})

    if module.adapter.get_option('orphan'):
        # this method is deprecated, but it's the only way through hvac to get
        # at the /create-orphan endpoint at this time.
        # See: https://github.com/hvac/hvac/issues/758
        try:
            response = client.create_token(orphan=True, **legacy_options)
        except AttributeError:
            module.warn(
                "'create_token' method was not found. Attempting method that requires root privileges."
            )
        except Exception as e:
            module.fail_json(msg=to_native(e),
                             exception=traceback.format_exc())

    if response is None:
        try:
            response = client.auth.token.create(**pass_thru_options)
        except Exception as e:
            module.fail_json(msg=to_native(e),
                             exception=traceback.format_exc())

    module.exit_json(changed=changed, login=response)
Esempio n. 6
0
def run_module():
    argspec = HashiVaultModule.generate_argspec(
        engine_mount_point=dict(type='str', default='secret'),
        path=dict(type='str', required=True),
        version=dict(type='int'),
    )

    module = HashiVaultModule(argument_spec=argspec, supports_check_mode=True)

    if not HAS_HVAC:
        module.fail_json(msg=missing_required_lib('hvac'),
                         exception=HVAC_IMPORT_ERROR)

    engine_mount_point = module.params.get('engine_mount_point')
    path = module.params.get('path')
    version = module.params.get('version')

    module.connection_options.process_connection_options()
    client_args = module.connection_options.get_hvac_connection_options()
    client = module.helper.get_vault_client(**client_args)

    try:
        module.authenticator.validate()
        module.authenticator.authenticate(client)
    except (NotImplementedError, HashiVaultValueError) as e:
        module.fail_json(msg=to_native(e), exception=traceback.format_exc())

    try:
        raw = client.secrets.kv.v2.read_secret_version(
            path=path, version=version, mount_point=engine_mount_point)
    except hvac.exceptions.Forbidden as e:
        module.fail_json(msg="Forbidden: Permission Denied to path ['%s']." %
                         path,
                         exception=traceback.format_exc())
    except hvac.exceptions.InvalidPath as e:
        module.fail_json(
            msg=
            "Invalid or missing path ['%s'] with secret version '%s'. Check the path or secret version."
            % (path, version or 'latest'),
            exception=traceback.format_exc())

    data = raw['data']
    metadata = data['metadata']
    secret = data['data']
    module.exit_json(raw=raw, data=data, secret=secret, metadata=metadata)
Esempio n. 7
0
def run_module():
    argspec = HashiVaultModule.generate_argspec(
        engine_mount_point=dict(type='str', default='kv'),
        path=dict(type='str', required=True),
    )

    module = HashiVaultModule(argument_spec=argspec, supports_check_mode=True)

    if not HAS_HVAC:
        module.fail_json(msg=missing_required_lib('hvac'),
                         exception=HVAC_IMPORT_ERROR)

    engine_mount_point = module.params.get('engine_mount_point')
    path = module.params.get('path')

    module.connection_options.process_connection_options()
    client_args = module.connection_options.get_hvac_connection_options()
    client = module.helper.get_vault_client(**client_args)

    try:
        module.authenticator.validate()
        module.authenticator.authenticate(client)
    except (NotImplementedError, HashiVaultValueError) as e:
        module.fail_json(msg=to_native(e), exception=traceback.format_exc())

    try:
        raw = client.secrets.kv.v1.read_secret(path=path,
                                               mount_point=engine_mount_point)
    except hvac.exceptions.Forbidden as e:
        module.fail_json(msg="Forbidden: Permission Denied to path ['%s']." %
                         path,
                         exception=traceback.format_exc())
    except hvac.exceptions.InvalidPath as e:
        if 'Invalid path for a versioned K/V secrets engine' in to_native(e):
            msg = "Invalid path for a versioned K/V secrets engine ['%s']. If this is a KV version 2 path, use community.hashi_vault.vault_kv2_get."
        else:
            msg = "Invalid or missing path ['%s']."

        module.fail_json(msg=msg % (path, ), exception=traceback.format_exc())

    metadata = raw.copy()
    data = metadata.pop('data')
    module.exit_json(raw=raw, data=data, secret=data, metadata=metadata)
Esempio n. 8
0
def run_module():
    argspec = HashiVaultModule.generate_argspec(
        path=dict(type='str', required=True),
        data=dict(type='dict', required=False, default={}),
        wrap_ttl=dict(type='str'),
    )

    module = HashiVaultModule(argument_spec=argspec, supports_check_mode=True)

    if not HAS_HVAC:
        module.fail_json(msg=missing_required_lib('hvac'),
                         exception=HVAC_IMPORT_ERROR)

    path = module.params.get('path')
    data = module.params.get('data')
    wrap_ttl = module.params.get('wrap_ttl')

    module.connection_options.process_connection_options()
    client_args = module.connection_options.get_hvac_connection_options()
    client = module.helper.get_vault_client(**client_args)

    try:
        module.authenticator.validate()
        module.authenticator.authenticate(client)
    except (NotImplementedError, HashiVaultValueError) as e:
        module.fail_json(msg=to_native(e), exception=traceback.format_exc())

    try:
        if module.check_mode:
            response = {}
        else:
            response = client.write(path=path, wrap_ttl=wrap_ttl, **data)
    except hvac.exceptions.Forbidden:
        module.fail_json(msg="Forbidden: Permission Denied to path '%s'." %
                         path,
                         exception=traceback.format_exc())
    except hvac.exceptions.InvalidPath:
        module.fail_json(msg="The path '%s' doesn't seem to exist." % path,
                         exception=traceback.format_exc())
    except hvac.exceptions.InternalServerError as e:
        module.fail_json(msg="Internal Server Error: %s" % to_native(e),
                         exception=traceback.format_exc())

    # https://github.com/hvac/hvac/issues/797
    # HVAC returns a raw response object when the body is not JSON.
    # That includes 204 responses, which are successful with no body.
    # So we will try to detect that and a act accordingly.
    # A better way may be to implement our own adapter for this
    # collection, but it's a little premature to do that.
    if hasattr(response, 'json') and callable(response.json):
        if response.status_code == 204:
            output = {}
        else:
            module.warn(
                'Vault returned status code %i and an unparsable body.' %
                response.status_code)
            output = response.content
    else:
        output = response

    module.exit_json(changed=True, data=output)
Esempio n. 9
0
def run_module():
    argspec = HashiVaultModule.generate_argspec(
        path=dict(type='str', required=True),
    )

    module = HashiVaultModule(
        argument_spec=argspec,
        supports_check_mode=True
    )

    if not HAS_HVAC:
        module.fail_json(
            msg=missing_required_lib('hvac'),
            exception=HVAC_IMPORT_ERROR
        )

    path = module.params.get('path')

    module.connection_options.process_connection_options()
    client_args = module.connection_options.get_hvac_connection_options()
    client = module.helper.get_vault_client(**client_args)

    try:
        module.authenticator.validate()
        module.authenticator.authenticate(client)
    except (NotImplementedError, HashiVaultValueError) as e:
        module.fail_json(msg=to_native(e), exception=traceback.format_exc())

    try:
        data = client.read(path)
    except hvac.exceptions.Forbidden as e:
        module.fail_json(msg="Forbidden: Permission Denied to path '%s'." % path, exception=traceback.format_exc())

    if data is None:
        module.fail_json(msg="The path '%s' doesn't seem to exist." % path)

    module.exit_json(data=data)
def run_module():
    this = dict(_retry_count=0)

    argspec = HashiVaultModule.generate_argspec(
        want_client=dict(type='bool'),
        want_args=dict(type='bool'),
        want_exception=dict(type='bool'),
    )

    def _generate_retry_callback(retry_action):
        '''returns a Retry callback function for plugins'''
        dummy = HashiVaultModule(argument_spec=argspec)
        original = dummy._generate_retry_callback(retry_action)

        def _on_retry(retry_obj):
            if retry_obj.total > 0:
                this['_retry_count'] += 1

            original(retry_obj)

        return _on_retry

    module = HashiVaultModule(
        hashi_vault_custom_retry_callback=_generate_retry_callback,
        argument_spec=argspec,
        supports_check_mode=False)

    options = module.adapter
    err = status = msg = None

    module.connection_options.process_connection_options()
    client_args = module.connection_options.get_hvac_connection_options()
    client = module.helper.get_vault_client(**client_args)

    try:
        status = client.sys.read_health_status(method='GET')
    except Exception as e:
        if options.get_option_default('want_exception'):
            err = dictify(e)
            msg = str(e)
        else:
            raise

    rob = {
        'retries': this['_retry_count'],
        'status': status,
        'failed': False,
        'inner': {
            'failed': False
        }
    }

    if options.get_option_default('want_client'):
        rob['client'] = dictify(client)

    if options.get_option_default('want_args'):
        rob['args'] = dictify(client_args)

    if err is not None:
        rob['inner']['failed'] = True
        rob['exception'] = err
        rob['msg'] = msg

    module.exit_json(**rob)