Пример #1
0
def get_appconfig_data_client(cmd, name, connection_string, auth_mode, endpoint):
    azconfig_client = None
    if auth_mode == "key":
        connection_string = resolve_connection_string(cmd, name, connection_string)
        try:
            azconfig_client = AzureAppConfigurationClient.from_connection_string(connection_string=connection_string,
                                                                                 user_agent=HttpHeaders.USER_AGENT)
        except ValueError as ex:
            raise CLIError("Failed to initialize AzureAppConfigurationClient due to an exception: {}".format(str(ex)))

    if auth_mode == "login":
        if not endpoint:
            try:
                if name:
                    _, endpoint = resolve_store_metadata(cmd, name)
                else:
                    raise CLIError("App Configuration endpoint or name should be provided if auth mode is 'login'.")
            except Exception as ex:
                raise CLIError(str(ex) + "\nYou may be able to resolve this issue by providing App Configuration endpoint instead of name.")

        from azure.cli.core._profile import Profile
        profile = Profile(cli_ctx=cmd.cli_ctx)
        cred, _, _ = profile.get_login_credentials()
        try:
            azconfig_client = AzureAppConfigurationClient(credential=cred,
                                                          base_url=endpoint,
                                                          user_agent=HttpHeaders.USER_AGENT)
        except (ValueError, TypeError) as ex:
            raise CLIError("Failed to initialize AzureAppConfigurationClient due to an exception: {}".format(str(ex)))

    return azconfig_client
Пример #2
0
def test_app_conf_integration():
    tenant_id, client_id, client_secret = settings_manager.load_service_principal(
    )
    credential = ClientSecretCredential(tenant_id, client_id, client_secret)
    app_config_name = settings_manager.load_app_config_name()
    app_config_client = AzureAppConfigurationClient(
        base_url=f"https://{app_config_name}.azconfig.io",
        credential=credential)
    configuration_settings = app_config_client.list_configuration_settings()
    [print(x) for x in configuration_settings]
 def __init__(self, method_name):
     super(AppConfigurationClientTest, self).__init__(method_name)
     self.vcr.match_on = ["path", "method", "query"]
     if self.is_playback():
         base_url = "https://fake_app_config.azconfig-test.io"
         credential = Mock(get_token=lambda _: AccessToken("fake-token", 0))
     else:
         base_url = os.getenv('APP_CONFIG_ENDPOINT')
         credential = DefaultAzureCredential()
     self.app_config_client = AzureAppConfigurationClient(
         base_url=base_url, credential=credential)
def main():
    CONNECTION_STRING = get_connection_string()

    # Create app config client
    client = AzureAppConfigurationClient.from_connection_string(CONNECTION_STRING)

    print("Set new configuration setting")
    config_setting = ConfigurationSetting(
        key="MyKey",
        value="my value",
        content_type="my content type",
        tags={"my tag": "my tag value"}
    )
    returned_config_setting = client.set_configuration_setting(config_setting)
    print("New configuration setting:")
    print_configuration_setting(returned_config_setting)
    print("")

    print("Get configuration setting")
    fetched_config_setting = client.get_configuration_setting(
        key="MyKey"
    )
    print("Fetched configuration setting:")
    print_configuration_setting(fetched_config_setting)
    print("")

    print("Delete configuration setting")
    client.delete_configuration_setting(
        key="MyKey"
    )
Пример #5
0
def list_key(cmd,
             key=None,
             fields=None,
             name=None,
             label=None,
             datetime=None,
             connection_string=None,
             top=None,
             all_=False,
             resolve_keyvault=False):
    if fields and resolve_keyvault:
        raise CLIError(
            "Please provide only one of these arguments: '--fields' or '--resolve-keyvault'. See 'az appconfig kv list -h' for examples."
        )

    connection_string = resolve_connection_string(cmd, name, connection_string)
    azconfig_client = AzureAppConfigurationClient.from_connection_string(
        connection_string=connection_string, user_agent=HttpHeaders.USER_AGENT)

    keyvalues = __read_kv_from_config_store(
        azconfig_client,
        key=key if key else SearchFilterOptions.ANY_KEY,
        label=label if label else SearchFilterOptions.ANY_LABEL,
        datetime=datetime,
        fields=fields,
        top=top,
        all_=all_,
        cli_ctx=cmd.cli_ctx if resolve_keyvault else None)
    return keyvalues
def main():
    CONNECTION_STRING = get_connection_string()

    # Create app config client
    client = AzureAppConfigurationClient.from_connection_string(
        CONNECTION_STRING)

    print("Add new configuration setting")
    config_setting = ConfigurationSetting(key="MyKey",
                                          label="MyLabel",
                                          value="my value",
                                          content_type="my content type",
                                          tags={"my tag": "my tag value"})
    added_config_setting = client.add_configuration_setting(config_setting)
    print("New configuration setting:")
    print_configuration_setting(added_config_setting)
    print("")

    print("Set configuration setting")
    added_config_setting.value = "new value"
    added_config_setting.content_type = "new content type"
    updated_config_setting = client.set_configuration_setting(config_setting)
    print_configuration_setting(updated_config_setting)
    print("")

    print("List configuration settings")
    config_settings = client.list_configuration_settings(labels=["MyLabel"])
    for item in config_settings:
        print_configuration_setting(item)

    print("Delete configuration setting")
    client.delete_configuration_setting(
        key="MyKey",
        label="MyLabel",
    )
