Exemple #1
0
    def provision(self):
        super(AzureEventGridMode, self).provision()
        session = local_session(self.policy.session_factory)
        key = self._get_webhook_key(session)
        webhook_url = 'https://%s.azurewebsites.net/api/%s?code=%s' % (
            self.webapp_name, self.policy_name, key)
        destination = WebHookEventSubscriptionDestination(
            endpoint_url=webhook_url)

        self.log.info("Creating Event Grid subscription")
        event_filter = EventSubscriptionFilter()
        event_info = EventSubscription(destination=destination,
                                       filter=event_filter)
        scope = '/subscriptions/%s' % session.subscription_id

        #: :type: azure.mgmt.eventgrid.EventGridManagementClient
        eventgrid_client = session.client(
            'azure.mgmt.eventgrid.EventGridManagementClient')

        status_success = False
        while not status_success:
            try:
                event_subscription = eventgrid_client.event_subscriptions.create_or_update(
                    scope, self.webapp_name, event_info)

                event_subscription.result()
                self.log.info('Event Grid subscription creation succeeded')
                status_success = True
            except CloudError as e:
                self.log.info(e)
                self.log.info('Retrying in 30 seconds')
                time.sleep(30)
Exemple #2
0
    def create_eventgrid(self) -> None:
        logger.info("creating eventgrid subscription")
        src_resource_id = self.results["deploy"]["fuzz-storage"]["value"]
        dst_resource_id = self.results["deploy"]["func-storage"]["value"]
        client = get_client_from_cli_profile(
            StorageManagementClient,
            subscription_id=self.get_subscription_id())
        event_subscription_info = EventSubscription(
            destination=StorageQueueEventSubscriptionDestination(
                resource_id=dst_resource_id, queue_name="file-changes"),
            filter=EventSubscriptionFilter(included_event_types=[
                "Microsoft.Storage.BlobCreated",
                "Microsoft.Storage.BlobDeleted",
            ]),
            retry_policy=RetryPolicy(
                max_delivery_attempts=30,
                event_time_to_live_in_minutes=1440,
            ),
        )

        client = get_client_from_cli_profile(
            EventGridManagementClient,
            subscription_id=self.get_subscription_id())
        result = client.event_subscriptions.create_or_update(
            src_resource_id, "onefuzz1", event_subscription_info).result()
        if result.provisioning_state != "Succeeded":
            raise Exception(
                "eventgrid subscription failed: %s" %
                json.dumps(result.as_dict(), indent=4, sort_keys=True), )
    def test_user_topics(self, resource_group, location):
        topic_name = "kalspython1"
        eventsubscription_name = "kalspythonEventSubscription2"

        # Create a new topic and verify that it is created successfully
        topic_result_create = self.eventgrid_client.topics.create_or_update(resource_group.name, topic_name, Topic(location="westcentralus"))
        topic = topic_result_create.result()
        self.assertEqual(topic.name, topic_name)

        # Create a new event subscription to this topic
        # Use this for recording mode
        # scope = "/subscriptions/55f3dcd4-cac7-43b4-990b-a139d62a1eb2/resourceGroups/" + resource_group.name + "/providers/Microsoft.EventGrid/topics/" + topic_name
        scope = "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/" + resource_group.name + "/providers/Microsoft.EventGrid/topics/" + topic_name

        destination = WebHookEventSubscriptionDestination(
            # TODO: Before recording tests, replace with a valid Azure function URL
            endpoint_url="https://kalsfunc1.azurewebsites.net/api/HttpTriggerCSharp1?code=hidden"
        )
        filter = EventSubscriptionFilter()

        event_subscription_info = EventSubscription(destination=destination, filter=filter)
        es_result_create = self.eventgrid_client.event_subscriptions.create_or_update(scope, eventsubscription_name, event_subscription_info)
        event_subscription = es_result_create.result()
        self.assertEqual(eventsubscription_name, event_subscription.name)

        # Delete the event subscription
        self.eventgrid_client.event_subscriptions.delete(scope, eventsubscription_name).wait()

        # Delete the topic
        self.eventgrid_client.topics.delete(resource_group.name, topic_name).wait()
