def _get_existing_variables(
        base_url: str,
        headers: Dict[str, str],
        workspace: Workspace,
        *,
        write_output: bool = False) -> Optional[Dict[str, Variable]]:
    """
    Fetches the variables for a given workspaces. This method will eagerly exit and return None if
    anything unexpected is encountered. This is done prophylactically as the ensuing update/create
    operations hinge on the successful completion of this method.

    :param base_url: A URL fragment onto which a path will be appended to construct the Terraform
                     API endpoint.
    :param headers: The headers to provide in the API HTTP request to fetch the variables.
    :param workspace: The workspace for which variables will be fetched.
    :param write_output: Whether to print a tabulated result of the patch operations to STDOUT.
    :return: A dictionary mapping variable IDs to variables, or None if an error occurred.
    """
    def write_parse_error(json_object: Any) -> None:
        if write_output:
            print(
                f"Warning: a variable was not successfully parsed from {json.dumps(json_object)}",
                file=sys.stderr)

    # yapf: disable
    response = safe_http_request(
        lambda: throttle(lambda: requests.get(
            f"{base_url}/workspaces/{workspace.workspace_id}/vars",
            headers=headers
        ))
    )
    # yapf: enable

    variables = {}
    if response.status_code == 200:
        body = response.json()
        if "data" in body and isinstance(body["data"], list):
            for obj in body["data"]:
                if isinstance(obj,
                              dict) and "id" in obj and "attributes" in obj:
                    variable_id = obj["id"]
                    variable = Variable.from_json(obj["attributes"])
                    if variable is not None:
                        variables[variable_id] = variable
                    else:
                        write_parse_error(obj)
                        return None
                else:
                    write_parse_error(obj)
                    return None
        else:
            write_parse_error(response.json())
            return None
    else:
        if write_output:
            print(
                f'Error: failed to get the existing variables for workspace "{workspace.name}".',
                file=sys.stderr)
        return None
    return variables
示例#2
0
def test_deserialization() -> None:
    variable = Variable.from_json(_test_json)
    assert variable.key == _test_json["key"]
    assert variable.value == _test_json["value"]
    assert variable.description == _test_json["description"]
    assert variable.sensitive == _test_json["sensitive"]
    assert variable.category == _test_json["category"]
    assert variable.hcl == _test_json["hcl"]
def parse_variables(file_path_and_name: str,
                    write_output: bool = False) -> List[Variable]:
    """
    Parses Variable objects out of a given file.

    :param file_path_and_name: The path (relative to the current working directory) and filename of
                               the file containing the variables to configure.
    :param write_output: Whether to print a tabulated result of the patch operations to STDOUT.
    :return: A list of variables that were parsed from the given file, if any.
    """

    variables = []
    try:
        if os.path.exists(file_path_and_name):
            with open(file_path_and_name, "r") as file:
                variables_json = json.load(file)
            for obj in variables_json:
                variable = Variable.from_json(obj)
                if variable is not None:
                    variables.append(variable)
                else:
                    if write_output:
                        # yapf: disable
                        print((
                            "Warning: a variable was not successfully parsed from "
                            f"{file_path_and_name}. Its JSON is {json.dumps(obj)}"
                        ), file=sys.stderr)
                        # yapf: enable
            return variables
        else:
            raise ValueError(f"{file_path_and_name} does not exist.")
    except:
        if write_output:
            print(
                f"Error: unable to read and/or parse the {file_path_and_name} file into JSON.",
                file=sys.stderr)
        return variables