def main():
    CONNECTION_STRING = get_connection_string()

    # Create app config client
    client = AzureAppConfigurationClient.from_connection_string(CONNECTION_STRING)

    config_setting = ConfigurationSetting(
        key="MyKey",
        value="my value",
        content_type="my content type",
        tags={"my tag": "my tag value"}
    )
    returned_config_setting = client.set_configuration_setting(config_setting)

    returned_config_setting.value = "new value"
    returned_config_setting.content_type = "new content type"
    client.set_configuration_setting(config_setting)

    items = client.list_revisions(key_filter="MyKey")
    for item in items:
        print_configuration_setting(item)
        print("")

    client.delete_configuration_setting(
        key="MyKey",
    )
    def test_mock_policies(self, client, appconfiguration_connection_string):
        from azure.core.pipeline.transport import HttpRequest, HttpResponse, HttpTransport
        from azure.core.pipeline.policies import RetryPolicy
        from azure.core.pipeline import Pipeline, PipelineResponse

        class MockTransport(HttpTransport):
            def __init__(self):
                self._count = 0
                self.auth_headers = None
            def __exit__(self, exc_type, exc_val, exc_tb):
                pass
            def close(self):
                pass
            def open(self):
                pass

            def send(self, request, **kwargs):  # type: (PipelineRequest, Any) -> PipelineResponse
                assert request.headers['Authorization'] != self.auth_headers
                self.auth_headers = request.headers['Authorization']
                response = HttpResponse(request, None)
                response.status_code = 429
                return response

        def new_method(self, request):
            request.http_request.headers["Authorization"] = uuid4()

        from azure.appconfiguration._azure_appconfiguration_requests import AppConfigRequestsCredentialsPolicy
        temp = AppConfigRequestsCredentialsPolicy._signed_request
        AppConfigRequestsCredentialsPolicy._signed_request = new_method

        client = AzureAppConfigurationClient.from_connection_string(appconfiguration_connection_string, transport=MockTransport())

        client.list_configuration_settings()

        AppConfigRequestsCredentialsPolicy._signed_request = temp
Пример #9
0
    def __init__(self):
        self.client = AzureAppConfigurationClient.from_connection_string(APP_CONFIG_CONNECTION_STR)

        self.api_instance = API_INSTANCE_NAME

        # sentinel should change if new configurations are available
        self.sentinel = self._get_sentinel()
        self.allowlist = self._get_allowlist()
 def __init__(self, method_name):
     super(AppConfigurationClientTest, self).__init__(method_name)
     self.vcr.match_on = ["path", "method", "query"]
     if self.is_playback():
         connection_str = "Endpoint=https://fake_app_config.azconfig-test.io;Id=0-l4-s0:h5htBaY5Z1LwFz50bIQv;Secret=bgyvBgwsQIw0s8myrqJJI3nLrj81M/kzSgSuP4BBoVg="
     else:
         connection_str = os.getenv('APP_CONFIG_CONNECTION')
     self.app_config_client = AzureAppConfigurationClient.from_connection_string(connection_str)
Пример #11
0
 def __init__(self, arguments):
     super().__init__(arguments)
     connection_string = self.get_from_env(
         "AZURE_APP_CONFIG_CONNECTION_STRING")
     self.key = "KEY"
     self.service_client = SyncAppConfigClient.from_connection_string(
         connection_string=connection_string)
     self.async_service_client = AsyncAppConfigClient.from_connection_string(
         connection_string=connection_string)
Пример #12
0
def unlock_feature(cmd,
                   feature,
                   name=None,
                   label=None,
                   connection_string=None,
                   yes=False):
    key = FeatureFlagConstants.FEATURE_FLAG_PREFIX + feature
    connection_string = resolve_connection_string(cmd, name, connection_string)
    azconfig_client = AzureAppConfigurationClient.from_connection_string(
        connection_string=connection_string, user_agent=HttpHeaders.USER_AGENT)

    retry_times = 3
    retry_interval = 1
    for i in range(0, retry_times):
        try:
            retrieved_kv = azconfig_client.get_configuration_setting(
                key=key, label=label)
        except ResourceNotFoundError:
            raise CLIError(
                "Feature '{}' with label '{}' does not exist.".format(
                    feature, label))
        except HttpResponseError as exception:
            raise CLIError(
                "Failed to retrieve feature flags from config store. " +
                str(exception))

        if retrieved_kv is None or retrieved_kv.content_type != FeatureFlagConstants.FEATURE_FLAG_CONTENT_TYPE:
            raise CLIError(
                "The feature '{}' you are trying to unlock does not exist.".
                format(feature))

        confirmation_message = "Are you sure you want to unlock the feature '{}' with label '{}'".format(
            feature, label)
        user_confirmation(confirmation_message, yes)

        try:
            new_kv = azconfig_client.set_read_only(
                retrieved_kv,
                read_only=False,
                match_condition=MatchConditions.IfNotModified)
            return map_keyvalue_to_featureflag(
                convert_configurationsetting_to_keyvalue(new_kv),
                show_conditions=False)
        except HttpResponseError as exception:
            if exception.status_code == StatusCodes.PRECONDITION_FAILED:
                logger.debug(
                    'Retrying unlock operation %s times with exception: concurrent setting operations',
                    i + 1)
                time.sleep(retry_interval)
            else:
                raise CLIError(str(exception))
        except Exception as exception:
            raise CLIError(str(exception))
    raise CLIError(
        "Failed to unlock the feature '{}' with label '{}' due to a conflicting operation."
        .format(feature, label))
    def setUp(self):
        self.working_folder = path.dirname(__file__)
        super(AppConfigurationClientExamples, self).setUp()
        # [START create_app_configuration_client]
        import os
        from azure.appconfiguration import AzureAppConfigurationClient

        connection_str = os.environ["APP_CONFIG_CONNECTION"]
        client = AzureAppConfigurationClient(connection_str)
        # [END create_app_configuration_client]

        self.client = client