Exemple #4
0
def cli_eventgrid_event_subscription_create(cmd,
                                            client,
                                            event_subscription_name,
                                            endpoint,
                                            resource_id=None,
                                            resource_group_name=None,
                                            topic_name=None,
                                            endpoint_type=WEBHOOK_DESTINATION,
                                            included_event_types=None,
                                            subject_begins_with=None,
                                            subject_ends_with=None,
                                            is_subject_case_sensitive=False,
                                            labels=None):
    scope = _get_scope_for_event_subscription(cmd.cli_ctx, resource_id,
                                              topic_name, resource_group_name)

    if endpoint_type.lower() == WEBHOOK_DESTINATION.lower():
        destination = WebHookEventSubscriptionDestination(endpoint)
    elif endpoint_type.lower() == EVENTHUB_DESTINATION.lower():
        destination = EventHubEventSubscriptionDestination(endpoint)

    event_subscription_filter = EventSubscriptionFilter(
        subject_begins_with, subject_ends_with, included_event_types,
        is_subject_case_sensitive)
    event_subscription_info = EventSubscription(destination,
                                                event_subscription_filter,
                                                labels)

    async_event_subscription_create = client.create_or_update(
        scope, event_subscription_name, event_subscription_info)
    created_event_subscription = async_event_subscription_create.result()
    return created_event_subscription
Exemple #5
0
    def createEventGridSubscription(self, eventSubscriptionName,
                                    storageAccountId, queueName,
                                    subscriptionId):
        logging.info("Creating new event grid subscription with name: " +
                     eventSubscriptionName + " in subscription: " +
                     subscriptionId)

        eventGridClient = self.getEventGridManagementClient(subscriptionId)

        scope = storageAccountId

        destination = StorageQueueEventSubscriptionDestination(
            resource_id=storageAccountId, queue_name=queueName)

        subscriptionFilter = EventSubscriptionFilter(
            # By default, "All" event types are included
            subject_begins_with=
            '/blobServices/default/containers/insights-operational-logs/',
            included_event_types=['Microsoft.Storage.BlobCreated'])

        event_subscription_info = EventSubscription(destination=destination,
                                                    filter=subscriptionFilter)

        event_subscription_async = eventGridClient.event_subscriptions.create_or_update(
            scope, eventSubscriptionName, event_subscription_info)
        event_subscription = event_subscription_async.result()

        logging.info(
            "Event grid subscription created successfully with name: " +
            eventSubscriptionName + " in subscription: " + subscriptionId)
        self.__log_item(event_subscription)
def _event_subscription_create(client, resource_group_name, provider_namespace,
                               resource_type, resource_name,
                               event_subscription_name, endpoint,
                               endpoint_type, included_event_types,
                               subject_begins_with, subject_ends_with,
                               is_subject_case_sensitive, labels):
    scope = _get_scope(resource_group_name, provider_namespace, resource_type,
                       resource_name)
    if endpoint_type.lower() == WEBHOOK_DESTINATION.lower():
        destination = WebHookEventSubscriptionDestination(endpoint)
    elif endpoint_type.lower() == EVENTHUB_DESTINATION.lower():
        destination = EventHubEventSubscriptionDestination(endpoint)

    event_subscription_filter = EventSubscriptionFilter(
        subject_begins_with, subject_ends_with, included_event_types,
        is_subject_case_sensitive)
    event_subscription_info = EventSubscription(destination,
                                                event_subscription_filter,
                                                labels)

    async_event_subscription_create = client.create(scope,
                                                    event_subscription_name,
                                                    event_subscription_info)
    created_event_subscription = async_event_subscription_create.result()
    return created_event_subscription
