Exemplo n.º 1
0
def test_is_terraform_cloud() -> None:
    domains = [CLOUD_DOMAIN, CLOUD_DOMAIN.upper()]
    for domain in domains:
        assert Terraform(domain, TEST_ORGANIZATION).is_terraform_cloud
    domains = ["something.mycompany.com", "app.company.io"]
    for domain in domains:
        assert not Terraform(domain, TEST_ORGANIZATION).is_terraform_cloud
Exemplo n.º 2
0
def test_lazy_workspace_fetching(mocker: MockerFixture) -> None:
    fetch_mock: MagicMock = mocker.patch(
        "terraform_manager.entities.terraform.fetch_all",
        return_value=[_test_workspace])
    terraform = Terraform(TEST_TERRAFORM_DOMAIN, TEST_ORGANIZATION, token=None)
    workspaces1 = terraform.workspaces
    workspaces2 = terraform.workspaces
    fetch_mock.assert_called_once()
    assert workspaces1 == workspaces2

    terraform.token = "test"
    workspaces3 = terraform.workspaces
    assert fetch_mock.call_count == 2
def configure_variables(terraform: Terraform, file: str) -> None:
    variables_to_configure = parse_variables(file, write_output=True)
    if len(variables_to_configure) == 0:
        if terraform.write_output:
            print(f"Error: no variable definitions found in {file}.", file=sys.stderr)
        fail()
    else:
        _fallible(terraform.configure_variables(variables_to_configure))
Exemplo n.º 4
0
def test_configuration_validation_no_tls_against_terraform_cloud(
        mocker: MockerFixture) -> None:
    fetch_mock: MagicMock = mocker.patch(
        "terraform_manager.entities.terraform.fetch_all",
        return_value=[_test_workspace])
    print_mock: MagicMock = mocker.patch("builtins.print")
    terraform = Terraform(CLOUD_DOMAIN,
                          TEST_ORGANIZATION,
                          workspace_names=[_test_workspace.name],
                          no_tls=True,
                          write_output=True)
    assert not terraform.configuration_is_valid()
    print_mock.assert_called_once_with(
        "Error: you should not disable SSL/TLS when interacting with Terraform Cloud.",
        file=sys.stderr)
    assert terraform.workspaces == []
    fetch_mock.assert_not_called()
def set_versions(terraform: Terraform, desired_version: Optional[str]) -> None:
    if not semver.VersionInfo.isvalid(desired_version) and desired_version != LATEST_VERSION:
        if terraform.write_output:
            print(
                f"Error: the version you specified ({desired_version}) is not valid.",
                file=sys.stderr
            )
        fail()
    else:
        _fallible(terraform.set_versions(desired_version))
Exemplo n.º 6
0
def _organization_required_main(arguments: Dict[str, Any]) -> None:
    organization: str = arguments["organization"]
    if arguments.get("domain") is None:
        domain: str = CLOUD_DOMAIN
    else:
        domain: str = arguments["domain"].lower()
    workspaces_to_target: Optional[List[str]] = arguments.get("workspaces")
    blacklist: bool = arguments["blacklist"]
    no_tls: bool = arguments["no_tls"]
    silent: bool = _is_silenced(parsed_arguments=arguments)

    terraform: Terraform = Terraform(
        domain,
        organization,
        workspace_names=workspaces_to_target,
        blacklist=blacklist,
        no_tls=no_tls,
        token=
        None,  # We disallow specifying a token inline at the CLI for security reasons
        write_output=(not silent))
    if not terraform.configuration_is_valid() or not cli_handlers.validate(
            terraform):
        cli_handlers.fail()
    elif arguments["summary"]:
        terraform.write_summary()
    elif arguments.get("terraform_version") is not None:
        cli_handlers.set_versions(terraform, arguments["terraform_version"])
    elif arguments["lock_workspaces"] or arguments["unlock_workspaces"]:
        cli_handlers.lock_or_unlock_workspaces(terraform,
                                               arguments["lock_workspaces"])
    elif arguments.get("working_directory"
                       ) is not None or arguments["clear_working_directory"]:
        cli_handlers.set_working_directories(
            terraform, arguments.get("working_directory"))
    elif arguments.get("execution_mode") is not None:
        cli_handlers.set_execution_modes(terraform,
                                         arguments["execution_mode"])
    elif arguments.get("configure_variables") is not None:
        cli_handlers.configure_variables(terraform,
                                         arguments["configure_variables"])
    elif arguments.get("delete_variables") is not None:
        cli_handlers.delete_variables(terraform, arguments["delete_variables"])
    elif arguments["enable_auto_apply"] or arguments["disable_auto_apply"]:
        cli_handlers.set_auto_apply(terraform, arguments["enable_auto_apply"])
    elif arguments["enable_speculative"] or arguments["disable_speculative"]:
        cli_handlers.set_speculative(terraform,
                                     arguments["enable_speculative"])
    else:
        if silent:
            _parser_fail()
        else:
            _parser.error(
                "Unable to determine which operation you are attempting to perform."
            )