Пример #14
0
def azure_appconfig_resolver(connection_string):

    client = AzureAppConfigurationClient.from_connection_string(
        connection_string)

    def return_config(k):
        try:
            return client.get_configuration_setting(k).value
        except ResourceNotFoundError as rnfe:
            raise KeyError from rnfe

    return return_config
Пример #15
0
    def wrapper(*args, **kwargs):
        appconfiguration_connection_string = kwargs.pop(
            "appconfiguration_connection_string")
        client = AzureAppConfigurationClient.from_connection_string(
            appconfiguration_connection_string)

        kwargs['client'] = client
        kwargs[
            'appconfiguration_connection_string'] = appconfiguration_connection_string

        # Do setUp on client
        test_config_setting = _add_for_test(
            client,
            ConfigurationSetting(
                key=KEY,
                label=LABEL,
                value=TEST_VALUE,
                content_type=TEST_CONTENT_TYPE,
                tags={
                    "tag1": "tag1",
                    "tag2": "tag2"
                },
            ))
        test_config_setting_no_label = _add_for_test(
            client,
            ConfigurationSetting(
                key=KEY,
                label=None,
                value=TEST_VALUE,
                content_type=TEST_CONTENT_TYPE,
                tags={
                    "tag1": "tag1",
                    "tag2": "tag2"
                },
            ))
        to_delete = [test_config_setting, test_config_setting_no_label]

        kwargs['test_config_setting'] = test_config_setting
        kwargs['test_config_setting_no_label'] = test_config_setting_no_label

        trimmed_kwargs = {k: v for k, v in kwargs.items()}
        trim_kwargs_from_test_function(func, trimmed_kwargs)

        func(*args, **trimmed_kwargs)

        for item in to_delete:
            try:
                client.delete_configuration_setting(key=item.key,
                                                    label=item.label)
            except:
                print("Issue deleting config with key {} and label {}".format(
                    item.key, item.label))
Пример #16
0
 def create_kv(self, connection_str):
     from azure.appconfiguration import (AzureAppConfigurationClient,
                                         ConfigurationSetting)
     app_config_client = AzureAppConfigurationClient.from_connection_string(
         connection_str)
     kv = ConfigurationSetting(key=KEY,
                               label=LABEL,
                               value=TEST_VALUE,
                               content_type=TEST_CONTENT_TYPE,
                               tags={
                                   "tag1": "tag1",
                                   "tag2": "tag2"
                               })
     created_kv = app_config_client.add_configuration_setting(kv)
     return created_kv
Пример #17
0
def list_revision(cmd,
                  key=None,
                  fields=None,
                  name=None,
                  label=None,
                  datetime=None,
                  connection_string=None,
                  top=None,
                  all_=False):
    connection_string = resolve_connection_string(cmd, name, connection_string)
    azconfig_client = AzureAppConfigurationClient.from_connection_string(
        connection_string=connection_string, user_agent=HttpHeaders.USER_AGENT)

    key = key if key else SearchFilterOptions.ANY_KEY
    label = label if label else SearchFilterOptions.ANY_LABEL
    if label == SearchFilterOptions.EMPTY_LABEL:
        label = prep_null_label_for_url_encoding(label)

    try:
        revisions_iterable = azconfig_client.list_revisions(
            key_filter=key,
            label_filter=label,
            accept_datetime=datetime,
            fields=fields)
        retrieved_revisions = []
        count = 0

        if all_:
            top = float('inf')
        elif top is None:
            top = 100

        for revision in revisions_iterable:
            kv_revision = convert_configurationsetting_to_keyvalue(revision)
            if fields:
                partial_revision = {}
                for field in fields:
                    partial_revision[field.name.lower(
                    )] = kv_revision.__dict__[field.name.lower()]
                retrieved_revisions.append(partial_revision)
            else:
                retrieved_revisions.append(kv_revision)
            count += 1
            if count >= top:
                return retrieved_revisions
        return retrieved_revisions
    except HttpResponseError as ex:
        raise CLIError('List revision operation failed.\n' + str(ex))
def handle_event_grid_notifications(event_grid_events):
    # type: (List[dict[str, Any]]) -> None
    CONNECTION_STRING = get_connection_string()

    all_keys = []

    with AzureAppConfigurationClient.from_connection_string(CONNECTION_STRING) as client:

        for event_grid_event in event_grid_events:
            if event_grid_event["eventType"] == 'Microsoft.KeyValueModified':
                sync_token = event['data']['syncToken']
                client.update_sync_token(sync_token)

                new_key = client.get_configuration_setting(key=event['data']['key'], label=event['data']['label'])

                all_keys.append(new_key)
Пример #19
0
def list_feature(cmd,
                 feature=None,
                 name=None,
                 label=None,
                 fields=None,
                 connection_string=None,
                 top=None,
                 all_=False):
    connection_string = resolve_connection_string(cmd, name, connection_string)
    azconfig_client = AzureAppConfigurationClient.from_connection_string(
        connection_string=connection_string, user_agent=HttpHeaders.USER_AGENT)
    try:
        retrieved_keyvalues = __list_all_keyvalues(
            azconfig_client,
            feature=feature if feature else SearchFilterOptions.ANY_KEY,
            label=label if label else SearchFilterOptions.ANY_LABEL)
        retrieved_featureflags = []
        for kv in retrieved_keyvalues:
            retrieved_featureflags.append(
                map_keyvalue_to_featureflag(keyvalue=kv, show_conditions=True))
        filtered_featureflags = []
        count = 0

        if all_:
            top = len(retrieved_featureflags)
        elif top is None:
            top = 100

        for featureflag in retrieved_featureflags:
            if fields:
                partial_featureflags = {}
                for field in fields:
                    # featureflag is guaranteed to have all the fields because
                    # we validate this in map_keyvalue_to_featureflag()
                    # So this line will never throw AttributeError
                    partial_featureflags[field.name.lower()] = getattr(
                        featureflag, field.name.lower())
                filtered_featureflags.append(partial_featureflags)
            else:
                filtered_featureflags.append(featureflag)
            count += 1
            if count >= top:
                break
        return filtered_featureflags

    except Exception as exception:
        raise CLIError(str(exception))