Exemple #7
0
    def test_domains_and_advanced_filter(self, resource_group, location):
        domain_name = "kalspythond1"
        eventsubscription_name = "kalspythonEventSubscription2"

        # Create a new domain and verify that it is created successfully
        domain_result_create = self.eventgrid_client.domains.create_or_update(resource_group.name, domain_name, Domain(location="westcentralus"))
        domain = domain_result_create.result()
        assert domain.name == domain_name

        # Create a new event subscription to this domain
        # Use this for recording mode
        # scope = "/subscriptions/55f3dcd4-cac7-43b4-990b-a139d62a1eb2/resourceGroups/" + resource_group.name + "/providers/Microsoft.EventGrid/domains/" + domain_name
        scope = "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/" + resource_group.name + "/providers/Microsoft.EventGrid/domains/" + domain_name

        destination = WebHookEventSubscriptionDestination(
            # TODO: Before recording tests, replace with a valid Azure function URL
            endpoint_url="https://kalsfunc1.azurewebsites.net/api/HttpTriggerCSharp1?code=hidden"
        )
        filter = EventSubscriptionFilter()
        advanced_filter = NumberLessThanAdvancedFilter(key="data.key1", value=4.0)
        filter.advanced_filters = []
        filter.advanced_filters.append(advanced_filter)

        event_subscription_info = EventSubscription(destination=destination, filter=filter)
        es_result_create = self.eventgrid_client.event_subscriptions.create_or_update(scope, eventsubscription_name, event_subscription_info)
        event_subscription = es_result_create.result()
        assert eventsubscription_name == event_subscription.name

        # Delete the event subscription
        self.eventgrid_client.event_subscriptions.delete(scope, eventsubscription_name).wait()

        # Delete the domain
        self.eventgrid_client.domains.delete(resource_group.name, domain_name).wait()
Exemple #8
0
def cli_eventgrid_event_subscription_create(   # pylint: disable=too-many-locals
        cmd,
        client,
        event_subscription_name,
        endpoint,
        resource_id=None,
        source_resource_id=None,
        resource_group_name=None,
        topic_name=None,
        endpoint_type=WEBHOOK_DESTINATION,
        included_event_types=None,
        subject_begins_with=None,
        subject_ends_with=None,
        is_subject_case_sensitive=False,
        max_delivery_attempts=30,
        event_ttl=1440,
        deadletter_endpoint=None,
        labels=None):
    scope = _get_scope_for_event_subscription(
        cli_ctx=cmd.cli_ctx,
        source_resource_id=source_resource_id,
        resource_id=resource_id,
        topic_name=topic_name,
        resource_group_name=resource_group_name)

    # Construct RetryPolicy based on max_delivery_attempts and event_ttl
    max_delivery_attempts = int(max_delivery_attempts)
    event_ttl = int(event_ttl)
    _validate_retry_policy(max_delivery_attempts, event_ttl)
    retry_policy = RetryPolicy(max_delivery_attempts=max_delivery_attempts, event_time_to_live_in_minutes=event_ttl)

    destination = _get_endpoint_destination(endpoint_type, endpoint)

    event_subscription_filter = EventSubscriptionFilter(
        subject_begins_with=subject_begins_with,
        subject_ends_with=subject_ends_with,
        included_event_types=included_event_types,
        is_subject_case_sensitive=is_subject_case_sensitive)

    deadletter_destination = None
    if deadletter_endpoint is not None:
        deadletter_destination = _get_deadletter_destination(deadletter_endpoint)

    event_subscription_info = EventSubscription(
        destination=destination,
        filter=event_subscription_filter,
        labels=labels,
        retry_policy=retry_policy,
        dead_letter_destination=deadletter_destination)

    _warn_if_manual_handshake_needed(endpoint_type, endpoint)

    return client.create_or_update(
        scope,
        event_subscription_name,
        event_subscription_info).result()
    def create(cls, destination, name, session=None, event_filter=None):
        s = session or local_session(Session)
        event_filter = event_filter or EventSubscriptionFilter()

        event_info = EventSubscription(destination=destination, filter=event_filter)
        scope = '/subscriptions/%s' % s.subscription_id

        client = s.client('azure.mgmt.eventgrid.EventGridManagementClient')
        event_subscription = client.event_subscriptions.create_or_update(scope, name, event_info)
        return event_subscription.result()
    def test_input_mappings_and_queue_destination(self, resource_group,
                                                  location):
        topic_name = "kalspython2"
        eventsubscription_name = "kalspythonEventSubscription3"

        input_schema = InputSchema.cloud_event_v01_schema
        # Create a new topic and verify that it is created successfully
        topic = Topic(location="westcentralus",
                      tags=None,
                      input_schema=input_schema,
                      input_schema_mapping=None)
        topic_result_create = self.eventgrid_client.topics.create_or_update(
            resource_group.name, topic_name, topic)
        topic = topic_result_create.result()
        self.assertEqual(topic.name, topic_name)
        self.assertEqual(topic.input_schema, "CloudEventV01Schema")

        # Create a new event subscription to this topic
        # Use this for recording mode
        # scope = "/subscriptions/55f3dcd4-cac7-43b4-990b-a139d62a1eb2/resourceGroups/" + resource_group.name + "/providers/Microsoft.EventGrid/topics/" + topic_name
        scope = "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/" + resource_group.name + "/providers/Microsoft.EventGrid/topics/" + topic_name

        destination = StorageQueueEventSubscriptionDestination(
            resource_id=
            "/subscriptions/55f3dcd4-cac7-43b4-990b-a139d62a1eb2/resourceGroups/kalstest/providers/Microsoft.Storage/storageAccounts/kalsdemo",
            queue_name="kalsdemoqueue")

        deadletter_destination = StorageBlobDeadLetterDestination(
            resource_id=
            "/subscriptions/55f3dcd4-cac7-43b4-990b-a139d62a1eb2/resourceGroups/kalstest/providers/Microsoft.Storage/storageAccounts/kalsdemo",
            blob_container_name="dlq")

        filter = EventSubscriptionFilter()

        event_subscription_info = EventSubscription(
            destination=destination,
            filter=filter,
            dead_letter_destination=deadletter_destination,
            event_delivery_schema=EventDeliverySchema.cloud_event_v01_schema,
            retry_policy=RetryPolicy(event_time_to_live_in_minutes=5,
                                     max_delivery_attempts=10))
        es_result_create = self.eventgrid_client.event_subscriptions.create_or_update(
            scope, eventsubscription_name, event_subscription_info)
        event_subscription = es_result_create.result()
        self.assertEqual(eventsubscription_name, event_subscription.name)

        # Delete the event subscription
        self.eventgrid_client.event_subscriptions.delete(
            scope, eventsubscription_name).wait()

        # Delete the topic
        self.eventgrid_client.topics.delete(resource_group.name,
                                            topic_name).wait()
