def main():
    argspec = hvault_argument_spec()
    argspec.update(
        dict(
            name=dict(required=True),
            state=dict(choices=['present', 'absent'], default='present'),
            policy=dict(type='raw'),
        ))

    module = AnsibleModule(
        supports_check_mode=True,
        argument_spec=argspec,
        required_if=[
            ['state', 'present', ['policy']],
        ],
    )

    client = HVaultClient(module.params, module)

    pol_path = 'sys/policies/acl/{0}'.format(module.params['name'])
    try:
        result = client.get(pol_path, fatal=False)
        result = result['data']
    except URLError:
        result = None

    if module.params['state'] == 'absent':
        if not result:
            module.exit_json(changed=False)
        if not module.check_mode:
            client.delete(pol_path)
        module.exit_json(changed=True)

    policy = module.params['policy']

    if not isinstance(policy, string_types):
        if not isinstance(policy, dict):
            module.fail_json(
                msg='policy must be either a dict or a string, got {0}'.format(
                    type(policy)))

        # allow people to write policies with less typing
        if 'path' not in policy:
            policy = {'path': policy}
        for key in policy['path']:
            if isinstance(policy['path'][key], list):
                policy['path'][key] = {'capabilities': policy['path'][key]}

        policy = jsonify(policy, indent=2, sort_keys=True)

    changed = False
    if not result or result['policy'] != policy:
        changed = True
        if not module.check_mode:
            client.put(pol_path, data={'policy': policy})
            result = client.get(pol_path)['data']

    module.exit_json(changed=changed, policy=result)
示例#2
0
def check_type_jsonarg(value):
    """Return a jsonified string. Sometimes the controller turns a json string
    into a dict/list so transform it back into json here

    Raises TypeError if unable to covert the value

    """
    if isinstance(value, (text_type, binary_type)):
        return value.strip()
    elif isinstance(value, (list, tuple, dict)):
        return jsonify(value)
    raise TypeError('%s cannot be converted to a json string' % type(value))
示例#3
0
    def _open_url(self, path, method, data=None, fatal=True):
        url = '{0}/v1/{1}'.format(self.params['vault_addr'], path)

        headers = {}
        if self.params.get('token'):
            headers['X-Vault-Token'] = self.params['token']
        if data:
            headers['Content-type'] = 'application/json'

        try:
            result = open_url(
                url,
                headers=headers,
                method=method,
                data=jsonify(data),
                timeout=self.params['timeout'],
                http_agent=self.params['http_agent'],
                use_proxy=self.params['use_proxy'],
                validate_certs=self.params['validate_certs'],
                client_cert=self.params['client_cert'],
                client_key=self.params['client_key'],
            ).read()
            if result:
                return json.loads(result)
            return None

        except HTTPError as e:
            if fatal and self._module:
                msg = 'Failed to {0} {1}: {2} (HTTP {3})'.format(
                    method, path, e.reason, e.code)
                result = {}
                try:
                    result = json.loads(e.read())
                except Exception:  # oop
                    pass
                failure = {
                    'msg': msg,
                    'headers': str(e.headers),
                    'result': result,
                }
                self._module.fail_json(**failure)
            raise

        except URLError as e:
            if fatal and self._module:
                self._module.fail_json(msg='Failed to {0} {1}: {2}'.format(
                    method, path, e.reason))
            raise
示例#4
0
    def exit_raw_json(module, **kwargs):
        """
        Print the raw parameters in JSON format, without masking.

        Due to Ansible filtering out values in the output that match values
        in variables which has `no_log` set, if a module need to return user
        defined dato to the controller, it cannot rely on
        AnsibleModule.exit_json, as there is a chance that a partial match may
        occur, masking the data returned.

        This method is a replacement for AnsibleModule.exit_json. It has
        nearly the same implementation as exit_json, but does not filter
        data. Beware that this data will be logged by Ansible, and if it
        contains sensible data, it will be appear in the logs.
        """
        module.do_cleanup_files()
        print(jsonify(kwargs))
        sys.exit(0)
def test_jsonify(test_input, expected):
    """Test for jsonify()."""
    assert jsonify(test_input) == expected