Пример #20
0
def unlock_key(cmd,
               key,
               label=None,
               name=None,
               connection_string=None,
               yes=False):
    connection_string = resolve_connection_string(cmd, name, connection_string)
    azconfig_client = AzureAppConfigurationClient.from_connection_string(
        connection_string=connection_string, user_agent=HttpHeaders.USER_AGENT)

    retry_times = 3
    retry_interval = 1
    for i in range(0, retry_times):
        try:
            retrieved_kv = azconfig_client.get_configuration_setting(
                key=key, label=label)
        except ResourceNotFoundError:
            raise CLIError("Key '{}' with label '{}' does not exist.".format(
                key, label))
        except HttpResponseError as exception:
            raise CLIError(str(exception))

        confirmation_message = "Are you sure you want to unlock the key '{}' with label '{}'".format(
            key, label)
        user_confirmation(confirmation_message, yes)

        try:
            new_kv = azconfig_client.set_read_only(
                retrieved_kv,
                read_only=False,
                match_condition=MatchConditions.IfNotModified)
            return convert_configurationsetting_to_keyvalue(new_kv)
        except HttpResponseError as exception:
            if exception.status_code == StatusCodes.PRECONDITION_FAILED:
                logger.debug(
                    'Retrying unlock operation %s times with exception: concurrent setting operations',
                    i + 1)
                time.sleep(retry_interval)
            else:
                raise CLIError(str(exception))
        except Exception as exception:
            raise CLIError(str(exception))
    raise CLIError(
        "Failed to unlock the key '{}' with label '{}' due to a conflicting operation."
        .format(key, label))
Пример #21
0
def list_filter(cmd,
                feature,
                name=None,
                label=None,
                connection_string=None,
                top=None,
                all_=False):
    key = FeatureFlagConstants.FEATURE_FLAG_PREFIX + feature
    connection_string = resolve_connection_string(cmd, name, connection_string)
    azconfig_client = AzureAppConfigurationClient.from_connection_string(
        connection_string=connection_string, user_agent=HttpHeaders.USER_AGENT)

    try:
        retrieved_kv = azconfig_client.get_configuration_setting(key=key,
                                                                 label=label)
    except ResourceNotFoundError:
        raise CLIError("Feature flag '{}' with label '{}' not found.".format(
            feature, label))
    except HttpResponseError as exception:
        raise CLIError("Failed to retrieve feature flags from config store. " +
                       str(exception))

    try:
        if retrieved_kv is None or retrieved_kv.content_type != FeatureFlagConstants.FEATURE_FLAG_CONTENT_TYPE:
            raise CLIError(
                "The feature flag {} does not exist.".format(feature))

        # we make sure that value retrieved is a valid json and only has the fields supported by backend.
        # if it's invalid, we catch appropriate exception that contains
        # detailed message
        feature_flag_value = map_keyvalue_to_featureflagvalue(retrieved_kv)
        feature_filters = feature_flag_value.conditions['client_filters']

        if all_:
            top = len(feature_filters)
        elif top is None:
            top = 100

        return feature_filters[:top]

    except Exception as exception:
        raise CLIError(str(exception))
Пример #22
0
def show_feature(cmd,
                 feature,
                 name=None,
                 label=None,
                 fields=None,
                 connection_string=None):
    key = FeatureFlagConstants.FEATURE_FLAG_PREFIX + feature
    connection_string = resolve_connection_string(cmd, name, connection_string)
    azconfig_client = AzureAppConfigurationClient.from_connection_string(
        connection_string=connection_string, user_agent=HttpHeaders.USER_AGENT)

    try:
        config_setting = azconfig_client.get_configuration_setting(key=key,
                                                                   label=label)
        if config_setting is None or config_setting.content_type != FeatureFlagConstants.FEATURE_FLAG_CONTENT_TYPE:
            raise CLIError("The feature flag does not exist.")

        retrieved_kv = convert_configurationsetting_to_keyvalue(config_setting)
        feature_flag = map_keyvalue_to_featureflag(keyvalue=retrieved_kv,
                                                   show_conditions=True)

        # If user has specified fields, we still get all the fields and then
        # filter what we need from the response.
        if fields:
            partial_featureflag = {}
            for field in fields:
                # feature_flag is guaranteed to have all the fields because
                # we validate this in map_keyvalue_to_featureflag()
                # So this line will never throw AttributeError
                partial_featureflag[field.name.lower()] = getattr(
                    feature_flag, field.name.lower())
            return partial_featureflag
        return feature_flag
    except ResourceNotFoundError:
        raise CLIError("Feature '{}' with label '{}' does not exist.".format(
            feature, label))
    except HttpResponseError as exception:
        raise CLIError(str(exception))

    raise CLIError("Failed to get the feature '{}' with label '{}'.".format(
        feature, label))
def main():
    CONNECTION_STRING = get_connection_string()

    # Create app config client
    client = AzureAppConfigurationClient.from_connection_string(
        CONNECTION_STRING)

    # Unconditional set
    config_setting = ConfigurationSetting(key="MyKey",
                                          value="my value",
                                          content_type="my content type",
                                          tags={"my tag": "my tag value"})
    client.set_configuration_setting(config_setting)

    # Unconditional get
    first_get = client.get_configuration_setting(key="MyKey")
    print_configuration_setting(first_get)

    # Conditional get, expect to return None because it is not modified
    second_get = client.get_configuration_setting(
        key="MyKey",
        etag=first_get.etag,
        match_condition=MatchConditions.IfModified)
    print_configuration_setting(second_get)

    # Conditional set
    first_get.value = "new value"
    client.set_configuration_setting(
        configuration_setting=first_get,
        match_condition=MatchConditions.IfNotModified)

    # Conditional set, expect to see error because it is modified
    try:
        client.set_configuration_setting(
            configuration_setting=first_get,
            match_condition=MatchConditions.IfNotModified)
    except ResourceModifiedError:
        pass

    client.delete_configuration_setting(key="MyKey")