def add_event_grid(src_account_id: str, resource_group: str,
                   location: str) -> None:
    client = get_client_from_cli_profile(EventGridManagementClient)
    base = get_base_event(client, resource_group, location)

    event_subscription_info = EventSubscription(
        destination=base.destination,
        filter=base.filter,
        retry_policy=base.retry_policy,
    )

    topic_id = uuid.uuid5(STORAGE_GUID_NAMESPACE, src_account_id).hex

    result = client.event_subscriptions.create_or_update(
        src_account_id, "corpus" + topic_id, event_subscription_info).result()
    if result.provisioning_state != "Succeeded":
        raise Exception(
            "eventgrid subscription failed: %s" %
            json.dumps(result.as_dict(), indent=4, sort_keys=True), )
Exemple #12
0
    def create_event_subscription(self):
        print("creating event subscription")
        event_client = EventGridManagementClient(self.credentials,
                                                 self.subscription_id)

        scope = '/subscriptions/' + self.subscription_id + '/resourceGroups/' + self.test_storage_res_group + '/providers/microsoft.storage/storageaccounts/%s' % self.test_storageaccount_name
        destination = EventHubEventSubscriptionDestination(
            resource_id=self.get_event_hub_resource_id())
        esfilter = EventSubscriptionFilter(
            **{
                "subject_begins_with":
                "/blobServices/default/containers/%s/" %
                self.test_container_name,
                "subject_ends_with":
                "",
                "is_subject_case_sensitive":
                False,
                "included_event_types": ["Microsoft.Storage.BlobCreated"]
            })
        event_subscription_info = EventSubscription(destination=destination,
                                                    filter=esfilter)
        create_resp = event_client.event_subscriptions.create_or_update(
            scope, self.event_subscription_name, event_subscription_info)
        create_resp.wait()