Exemplo n.º 7
0
def test_configuration_validation_unexpected_blacklist_flag(
        mocker: MockerFixture) -> None:
    for test in [None, []]:
        fetch_mock: MagicMock = mocker.patch(
            "terraform_manager.entities.terraform.fetch_all",
            return_value=[_test_workspace])
        print_mock: MagicMock = mocker.patch("builtins.print")
        terraform = Terraform(TEST_TERRAFORM_DOMAIN,
                              TEST_ORGANIZATION,
                              workspace_names=test,
                              blacklist=True,
                              write_output=True)
        assert not terraform.configuration_is_valid()
        # yapf: disable
        print_mock.assert_called_once_with((
            "Error: the blacklist flag is only applicable when you specify workspace(s) to filter "
            "on."
        ), file=sys.stderr)
        # yapf: enable
        assert terraform.workspaces == []
        fetch_mock.assert_not_called()
def delete_variables(terraform: Terraform, variable_keys: List[str]) -> None:
    _fallible(terraform.delete_variables(variable_keys))
def set_speculative(terraform: Terraform, speculative: bool) -> None:
    _fallible(terraform.set_speculative(speculative))
Exemplo n.º 10
0
def set_auto_apply(terraform: Terraform, auto_apply: bool) -> None:
    _fallible(terraform.set_auto_apply(auto_apply))
Exemplo n.º 11
0
def set_execution_modes(terraform: Terraform, execution_mode: str) -> None:
    arguments = execution_mode.split(",")
    if len(arguments) > 1:
        _fallible(terraform.set_execution_modes(arguments[0], agent_pool_id=arguments[1]))
    else:
        _fallible(terraform.set_execution_modes(execution_mode))
Exemplo n.º 12
0
def set_working_directories(terraform: Terraform, working_directory: Optional[str]) -> None:
    _fallible(terraform.set_working_directories(working_directory))
Exemplo n.º 13
0
def lock_or_unlock_workspaces(terraform: Terraform, lock: bool) -> None:
    _fallible(terraform.lock_workspaces() if lock else terraform.unlock_workspaces())