def main():
    CONNECTION_STRING = get_connection_string()

    # Create app config client
    client = AzureAppConfigurationClient.from_connection_string(CONNECTION_STRING)

    print("Set new configuration setting")
    config_setting = ConfigurationSetting(
        key="MyKey",
        value="my value",
        content_type="my content type",
        tags={"my tag": "my tag value"}
    )
    returned_config_setting = client.set_configuration_setting(config_setting)
    print("New configuration setting:")
    print_configuration_setting(returned_config_setting)
    print("")

    print("Read only configuration setting:")
    read_only_config_setting = client.set_read_only(
        returned_config_setting
    )
    print_configuration_setting(read_only_config_setting)
    print("")

    print("Clear read only configuration setting:")
    read_write_config_setting = client.set_read_only(
        returned_config_setting, False
    )
    print_configuration_setting(read_write_config_setting)
    print("")

    print("Delete configuration setting")
    client.delete_configuration_setting(
        key="MyKey",
    )
Пример #25
0
def show_key(cmd,
             key,
             name=None,
             label=None,
             datetime=None,
             connection_string=None):
    connection_string = resolve_connection_string(cmd, name, connection_string)
    azconfig_client = AzureAppConfigurationClient.from_connection_string(
        connection_string=connection_string, user_agent=HttpHeaders.USER_AGENT)

    try:
        key_value = azconfig_client.get_configuration_setting(
            key=key, label=label, accept_datetime=datetime)
        if key_value is None:
            raise CLIError("The key-value does not exist.")
        return convert_configurationsetting_to_keyvalue(key_value)
    except ResourceNotFoundError:
        raise CLIError("Key '{}' with label '{}' does not exist.".format(
            key, label))
    except HttpResponseError as exception:
        raise CLIError(str(exception))

    raise CLIError("Failed to get the key '{}' with label '{}'.".format(
        key, label))
Пример #26
0
    def get_azure_app_configuration_client(self):
        connection_str = self.config.AZURE_APP_CONFIGURATION_CONNECTION_STRING
        client = AzureAppConfigurationClient.from_connection_string(
            connection_str)

        return client
from azure.appconfiguration import AzureAppConfigurationClient

connection_str = "Endpoint=https://config-demo-azure.azconfig.io;Id=/sWh-l9-s0:n06YX28m2mvHmdknfJdx;Secret=lVepuj2LbqdRjl5dHDXc1U/M7Q0QkXlt71Qhdq6SxSE="
client = AzureAppConfigurationClient.from_connection_string(connection_str)


def get_tweeter_config():
    tweeter_conf = {}
    tweeter_conf['access_token'] = client.get_configuration_setting(
        key="tweeter_access_token").value
    tweeter_conf['access_token_secret'] = client.get_configuration_setting(
        key="tweeter_access_token_secret").value
    tweeter_conf['consumer_key'] = client.get_configuration_setting(
        key="tweeter_consumer_key").value
    tweeter_conf['consumer_secret'] = client.get_configuration_setting(
        key="tweeter_consumer_secret").value
    tweeter_conf['tweets_number'] = client.get_configuration_setting(
        key="tweets_number").value
    return tweeter_conf


def get_eventhub_config():
    eventhub_conf = {}
    eventhub_conf['tweeter-name'] = client.get_configuration_setting(
        key="eventhub-tweeter-name").value
    eventhub_conf['connection_string'] = client.get_configuration_setting(
        key="evet_hub_connection_string").value
    return eventhub_conf
Пример #28
0
 def create_aad_client(self, base_url):
     cred = self.get_credential(AzureAppConfigurationClient)
     return AzureAppConfigurationClient(base_url, cred)