def run_example():
    """Resource Group management example."""
    #
    # Create the Resource Manager Client with an Application (service principal) token provider
    #
    subscription_id = os.environ.get(
        'AZURE_SUBSCRIPTION_ID',
        '11111111-1111-1111-1111-111111111111')  # your Azure Subscription Id
    credentials = ServicePrincipalCredentials(
        client_id=os.environ['AZURE_CLIENT_ID'],
        secret=os.environ['AZURE_CLIENT_SECRET'],
        tenant=os.environ['AZURE_TENANT_ID'])
    resource_client = ResourceManagementClient(credentials, subscription_id)
    event_grid_client = EventGridManagementClient(credentials, subscription_id)

    # Create Resource group
    print('\nCreating a Resource Group...')
    resource_group = resource_client.resource_groups.create_or_update(
        GROUP_NAME, {'location': LOCATION})
    print_item(resource_group)

    # Creating an event subscription to storage account {StorageAccountResourceId} with destination as {HybridConnectionResourceId}
    print(
        '\nCreating an event subscription to storage account {} with destination as {}'
        .format(STORAGE_ACOUNT_RESOURCE_ID, QUEUE_NAME))

    # Scope could be any ARM resource ID that supports EventGrid
    # https://docs.microsoft.com/azure/event-grid/event-sources
    scope = "/subscriptions/{}".format(subscription_id)
    event_subscription_name = 'EventSubscription1'
    destination = StorageQueueEventSubscriptionDestination(
        resource_id=STORAGE_ACOUNT_RESOURCE_ID, queue_name=QUEUE_NAME)
    filter = EventSubscriptionFilter(
        # By default, "All" event types are included
        is_subject_case_sensitive=False,
        subject_begins_with='',
        subject_ends_with='')

    event_subscription_info = EventSubscription(destination=destination,
                                                filter=filter)

    event_subscription_async_poller = event_grid_client.event_subscriptions.create_or_update(
        scope,
        event_subscription_name,
        event_subscription_info,
    )
    # Blocking call for the EventSubscription to be created
    event_subscription = event_subscription_async_poller.result(
    )  # type: EventSubscription
    print_item(event_subscription)

    input("Press enter to delete all created resources.")

    # Delete the EventSubscription
    print('\nDeleting the event subscription')
    delete_async_operation = event_grid_client.event_subscriptions.delete(
        scope, event_subscription_name)
    delete_async_operation.wait()
    print("\nDeleted: {}".format(event_subscription_name))

    # Delete Resource group and everything in it
    print('\nDelete Resource Group')
    delete_async_operation = resource_client.resource_groups.delete(GROUP_NAME)
    delete_async_operation.wait()
    print("\nDeleted: {}".format(GROUP_NAME))
