Example #1
0
def cli_topic_create_or_update(client,
                               resource_group_name,
                               topic_name,
                               location,
                               tags=None):
    topic_info = Topic(location=location, tags=tags)
    return client.create_or_update(resource_group_name, topic_name, topic_info)
    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()
Example #3
0
    def create_resource(self, name, **kwargs):
        if self.is_live:
            self.client = self.create_mgmt_client(EventGridManagementClient)
            group = self._get_resource_group(**kwargs)

            if self.name_prefix.startswith("cloud"):
                # Create a new topic and verify that it is created successfully
                topic = Topic(location=self.parameter_location,
                              tags=None,
                              input_schema=CLOUD_EVENT_SCHEMA,
                              input_schema_mapping=None)
            elif self.name_prefix.startswith("custom"):
                # Create a new topic and verify that it is created successfully
                topic = Topic(
                    location=self.parameter_location,
                    tags=None,
                    input_schema=CUSTOM_EVENT_SCHEMA,
                    input_schema_mapping=CUSTOM_JSON_INPUT_SCHEMA_MAPPING)
            else:
                topic = Topic(location=self.parameter_location)
            topic_operation = self.client.topics.begin_create_or_update(
                group.name,
                name,
                topic,
            )
            self.resource = topic_operation.result()
            key = self.client.topics.list_shared_access_keys(group.name, name)
            self.primary_key = key.key1
            self.endpoint = self.resource.endpoint
        else:
            self.resource = FakeResource(name=name, id=name)
            self.primary_key = "ZmFrZV9hY29jdW50X2tleQ=="  # test key copied from sb_preparer
            self.endpoint = "https://{}.westus-1.eventgrid.azure.net/api/events".format(
                name)
        return {
            self.parameter_name: self.resource,
            '{}_primary_key'.format(self.parameter_name): self.primary_key,
            '{}_endpoint'.format(self.parameter_name): self.endpoint,
        }
    def GetEventGridTopics(tenantId, subscriptionId, resourceGroup,
                           gridLocation, clientId, cientSecret, topicNames):

        credentials = ServicePrincipalCredentials(client_id=clientId,
                                                  secret=cientSecret,
                                                  tenant=tenantId)

        event_grid_client = EventGridManagementClient(credentials,
                                                      subscriptionId)

        # list of current topics for this RG
        pagedTopics = event_grid_client.topics.list_by_resource_group(
            resourceGroup)

        returnDict = {}
        for topic in topicNames:
            print(f"Checking for existence of topic {topic}")
            p_topic = None
            for paged_topic in pagedTopics:
                if topic == paged_topic.name:
                    p_topic = paged_topic
                    break

            if p_topic == None:
                print(f"Topic {topic} does not exist. Creating now...")
                topic_result_poller = event_grid_client.topics.create_or_update(
                    resourceGroup, topic,
                    Topic(location=gridLocation, tags={'createdBy': 'MCCC'}))
                # Blocking call
                topic_result = topic_result_poller.result()  # type: Topic
                print(topic_result)
                print(f"Topic {topic} Created ")
            else:
                print(f"Topic {topic} already exists.")

            key = event_grid_client.topics.list_shared_access_keys(
                resourceGroup, topic).key1
            endpoint = f"{topic}.{gridLocation}-1.eventgrid.azure.net"
            key = event_grid_client.topics.list_shared_access_keys(
                resourceGroup, topic).key1
            rTopic = EventGrid.MCCCTopic(topic, key, endpoint)
            returnDict[topic] = rTopic

        return returnDict
    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()
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))