Пример #29
0
def restore_key(cmd,
                datetime,
                key=None,
                name=None,
                label=None,
                connection_string=None,
                yes=False):

    connection_string = resolve_connection_string(cmd, name, connection_string)
    azconfig_client = AzureAppConfigurationClient.from_connection_string(
        connection_string=connection_string, user_agent=HttpHeaders.USER_AGENT)

    exception_messages = []
    try:
        restore_keyvalues = __read_kv_from_config_store(
            azconfig_client,
            key=key if key else SearchFilterOptions.ANY_KEY,
            label=label if label else SearchFilterOptions.ANY_LABEL,
            datetime=datetime)
        current_keyvalues = __read_kv_from_config_store(
            azconfig_client,
            key=key if key else SearchFilterOptions.ANY_KEY,
            label=label if label else SearchFilterOptions.ANY_LABEL)
    except HttpResponseError as exception:
        raise CLIError(
            'Failed to read key-value(s) that match the specified key and label.'
            + str(exception))

    try:
        kvs_to_restore, kvs_to_modify, kvs_to_delete = __compare_kvs_for_restore(
            restore_keyvalues, current_keyvalues)
        if not yes:
            need_change = __print_restore_preview(kvs_to_restore,
                                                  kvs_to_modify, kvs_to_delete)
            if need_change is False:
                logger.debug(
                    'Canceling the restore operation based on user selection.')
                return

        keys_to_restore = len(kvs_to_restore) + len(kvs_to_modify) + len(
            kvs_to_delete)
        restored_so_far = 0

        for kv in chain(kvs_to_restore, kvs_to_modify):
            set_kv = convert_keyvalue_to_configurationsetting(kv)
            try:
                azconfig_client.set_configuration_setting(set_kv)
                restored_so_far += 1
            except ResourceReadOnlyError:
                exception = "Failed to update read-only key-value with key '{}' and label '{}'. Unlock the key-value before updating it.".format(
                    set_kv.key, set_kv.label)
                exception_messages.append(exception)
            except ResourceModifiedError:
                exception = "Failed to update key-value with key '{}' and label '{}' due to a conflicting operation.".format(
                    set_kv.key, set_kv.label)
                exception_messages.append(exception)

        for kv in kvs_to_delete:
            try:
                azconfig_client.delete_configuration_setting(
                    key=kv.key,
                    label=kv.label,
                    etag=kv.etag,
                    match_condition=MatchConditions.IfNotModified)
                restored_so_far += 1
            except ResourceReadOnlyError:
                exception = "Failed to delete read-only key-value with key '{}' and label '{}'. Unlock the key-value before deleting it.".format(
                    kv.key, kv.label)
                exception_messages.append(exception)
            except ResourceModifiedError:
                exception = "Failed to delete key-value with key '{}' and label '{}' due to a conflicting operation.".format(
                    kv.key, kv.label)
                exception_messages.append(exception)

        if restored_so_far != keys_to_restore:
            logger.error(
                'Failed after restoring %d out of %d keys. The following error(s) occurred:\n%s\n',
                restored_so_far, keys_to_restore,
                json.dumps(exception_messages, indent=2, ensure_ascii=False))
        else:
            logger.debug('Successfully restored %d out of %d keys',
                         restored_so_far, keys_to_restore)
        return

    except HttpResponseError as ex:
        exception_messages.append(str(ex))

    raise CLIError(
        'Restore operation failed. The following error(s) occurred:\n' +
        json.dumps(exception_messages, indent=2, ensure_ascii=False))