Exemple #14
0
def main():
    # # Loading input values
    # print("::debug::Loading input values")
    azure_credentials = os.environ.get("INPUT_AZURE_CREDENTIALS", default='{}')
    resource_group = os.environ.get("INPUT_RESOURCE_GROUP", default="")
    pattoken = os.environ.get("INPUT_PATTOKEN", default="")
    provider_type = os.environ.get("INPUT_PROVIDER_TYPE", default="")
    events_to_subscribe = os.environ.get("INPUT_EVENTS_TO_SUBSCRIBE",
                                         default="")

    try:
        azure_credentials = json.loads(azure_credentials)
    except JSONDecodeError:
        print(
            "::error::Please paste output of `az ad sp create-for-rbac --name <your-sp-name> --role contributor --scopes /subscriptions/<your-subscriptionId>/resourceGroups/<your-rg> --sdk-auth` as value of secret variable: AZURE_CREDENTIALS"
        )
        raise AMLConfigurationException(
            f"Incorrect or poorly formed output from azure credentials saved in AZURE_CREDENTIALS secret. See setup in https://github.com/Azure/aml-workspace/blob/master/README.md"
        )

    if not resource_group:
        raise AMLConfigurationException(f"A resource group must be provided")

    # Checking provided parameters
    print("::debug::Checking provided parameters")
    required_parameters_provided(
        parameters=azure_credentials,
        keys=["tenantId", "clientId", "clientSecret"],
        message=
        "Required parameter(s) not found in your azure credentials saved in AZURE_CREDENTIALS secret for logging in to the workspace. Please provide a value for the following key(s): "
    )

    # # Loading parameters file
    # print("::debug::Loading parameters file")

    template_file_file_path = os.path.join("/code", "func_deploy.json")

    # Mask values
    print("::debug::Masking parameters")
    mask_parameter(parameter=azure_credentials.get("tenantId", ""))
    mask_parameter(parameter=azure_credentials.get("clientId", ""))
    mask_parameter(parameter=azure_credentials.get("clientSecret", ""))
    mask_parameter(parameter=azure_credentials.get("subscriptionId", ""))

    # Login User on CLI
    tenant_id = azure_credentials.get("tenantId", "")
    service_principal_id = azure_credentials.get("clientId", "")
    service_principal_password = azure_credentials.get("clientSecret", "")
    subscriptionId = azure_credentials.get("subscriptionId", "")

    credentials = None
    try:
        credentials = ServicePrincipalCredentials(
            client_id=service_principal_id,
            secret=service_principal_password,
            tenant=tenant_id)
    except Exception as ex:
        raise CredentialsVerificationError(ex)

    ####################### Authentication Done ###################################

    # repository name
    repository_name = os.environ.get("GITHUB_REPOSITORY",
                                     "azureeventgridsample")
    functionAppName = repository_name.replace(
        "/", "")  # create a unique function-AppName
    functionAppName = functionAppName.replace("_", "").replace("-", "")[:32]
    functionFolder = 'fappdeploy'
    functionGitHubURL = "https://github.com/Ayaz43/function_app.git"
    functionGitHubBranch = "master"
    functionName = "generic_triggers"
    patToken = pattoken
    parameters = {
        'functionAppName': functionAppName,
        'functionFolder': functionFolder,
        'functionGitHubURL': functionGitHubURL,
        'functionGitHubBranch': functionGitHubBranch,
        'patToken': patToken,
        'ownerName': functionAppName
    }

    parameters = {k: {'value': v} for k, v in parameters.items()}

    client = None
    try:
        client = ResourceManagementClient(credentials, subscriptionId)
    except Exception as ex:
        raise ResourceManagementError(ex)

    template = None
    with open(template_file_file_path, 'r') as template_file_fd:
        template = json.load(template_file_fd)

    deployment_properties = {
        'properties': {
            'mode': DeploymentMode.incremental,
            'template': template,
            'parameters': parameters
        }
    }

    try:
        validate = client.deployments.validate(resource_group, "azure-sample",
                                               deployment_properties)
        validate.wait()

    except Exception as ex:
        raise ActionDeploymentError(ex)
    try:
        deployment_async_operation = client.deployments.create_or_update(
            resource_group, 'azure-sample', deployment_properties)
        deployment_async_operation.wait()
    except Exception as ex:
        raise ActionDeploymentError(ex)

    deploymemnt_result = deployment_async_operation.result()

    # parameters
    code = deploymemnt_result.properties.outputs['hostKey']['value']
    functionAppName = deploymemnt_result.properties.outputs['functionAppName'][
        'value']

    function_url = "https://{}.azurewebsites.net/api/{}?code={}&repoName={}".format(
        functionAppName, functionName, code, repository_name)
    resource_id = "/subscriptions/{}/resourceGroups/{}/providers/{}".format(
        subscriptionId, resource_group, provider_type)

    event_grid_client = EventGridManagementClient(credentials, subscriptionId)
    event_subscription_name = 'EventSubscription1'

    destination = WebHookEventSubscriptionDestination(
        endpoint_url=function_url)

    included_events = get_events_list(events_to_subscribe)
    filter = EventSubscriptionFilter(
        # By default, "All" event types are included
        included_event_types=included_events,
        is_subject_case_sensitive=False,
        subject_begins_with='',
        subject_ends_with='')

    event_subscription_info = EventSubscription(destination=destination,
                                                filter=filter)

    event_subscription_async_poller = event_grid_client.event_subscriptions.create_or_update(
        resource_id,
        event_subscription_name,
        event_subscription_info,
    )

    event_subscription = event_subscription_async_poller.result(
    )  # type: EventSubscription
    print(
        f"::set-output name=destination_url::{event_subscription.destination.endpoint_base_url}"
    )