Exemplo n.º 14
0
def test_passthrough(mocker: MockerFixture) -> None:
    workspaces = [_test_workspace]

    mocker.patch("terraform_manager.entities.terraform.fetch_all",
                 return_value=workspaces)
    lock_or_unlock_mock: MagicMock = mocker.patch(
        "terraform_manager.entities.terraform.lock_or_unlock_workspaces",
        return_value=True)
    summary_mock: MagicMock = mocker.patch(
        "terraform_manager.entities.terraform.write_summary")
    configure_variables_mock: MagicMock = mocker.patch(
        "terraform_manager.entities.terraform.configure_variables",
        return_value=True)
    delete_variables_mock: MagicMock = mocker.patch(
        "terraform_manager.entities.terraform.delete_variables",
        return_value=True)
    batch_operation_mock: MagicMock = mocker.patch(
        "terraform_manager.entities.terraform.batch_operation",
        return_value=True)

    terraform = Terraform(TEST_TERRAFORM_DOMAIN, TEST_ORGANIZATION)

    assert terraform.lock_workspaces()
    assert terraform.unlock_workspaces()
    lock_or_unlock_mock.assert_has_calls([
        call(TEST_TERRAFORM_DOMAIN,
             TEST_ORGANIZATION,
             workspaces,
             set_lock=True,
             no_tls=False,
             token=None,
             write_output=False),
        call(TEST_TERRAFORM_DOMAIN,
             TEST_ORGANIZATION,
             workspaces,
             set_lock=False,
             no_tls=False,
             token=None,
             write_output=False)
    ])

    assert terraform.check_versions("0.13.5")
    assert not terraform.check_versions("0.12.9")

    terraform.write_summary()
    summary_mock.assert_called_once_with(TEST_TERRAFORM_DOMAIN,
                                         TEST_ORGANIZATION,
                                         workspaces,
                                         targeting_specific_workspaces=False,
                                         write_output=False)

    variables = []
    assert terraform.configure_variables(variables)
    configure_variables_mock.assert_called_once_with(TEST_TERRAFORM_DOMAIN,
                                                     TEST_ORGANIZATION,
                                                     workspaces,
                                                     variables=variables,
                                                     no_tls=False,
                                                     token=None,
                                                     write_output=False)

    assert terraform.delete_variables(variables)
    delete_variables_mock.assert_called_once_with(TEST_TERRAFORM_DOMAIN,
                                                  TEST_ORGANIZATION,
                                                  workspaces,
                                                  variables=variables,
                                                  no_tls=False,
                                                  token=None,
                                                  write_output=False)

    assert terraform.set_working_directories("test")
    assert terraform.set_execution_modes("local")
    assert not terraform.set_execution_modes("something invalid")
    assert terraform.set_auto_apply(False)
    assert terraform.set_versions("1000.0.0")
    assert terraform.set_speculative(False)
    assert batch_operation_mock.call_count == 5
Exemplo n.º 15
0
def test_set_execution_modes(mocker: MockerFixture) -> None:
    for write_output in [True, False]:
        print_mock: MagicMock = mocker.patch("builtins.print")

        cloud_terraform = Terraform(TEST_TERRAFORM_DOMAIN,
                                    TEST_ORGANIZATION,
                                    write_output=write_output)
        enterprise_domain = "something.company.com"
        enterprise_terraform = Terraform(enterprise_domain,
                                         TEST_ORGANIZATION,
                                         write_output=write_output)

        for terraform in [cloud_terraform, enterprise_terraform]:
            invalid = "invalid"
            assert not terraform.set_execution_modes(invalid)
            if write_output:
                print_mock.assert_called_once_with(
                    f"Error: invalid execution-mode specified: {invalid}",
                    file=sys.stderr)
                print_mock.reset_mock()
            else:
                print_mock.assert_not_called()

        assert not enterprise_terraform.set_execution_modes(
            "agent", agent_pool_id="something")
        if write_output:
            # yapf: disable
            print_mock.assert_called_once_with((
                f'Error: desired execution-mode is "agent" but you are not targeting Terraform '
                f'Cloud (selected domain is "{enterprise_domain}").'
            ), file=sys.stderr)
            # yapf: enable
            print_mock.reset_mock()
        else:
            print_mock.assert_not_called()

        assert not cloud_terraform.set_execution_modes("agent")
        if write_output:
            print_mock.assert_called_once_with(
                f'Error: desired execution-mode is "agent" but no agent-pool-id was specified.',
                file=sys.stderr)
            print_mock.reset_mock()
        else:
            print_mock.assert_not_called()

        for test in [None, ""]:
            assert not cloud_terraform.set_execution_modes("agent",
                                                           agent_pool_id=test)
            if write_output:
                print_mock.assert_called_once_with(
                    f'Error: desired execution-mode is "agent" but no agent-pool-id was specified.',
                    file=sys.stderr)
                print_mock.reset_mock()
            else:
                print_mock.assert_not_called()

        for test in ["remote", "local"]:
            for terraform in [cloud_terraform, enterprise_terraform]:
                assert not terraform.set_execution_modes(
                    test, agent_pool_id="something")
                if write_output:
                    # yapf: disable
                    print_mock.assert_called_once_with((
                        f'Error: desired execution-mode is "{test}" but an agent-pool-id was '
                        f'specified.'
                    ), file=sys.stderr)
                    # yapf: enable
                    print_mock.reset_mock()
                else:
                    print_mock.assert_not_called()