class AppConfigurationClientTest(AzureMgmtTestCase):
    def __init__(self, method_name):
        super(AppConfigurationClientTest, self).__init__(method_name)
        self.vcr.match_on = ["path", "method", "query"]
        if self.is_playback():
            base_url = "https://fake_app_config.azconfig-test.io"
            credential = Mock(get_token=lambda _: AccessToken("fake-token", 0))
        else:
            base_url = os.getenv('APP_CONFIG_ENDPOINT')
            credential = DefaultAzureCredential()
        self.app_config_client = AzureAppConfigurationClient(
            base_url=base_url, credential=credential)

    def setUp(self):
        super(AppConfigurationClientTest, self).setUp()
        self.test_config_setting = self._add_for_test(
            ConfigurationSetting(
                key=KEY,
                label=LABEL,
                value=TEST_VALUE,
                content_type=TEST_CONTENT_TYPE,
                tags={
                    "tag1": "tag1",
                    "tag2": "tag2"
                },
            ))
        self.test_config_setting_no_label = self._add_for_test(
            ConfigurationSetting(
                key=KEY,
                label=None,
                value=TEST_VALUE,
                content_type=TEST_CONTENT_TYPE,
                tags={
                    "tag1": "tag1",
                    "tag2": "tag2"
                },
            ))
        self.to_delete = [
            self.test_config_setting, self.test_config_setting_no_label
        ]

    def tearDown(self):
        super(AppConfigurationClientTest, self).tearDown()
        for item in self.to_delete:
            self.app_config_client.delete_configuration_setting(
                key=item.key, label=item.label)

    def _add_for_test(self, kv):
        exist = bool(
            list(
                self.app_config_client.list_configuration_settings(
                    key_filter=kv.key, label_filter=kv.label)))
        if exist:
            self._delete_from_test(kv.key, kv.label)
        return self.app_config_client.add_configuration_setting(kv)

    def _delete_from_test(self, key, label):
        try:
            self.app_config_client.delete_configuration_setting(key=key,
                                                                label=label)
        except AzureError:
            logging.debug(
                "Error occurred removing configuration setting %s %s during unit test"
                % (key, label))

    # method: add_configuration_setting
    def test_add_configuration_setting(self):
        kv = ConfigurationSetting(
            key=KEY + "_ADD",
            label=LABEL,
            value=TEST_VALUE,
            content_type=TEST_CONTENT_TYPE,
            tags={
                "tag1": "tag1",
                "tag2": "tag2"
            },
        )
        created_kv = self.app_config_client.add_configuration_setting(kv)
        self.to_delete.append(created_kv)
        assert (created_kv.label == kv.label and kv.value == kv.value
                and created_kv.content_type == kv.content_type
                and created_kv.tags == kv.tags)
        assert (created_kv.etag is not None
                and created_kv.last_modified is not None
                and created_kv.read_only is False)

    def test_add_existing_configuration_setting(self):
        with pytest.raises(ResourceExistsError):
            self.app_config_client.add_configuration_setting(
                ConfigurationSetting(
                    key=self.test_config_setting.key,
                    lable=self.test_config_setting.label,
                ))

    # method: set_configuration_setting
    def test_set_existing_configuration_setting_label_etag(self):
        to_set_kv = self.test_config_setting
        to_set_kv.value = to_set_kv.value + "a"
        to_set_kv.tags = {"a": "b", "c": "d"}
        set_kv = self.app_config_client.set_configuration_setting(to_set_kv)
        assert (to_set_kv.key == set_kv.key
                and to_set_kv.label == to_set_kv.label
                and to_set_kv.value == set_kv.value
                and to_set_kv.content_type == set_kv.content_type
                and to_set_kv.tags == set_kv.tags
                and to_set_kv.etag != set_kv.etag)

    def test_set_existing_configuration_setting_label_wrong_etag(self):
        to_set_kv = self.test_config_setting
        to_set_kv.value = to_set_kv.value + "a"
        to_set_kv.tags = {"a": "b", "c": "d"}
        to_set_kv.etag = "wrong etag"
        with pytest.raises(ResourceModifiedError):
            self.app_config_client.set_configuration_setting(
                to_set_kv, match_condition=MatchConditions.IfNotModified)

    def test_set_configuration_setting_etag(self):
        kv = ConfigurationSetting(
            key=KEY + "_SET",
            label=LABEL,
            value=TEST_VALUE,
            content_type=TEST_CONTENT_TYPE,
            tags={
                "tag1": "tag1",
                "tag2": "tag2"
            },
        )
        kv.etag = "random etag"
        with pytest.raises(ResourceModifiedError):
            self.app_config_client.set_configuration_setting(
                kv, match_condition=MatchConditions.IfNotModified)

    def test_set_configuration_setting_no_etag(self):
        to_set_kv = ConfigurationSetting(
            key=KEY + "_SET",
            label=LABEL,
            value=TEST_VALUE,
            content_type=TEST_CONTENT_TYPE,
            tags={
                "tag1": "tag1",
                "tag2": "tag2"
            },
        )
        set_kv = self.app_config_client.set_configuration_setting(to_set_kv)
        self.to_delete.append(to_set_kv)
        assert (to_set_kv.key == set_kv.key and to_set_kv.label == set_kv.label
                and to_set_kv.value == set_kv.value
                and to_set_kv.content_type == set_kv.content_type
                and to_set_kv.tags == set_kv.tags
                and to_set_kv.etag != set_kv.etag)

    # method: get_configuration_setting
    def test_get_configuration_setting_no_label(self):
        compare_kv = self.test_config_setting_no_label
        fetched_kv = self.app_config_client.get_configuration_setting(
            compare_kv.key)
        assert (fetched_kv.key == compare_kv.key
                and fetched_kv.value == compare_kv.value
                and fetched_kv.content_type == compare_kv.content_type
                and fetched_kv.tags == compare_kv.tags)
        assert fetched_kv.label is None

    def test_get_configuration_setting_label(self):
        compare_kv = self.test_config_setting
        fetched_kv = self.app_config_client.get_configuration_setting(
            compare_kv.key, compare_kv.label)
        assert (fetched_kv.key == compare_kv.key
                and fetched_kv.value == compare_kv.value
                and fetched_kv.content_type == compare_kv.content_type
                and fetched_kv.tags == compare_kv.tags)
        assert fetched_kv.label is not None

    def test_get_non_existing_configuration_setting(self):
        compare_kv = self.test_config_setting
        with pytest.raises(ResourceNotFoundError):
            self.app_config_client.get_configuration_setting(
                compare_kv.key, compare_kv.label + "a")

    # method: delete_configuration_setting
    def test_delete_with_key_no_label(self):
        to_delete_kv = self.test_config_setting_no_label
        self.app_config_client.delete_configuration_setting(to_delete_kv.key)
        self.to_delete.remove(to_delete_kv)
        with pytest.raises(ResourceNotFoundError):
            self.app_config_client.get_configuration_setting(to_delete_kv.key)

    def test_delete_with_key_label(self):
        to_delete_kv = self.test_config_setting
        self.app_config_client.delete_configuration_setting(
            to_delete_kv.key, label=to_delete_kv.label)
        self.to_delete.remove(to_delete_kv)
        with pytest.raises(ResourceNotFoundError):
            self.app_config_client.get_configuration_setting(
                to_delete_kv.key, label=to_delete_kv.label)

    def test_delete_non_existing(self):
        deleted_kv = self.app_config_client.delete_configuration_setting(
            "not_exist_" + KEY)
        assert deleted_kv is None

    def test_delete_correct_etag(self):
        to_delete_kv = self.test_config_setting_no_label
        deleted_kv = self.app_config_client.delete_configuration_setting(
            to_delete_kv.key, etag=to_delete_kv.etag)
        self.to_delete.remove(to_delete_kv)
        assert deleted_kv is not None
        with pytest.raises(ResourceNotFoundError):
            self.app_config_client.get_configuration_setting(to_delete_kv.key)

    def test_delete_wrong_etag(self):
        to_delete_kv = self.test_config_setting_no_label
        with pytest.raises(ResourceModifiedError):
            self.app_config_client.delete_configuration_setting(
                to_delete_kv.key,
                etag="wrong etag",
                match_condition=MatchConditions.IfNotModified)

    # method: list_configuration_settings
    def test_list_configuration_settings_key_label(self):
        items = list(
            self.app_config_client.list_configuration_settings(
                label_filter=LABEL, key_filter=KEY))
        assert len(items) == 1
        assert all(x.key == KEY and x.label == LABEL for x in items)

    def test_list_configuration_settings_only_label(self):
        items = list(
            self.app_config_client.list_configuration_settings(
                label_filter=LABEL))
        assert len(items) == 1
        assert all(x.label == LABEL for x in items)

    def test_list_configuration_settings_only_key(self):
        items = list(
            self.app_config_client.list_configuration_settings(key_filter=KEY))
        assert len(items) == 2
        assert all(x.key == KEY for x in items)

    def test_list_configuration_settings_fields(self):
        items = list(
            self.app_config_client.list_configuration_settings(
                key_filter="*",
                label_filter=LABEL,
                fields=["key", "content_type"]))
        assert len(items) == 1
        assert all(x.key and not x.label and x.content_type for x in items)

    def test_list_configuration_settings_reserved_chars(self):
        resered_char_kv = ConfigurationSetting(key=KEY,
                                               label=LABEL_RESERVED_CHARS,
                                               value=TEST_VALUE)
        resered_char_kv = self.app_config_client.add_configuration_setting(
            resered_char_kv)
        self.to_delete.append(resered_char_kv)
        escaped_label = re.sub(r"((?!^)\*(?!$)|\\|,)", r"\\\1",
                               LABEL_RESERVED_CHARS)
        items = list(
            self.app_config_client.list_configuration_settings(
                label_filter=escaped_label))
        assert len(items) == 1
        assert all(x.label == LABEL_RESERVED_CHARS for x in items)

    def test_list_configuration_settings_contains(self):
        items = list(
            self.app_config_client.list_configuration_settings(
                label_filter="*" + LABEL + "*"))
        assert len(items) == 1
        assert all(x.label == LABEL for x in items)

    def test_list_configuration_settings_correct_etag(self):
        to_list_kv = self.test_config_setting
        custom_headers = {"If-Match": to_list_kv.etag}
        items = list(
            self.app_config_client.list_configuration_settings(
                key_filter=to_list_kv.key,
                label_filter=to_list_kv.label,
                headers=custom_headers))
        assert len(items) == 1
        assert all(x.key == to_list_kv.key and x.label == to_list_kv.label
                   for x in items)

    def test_list_configuration_settings_multi_pages(self):
        # create PAGE_SIZE+1 configuration settings to have at least two pages
        try:
            delete_me = [
                self.app_config_client.add_configuration_setting(
                    ConfigurationSetting(
                        key="multi_" + str(i) + KEY_UUID,
                        label="multi_label_" + str(i),
                        value="multi value",
                    )) for i in range(PAGE_SIZE + 1)
            ]
        except ResourceExistsError:
            pass
        items = self.app_config_client.list_configuration_settings(
            key_filter="multi_*")
        assert len(list(items)) > PAGE_SIZE

        # Remove the configuration settings
        try:
            [
                self.app_config_client.delete_configuration_setting(
                    key="multi_" + str(i) + KEY_UUID,
                    label="multi_label_" + str(i))
                for i in range(PAGE_SIZE + 1)
            ]
        except AzureError:
            pass

    def test_list_configuration_settings_null_label(self):
        items = self.app_config_client.list_configuration_settings(
            label_filter="\0")
        assert len(list(items)) > 0

    def test_list_configuration_settings_only_accepttime(self):
        exclude_today = self.app_config_client.list_configuration_settings(
            accept_datetime=datetime.datetime.today() +
            datetime.timedelta(days=-1))
        all_inclusive = self.app_config_client.list_configuration_settings()
        assert len(list(all_inclusive)) > len(list(exclude_today))

    # method: list_revisions
    def test_list_revisions_key_label(self):
        to_list1 = self.test_config_setting
        items = list(
            self.app_config_client.list_revisions(label_filter=to_list1.label,
                                                  key_filter=to_list1.key))
        assert len(items) >= 2
        assert all(x.key == to_list1.key and x.label == to_list1.label
                   for x in items)

    def test_list_revisions_only_label(self):
        items = list(self.app_config_client.list_revisions(label_filter=LABEL))
        assert len(items) >= 1
        assert all(x.label == LABEL for x in items)

    def test_list_revisions_key_no_label(self):
        items = list(self.app_config_client.list_revisions(key_filter=KEY))
        assert len(items) >= 1
        assert all(x.key == KEY for x in items)

    def test_list_revisions_fields(self):
        items = list(
            self.app_config_client.list_revisions(
                key_filter="*",
                label_filter=LABEL,
                fields=["key", "content_type"]))
        assert all(x.key and not x.label and x.content_type and not x.tags
                   and not x.etag for x in items)

    def test_list_revisions_correct_etag(self):
        to_list_kv = self.test_config_setting
        custom_headers = {"If-Match": to_list_kv.etag}
        items = list(
            self.app_config_client.list_revisions(
                key_filter=to_list_kv.key,
                label_filter=to_list_kv.label,
                headers=custom_headers))
        assert len(items) >= 1
        assert all(x.key == to_list_kv.key and x.label == to_list_kv.label
                   for x in items)

    def test_read_only(self):
        kv = self.test_config_setting_no_label
        read_only_kv = self.app_config_client.set_read_only(kv)
        assert read_only_kv.read_only
        readable_kv = self.app_config_client.set_read_only(read_only_kv, False)
        assert not readable_kv.read_only

    def test_delete_read_only(self):
        to_delete_kv = self.test_config_setting_no_label
        read_only_kv = self.app_config_client.set_read_only(to_delete_kv)
        with pytest.raises(ResourceReadOnlyError):
            self.app_config_client.delete_configuration_setting(
                to_delete_kv.key)
        self.app_config_client.set_read_only(read_only_kv, False)
        self.app_config_client.delete_configuration_setting(to_delete_kv.key)
        self.to_delete.remove(to_delete_kv)
        with pytest.raises(ResourceNotFoundError):
            self.app_config_client.get_configuration_setting(to_delete_kv.key)

    def test_set_read_only(self):
        to_set_kv = self.test_config_setting
        to_set_kv.value = to_set_kv.value + "a"
        to_set_kv.tags = {"a": "b", "c": "d"}
        read_only_kv = self.app_config_client.set_read_only(to_set_kv)
        with pytest.raises(ResourceReadOnlyError):
            self.app_config_client.set_configuration_setting(read_only_kv)
        readable_kv = self.app_config_client.set_read_only(read_only_kv, False)
        readable_kv.value = to_set_kv.value
        readable_kv.tags = to_set_kv.tags
        set_kv = self.app_config_client.set_configuration_setting(readable_kv)
        assert (to_set_kv.key == set_kv.key
                and to_set_kv.label == to_set_kv.label
                and to_set_kv.value == set_kv.value
                and to_set_kv.content_type == set_kv.content_type
                and to_set_kv.tags == set_kv.tags
                and to_set_kv.etag != set_kv.etag)