def run_example():
    """Resource Group management example."""
    #
    # Create the Resource Manager Client with an Application (service principal) token provider
    #
    subscription_id = os.environ.get(
        'AZURE_SUBSCRIPTION_ID',
        '11111111-1111-1111-1111-111111111111')  # your Azure Subscription Id
    credentials = ServicePrincipalCredentials(
        client_id=os.environ['AZURE_CLIENT_ID'],
        secret=os.environ['AZURE_CLIENT_SECRET'],
        tenant=os.environ['AZURE_TENANT_ID'])
    resource_client = ResourceManagementClient(credentials, subscription_id)
    event_grid_client = EventGridManagementClient(credentials, subscription_id)

    # Create Resource group
    print('\nCreating a Resource Group...')
    resource_group = resource_client.resource_groups.create_or_update(
        GROUP_NAME, {'location': LOCATION})
    print_item(resource_group)

    # Create EventGrid topic
    print('\nCreating an EventGrid topic...')
    topic_result_async_poller = event_grid_client.topics.create_or_update(
        resource_group.name, TOPIC_NAME,
        Topic(location=resource_group.location,
              tags={
                  'key1': 'value1',
                  'key2': 'value2'
              }))
    # Blocking call for the Topic to be created
    topic = topic_result_async_poller.result()  # type: Topic
    print_item(topic)

    # Get the keys for the topic
    print('\nGetting the topic keys...')
    keys = event_grid_client.topics.list_shared_access_keys(
        resource_group.name, topic.name)  # type: TopicSharedAccessKeys
    print('The key1 value of topic {} is: {}'.format(topic.name, keys.key1))

    # Create an event subscription
    print('\nCreating an event subscription')
    event_subscription_name = 'EventSubscription1'
    destination = WebHookEventSubscriptionDestination(
        endpoint_url=ENDPOINT_URL)
    filter = EventSubscriptionFilter(
        # By default, "All" event types are included
        is_subject_case_sensitive=False,
        subject_begins_with='',
        subject_ends_with='')

    event_subscription_info = EventSubscription(destination=destination,
                                                filter=filter)

    event_subscription_async_poller = event_grid_client.event_subscriptions.create_or_update(
        topic.id,
        event_subscription_name,
        event_subscription_info,
    )
    # Blocking call for the EventSubscription to be created
    event_subscription = event_subscription_async_poller.result(
    )  # type: EventSubscription
    print_item(event_subscription)

    input("Press enter to delete all created resources.")

    # Delete the EventSubscription
    print('\nDeleting the event subscription')
    delete_async_operation = event_grid_client.event_subscriptions.delete(
        topic.id, event_subscription_name)
    delete_async_operation.wait()
    print("\nDeleted: {}".format(event_subscription_name))

    # Delete the topic
    print('\nDeleting the topic')
    delete_async_operation = event_grid_client.topics.delete(
        resource_group.name, topic.name)
    delete_async_operation.wait()
    print("\nDeleted: {}".format(topic.name))

    # Delete Resource group and everything in it
    print('\nDelete Resource Group')
    delete_async_operation = resource_client.resource_groups.delete(GROUP_NAME)
    delete_async_operation.wait()
    print("\nDeleted: {}".format(GROUP_NAME))
