def fail_exit(module, e):
    if e.reason == "Unauthorized":
        raise AnsibleAuthenticationFailure(to_native(e.reason))
    elif e.body is not None:
        err = json.loads(str(e.body))
        raise AnsibleError(err["message"])
    else:
        return module.exit_json(failed=True, msg=to_native(e.reason))
Exemplo n.º 2
0
def check_type_dict(value):
    """Verify that value is a dict or convert it to a dict and return it.

    Raises TypeError if unable to convert to a dict

    :arg value: Dict or string to convert to a dict. Accepts 'k1=v2, k2=v2'.

    :returns: value converted to a dictionary
    """
    if isinstance(value, dict):
        return value

    if isinstance(value, string_types):
        if value.startswith("{"):
            try:
                return json.loads(value)
            except Exception:
                (result, exc) = safe_eval(value,
                                          dict(),
                                          include_exceptions=True)
                if exc is not None:
                    raise TypeError('unable to evaluate string as dictionary')
                return result
        elif '=' in value:
            fields = []
            field_buffer = []
            in_quote = False
            in_escape = False
            for c in value.strip():
                if in_escape:
                    field_buffer.append(c)
                    in_escape = False
                elif c == '\\':
                    in_escape = True
                elif not in_quote and c in ('\'', '"'):
                    in_quote = c
                elif in_quote and in_quote == c:
                    in_quote = False
                elif not in_quote and c in (',', ' '):
                    field = ''.join(field_buffer)
                    if field:
                        fields.append(field)
                    field_buffer = []
                else:
                    field_buffer.append(c)

            field = ''.join(field_buffer)
            if field:
                fields.append(field)
            return dict(x.split("=", 1) for x in fields)
        else:
            raise TypeError(
                "dictionary requested, could not parse JSON or key=value")

    raise TypeError('%s cannot be converted to a dict' % type(value))
def _create_flag(module, api_instance):
    # Variations can only be set at time of flag creation.
    if module.params["conftest"]["enabled"]:
        validate_params(module)

    if module.params["kind"] == "bool":
        variations = [
            launchdarkly_api.Variation(value=True),
            launchdarkly_api.Variation(value=False),
        ]
    elif module.params["kind"] == "json":
        # No easy way to check isinstance json
        variations = _build_variations(module)
    elif module.params["kind"] == "str":
        if not all(
                isinstance(item, string_types)
                for item in module.params["variations"]):
            module.exit_json(msg="Variations need to all be strings")
        variations = _build_variations(module)
    elif module.params["kind"] == "number":
        if not all(
                isinstance(item, int) for item in module.params["variations"]):
            module.exit_json(msg="Variations need to all be integers")
        variations = _build_variations(module)

    feature_flag_config = {
        "key": module.params["key"],
        "variations": variations,
        "temporary": module.params["temporary"],
        "name": module.params["name"],
    }

    try:
        response, status, headers = api_instance.post_feature_flag_with_http_info(
            module.params["project_key"], feature_flag_config)

    except ApiException as e:
        err = json.loads(str(e.body))
        if err["code"] == "key_exists":
            module.exit_json(msg="error: Key already exists")
        else:
            fail_exit(module, e)

    _configure_flag(module, api_instance, response)
    module.exit_json(msg="flag successfully created",
                     content=api_response.to_dict())
Exemplo n.º 4
0
def main():

    module = AnsibleModule(
        argument_spec=dict(
            sdk_key=dict(
                required=True,
                type="str",
                no_log=True,
                fallback=(env_fallback, ["LAUNCHDARKLY_SDK_KEY"]),
            ),
            overrides_flag=dict(type="list", elements="dict"),
            overrides_segment=dict(type="list", elem="dict"),
        )
    )

    if not HAS_LD:
        module.fail_json(
            msg=missing_required_lib("launchdarkly-server-sdk"), exception=LD_IMP_ERR
        )

    headers = {"Authorization": module.params["sdk_key"]}
    resp = open_url(
        "https://app.launchdarkly.com/sdk/latest-all", headers=headers, method="GET"
    )

    test_data = json.loads(resp.read())
    if module.params.get("overrides_flag"):
        for k, v in [
            (k, v) for x in module.params["overrides_flag"] for (k, v) in x.items()
        ]:
            if v not in test_data["flags"][k]["variations"]:
                raise AnsibleError("Override variation does not match flag variations")

            if "flagValues" in test_data.keys():
                test_data["flagValues"][k] = v
            else:
                test_data["flagValues"] = {}
                test_data["flagValues"][k] = v
            del test_data["flags"][k]

    module.exit_json(changed=True, content=test_data)