Exemple #16
0
def run_example():
    """Resource Group management example."""
    #
    # Create the Resource Manager Client with an Application (service principal) token provider
    #
    subscription_id = os.environ.get(
        'AZURE_SUBSCRIPTION_ID',
        '11111111-1111-1111-1111-111111111111')  # your Azure Subscription Id
    credentials = ServicePrincipalCredentials(
        client_id=os.environ['AZURE_CLIENT_ID'],
        secret=os.environ['AZURE_CLIENT_SECRET'],
        tenant=os.environ['AZURE_TENANT_ID'])
    resource_client = ResourceManagementClient(credentials, subscription_id)
    event_grid_client = EventGridManagementClient(credentials, subscription_id)

    # Create Resource group
    print('\nCreating a Resource Group...')
    resource_group = resource_client.resource_groups.create_or_update(
        GROUP_NAME, {'location': LOCATION})
    print_item(resource_group)

    # Creating an event subscription to storage account {StorageAccountResourceId} with destination as {HybridConnectionResourceId}
    print(
        '\nCreating an event subscription to storage account {} with destination as {}'
        .format(STORAGE_ACOUNT_RESOURCE_ID, HYBRID_CONNECTION_RESOURCE_ID))
    event_subscription_name = 'EventSubscription1'
    destination = HybridConnectionEventSubscriptionDestination(
        resource_id=HYBRID_CONNECTION_RESOURCE_ID)
    filter = EventSubscriptionFilter(
        included_event_types=['Microsoft.Storage.BlobCreatedEvent'],
        is_subject_case_sensitive=False,
        subject_begins_with='/blobServices/default/containers/container1',
        subject_ends_with='.jpg')

    event_subscription_info = EventSubscription(destination=destination,
                                                filter=filter)

    event_subscription_async_poller = event_grid_client.event_subscriptions.create_or_update(
        STORAGE_ACOUNT_RESOURCE_ID,
        event_subscription_name,
        event_subscription_info,
    )
    # Blocking call for the EventSubscription to be created
    event_subscription = event_subscription_async_poller.result(
    )  # type: EventSubscription
    print_item(event_subscription)

    input("Press enter to delete all created resources.")

    # Delete the EventSubscription
    print('\nDeleting the event subscription')
    delete_async_operation = event_grid_client.event_subscriptions.delete(
        STORAGE_ACOUNT_RESOURCE_ID, event_subscription_name)
    delete_async_operation.wait()
    print("\nDeleted: {}".format(event_subscription_name))

    # Delete Resource group and everything in it
    print('\nDelete Resource Group')
    delete_async_operation = resource_client.resource_groups.delete(GROUP_NAME)
    delete_async_operation.wait()
    print("\nDeleted: {}".format(GROUP_NAME))
Exemple #17
0
def cli_eventgrid_event_subscription_create(  # pylint: disable=too-many-locals
        cmd,
        client,
        event_subscription_name,
        endpoint,
        resource_id=None,
        source_resource_id=None,
        resource_group_name=None,
        topic_name=None,
        endpoint_type=WEBHOOK_DESTINATION,
        included_event_types=None,
        subject_begins_with=None,
        subject_ends_with=None,
        is_subject_case_sensitive=False,
        max_delivery_attempts=30,
        event_ttl=1440,
        deadletter_endpoint=None,
        labels=None,
        expiration_date=None,
        advanced_filter=None):

    if included_event_types is not None and len(
            included_event_types) == 1 and included_event_types[0].lower(
            ) == 'all':
        logger.warning(
            'The usage of \"All\" for --included-event-types is not allowed starting from Azure Event Grid'
            ' API Version 2019-02-01-preview. However, the call here is still permitted by replacing'
            ' \"All\" with None in order to return all the event types (for the custom topics and'
            ' domains case) or default event types (for other topic types case). In any future calls,'
            ' please consider leaving --included-event-types unspecified or use None instead.'
        )
        included_event_types = None

    scope = _get_scope_for_event_subscription(
        cli_ctx=cmd.cli_ctx,
        source_resource_id=source_resource_id,
        resource_id=resource_id,
        topic_name=topic_name,
        resource_group_name=resource_group_name)

    # Construct RetryPolicy based on max_delivery_attempts and event_ttl
    max_delivery_attempts = int(max_delivery_attempts)
    event_ttl = int(event_ttl)
    _validate_retry_policy(max_delivery_attempts, event_ttl)
    retry_policy = RetryPolicy(max_delivery_attempts=max_delivery_attempts,
                               event_time_to_live_in_minutes=event_ttl)

    destination = _get_endpoint_destination(endpoint_type, endpoint)

    event_subscription_filter = EventSubscriptionFilter(
        subject_begins_with=subject_begins_with,
        subject_ends_with=subject_ends_with,
        included_event_types=included_event_types,
        is_subject_case_sensitive=is_subject_case_sensitive,
        advanced_filters=advanced_filter)

    deadletter_destination = None
    if deadletter_endpoint is not None:
        deadletter_destination = _get_deadletter_destination(
            deadletter_endpoint)

    if expiration_date is not None:
        expiration_date = parse(expiration_date)

    event_subscription_info = EventSubscription(
        destination=destination,
        filter=event_subscription_filter,
        labels=labels,
        retry_policy=retry_policy,
        expiration_time_utc=expiration_date,
        dead_letter_destination=deadletter_destination)

    _warn_if_manual_handshake_needed(endpoint_type, endpoint)

    return client.create_or_update(scope, event_subscription_name,
                                   event_subscription_info)