Example #1
0
        private async Task <GenericResourceInner> SetResourceAsync(GenericResourceInner resource)
        {
            if (resource is null)
            {
                throw new ArgumentNullException(nameof(resource));
            }

            using var resourceManagementClient = AzureResourceService.AzureSessionService
                                                 .CreateClient <ResourceManagementClient>(subscriptionId: this.ResourceId.SubscriptionId);

            var apiVersion = await GetLatestApiVersionAsync()
                             .ConfigureAwait(false);

            if (resource.Properties != null)
            {
                // we need to ensure that the update call doesn't contain
                // a provisioning state information - otherwise the update
                // call will end up in a BAD REQUEST error

                var properties = JObject.FromObject(resource.Properties);
                properties.SelectToken("$.provisioningState")?.Parent?.Remove();
                resource.Properties = properties;
            }

            return(await resourceManagementClient.Resources
                   .UpdateByIdAsync(this.ResourceId.ToString(), apiVersion, resource)
                   .ConfigureAwait(false));
        }
Example #2
0
        public string CreateApplicationInsights(ICloudAppConfig appConfig)
        {
            using (var rmc = new ResourceManagementClient(appConfig.Creds))
            {
                rmc.SubscriptionId = appConfig.SubscriptionId;
                var myparams = new GenericResourceInner(appConfig.AppInsightsLocation,
                                                        name: appConfig.AppInsightsName,
                                                        properties: new
                {
                    ApplicationId = appConfig.AppInsightsName
                });

                var appinsights = rmc.Resources.CreateOrUpdate(appConfig.ResGrpName,
                                                               resourceProviderNamespace: "microsoft.insights",
                                                               resourceType: "components",
                                                               resourceName: appConfig.AppInsightsName,
                                                               parentResourcePath: "",
                                                               apiVersion: "2015-05-01",
                                                               parameters: myparams);

                var key = JObject.Parse(appinsights.Properties.ToString())["InstrumentationKey"];

                Logger.Info($"AppInsightKey={key}");

                return(key.ToString());
            }
        }
        public async Task UpdateResource(ResourceItem updateItem)
        {
            _client.SubscriptionId = updateItem.Subscription;
            GenericResourceInner resource = await _client.Resources.GetByIdAsync(updateItem.Id, updateItem.ApiVersion);

            resource.Tags       = updateItem.Tags;
            resource.Properties = null;  // some resource types support PATCH operations ONLY on tags.
            await _client.Resources.UpdateByIdAsync(updateItem.Id, updateItem.ApiVersion, resource);
        }
        /// <summary>
        /// sets the default expirience (api) of a cosmos db resource.
        /// </summary>
        /// <param name="defaultExpirience"> the new default expirience tag value (docdc, mongodb, graph, table...). </param>
        /// <param name="resourceGroup"> the name of the resource group that contains the cosmos resource. </param>
        /// <param name="resourceName"> the name of the resource for which the default expirience will be changed. </param>
        public async void SetDefaultExpirience(string defaultExpirience, string resourceGroup, string resourceName)
        {
            try
            {
                GenericResourceInner genericResourceI = await this.resourceManagementClient.Resources.GetAsync(resourceGroup, "Microsoft.DocumentDB", "", "databaseAccounts", resourceName, "2016-03-31");

                genericResourceI.Tags.Add("defaultExperience", defaultExpirience);
                await this.resourceManagementClient.Resources.CreateOrUpdateAsync(resourceGroup, "Microsoft.DocumentDB", "", "databaseAccounts", resourceName, "2016-03-31", genericResourceI);
            }
            catch (Exception e)
            {
                Console.WriteLine("Something went wrong while trying to set the defaultExpirience tag... set the tag through the portal or retry.");
                Console.WriteLine(e.Message);
                Console.WriteLine("The default expirience was not changed for the resource [{0}].", resourceName);
            }
        }
Example #5
0
        /// <summary>
        /// Retrieves all the properties of the specified resource from ARM, using the specified ARM API version.
        /// The returned object contains the resource properties. Every ARM resource has different properties with
        /// different schema.
        /// For schema details for the properties of a specific ARM resource type:
        /// <code>https://docs.microsoft.com/azure/templates/{provider-namespace}/{resource-type}</code>
        /// For example, <a href="https://docs.microsoft.com/en-us/azure/templates/Microsoft.Compute/virtualMachines">this link</a>
        /// provides the schema for virtual machine properties.
        /// </summary>
        /// <param name="resource">The specific resource for which to retrieve the properties.</param>
        /// <param name="apiVersion">The ARM API version to use.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>A <see cref="Task{TResult}"/>, running the current operation, and returning the resource properties.</returns>
        public async Task <ResourceProperties> GetResourcePropertiesAsync(ResourceIdentifier resource, string apiVersion, CancellationToken cancellationToken)
        {
            var client = this.GetResourceManagementClient(resource.SubscriptionId);

            // Get the resource type string
            if (!ResourceIdentifier.MapResourceTypeToString.TryGetValue(resource.ResourceType, out string resourceTypeString))
            {
                throw new ArgumentException($"Resource type {resource.ResourceType} is not supported for the GetResourcePropertiesAsync method", nameof(resource));
            }

            // Extract the provider and resource type
            ParseResourceTypeString(resourceTypeString, out string provider, out string type);

            // Get the default API version for this resource type or the latest API version if there is no default (or use a specific version if one was specified)
            if (string.IsNullOrEmpty(apiVersion))
            {
                if (ProviderToDefaultApiVersionMapping.ContainsKey(provider))
                {
                    apiVersion = ProviderToDefaultApiVersionMapping[provider];
                }
                else
                {
                    apiVersion = await this.GetLatestApiVersionAsync(client, provider, type, cancellationToken);
                }
            }

            // Get the resource
            GenericResourceInner result = await this.RunAndTrack(() => client.Resources.GetAsync(
                                                                     resource.ResourceGroupName,
                                                                     provider,
                                                                     string.Empty,
                                                                     type,
                                                                     resource.ResourceName,
                                                                     apiVersion,
                                                                     cancellationToken));

            // Get the resource properties as a JObject
            return(new ResourceProperties(
                       result.Sku == null ? null : new ResourceSku(result.Sku.Name, result.Sku.Tier, result.Sku.Size, result.Sku.Family, result.Sku.Model, result.Sku.Capacity),
                       result.Properties as JObject,
                       apiVersion));
        }
Example #6
0
        public async Task CreateEndpointAsync(string instanceName)
        {
            var auth = GetAzureResourceManagerClient();
            var subs = await auth.Subscriptions.ListAsync();

            do
            {
                GenericResourceInner match = null;
                foreach (var sub in subs)
                {
                    var rm      = auth.WithSubscription(sub.SubscriptionId);
                    var results = await rm.Inner.Resources.ListAsync(
                        new ODataQuery <GenericResourceFilter>(
                            $"resourceType eq 'Microsoft.DigitalTwins/digitaltwinsinstances' and name eq '{instanceName}'"));

                    match = results.FirstOrDefault();
                    if (match != null)
                    {
                        _log.LogInformation($"Found {instanceName}: {match.Id}, creating endpoint");
                        var rg       = match.Id.Split("/", StringSplitOptions.RemoveEmptyEntries)[3];
                        var endpoint = await GetNewEndpoint(rm, instanceName, rg, sub.SubscriptionId);

                        await rm.GenericResources.CreateAsync(new[] { endpoint });

                        break;
                    }
                }

                if (match != null)
                {
                    break;
                }

                subs = await subs.GetNextPageAsync();
            } while (subs != null);
        }
 /// <summary>
 /// Updates a resource by ID.
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='resourceId'>
 /// The fully qualified ID of the resource, including the resource name and
 /// resource type. Use the format,
 /// /subscriptions/{guid}/resourceGroups/{resource-group-name}/{resource-provider-namespace}/{resource-type}/{resource-name}
 /// </param>
 /// <param name='apiVersion'>
 /// The API version to use for the operation.
 /// </param>
 /// <param name='parameters'>
 /// Update resource parameters.
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task <GenericResourceInner> BeginUpdateByIdAsync(this IResourcesOperations operations, string resourceId, string apiVersion, GenericResourceInner parameters, CancellationToken cancellationToken = default(CancellationToken))
 {
     using (var _result = await operations.BeginUpdateByIdWithHttpMessagesAsync(resourceId, apiVersion, parameters, null, cancellationToken).ConfigureAwait(false))
     {
         return(_result.Body);
     }
 }
 /// <summary>
 /// Updates a resource.
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='resourceGroupName'>
 /// The name of the resource group for the resource. The name is case
 /// insensitive.
 /// </param>
 /// <param name='resourceProviderNamespace'>
 /// The namespace of the resource provider.
 /// </param>
 /// <param name='parentResourcePath'>
 /// The parent resource identity.
 /// </param>
 /// <param name='resourceType'>
 /// The resource type of the resource to update.
 /// </param>
 /// <param name='resourceName'>
 /// The name of the resource to update.
 /// </param>
 /// <param name='apiVersion'>
 /// The API version to use for the operation.
 /// </param>
 /// <param name='parameters'>
 /// Parameters for updating the resource.
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task <GenericResourceInner> BeginUpdateAsync(this IResourcesOperations operations, string resourceGroupName, string resourceProviderNamespace, string parentResourcePath, string resourceType, string resourceName, string apiVersion, GenericResourceInner parameters, CancellationToken cancellationToken = default(CancellationToken))
 {
     using (var _result = await operations.BeginUpdateWithHttpMessagesAsync(resourceGroupName, resourceProviderNamespace, parentResourcePath, resourceType, resourceName, apiVersion, parameters, null, cancellationToken).ConfigureAwait(false))
     {
         return(_result.Body);
     }
 }
Example #9
0
        public static async Task Run([QueueTrigger("resources-to-tag", Connection = "AzureWebJobsStorage"), Disable("true")] string myQueueItem,
                                     [Table("InvalidTagResources")] CloudTable invalidResourceTable,
                                     TraceWriter log)
        {
            log.Info($"C# Queue trigger function triggered: {myQueueItem}");

            ResourceItem updateItem = JsonConvert.DeserializeObject <ResourceItem>(myQueueItem);

            TokenCredentials tokenCredential;

            if (Environment.GetEnvironmentVariable("MSI_ENDPOINT") == null)
            {
                log.Info("Using service principal");
                string appId     = Environment.GetEnvironmentVariable("appId");
                string appSecret = Environment.GetEnvironmentVariable("appSecret");
                string tenantId  = Environment.GetEnvironmentVariable("tenantId");
                tokenCredential = AuthenticationService.GetAccessToken(appId, appSecret, tenantId);
            }
            else
            {
                log.Info("Using MSI");
                var    azureServiceTokenProvider = new AzureServiceTokenProvider();
                string token = await azureServiceTokenProvider.GetAccessTokenAsync("https://management.core.windows.net/");

                tokenCredential = new TokenCredentials(token);
            }

            var client = new ResourceManagementClient(tokenCredential);

            client.SubscriptionId = updateItem.Subscription;
            GenericResourceInner resource = null;

            try
            {
                resource = await client.Resources.GetByIdAsync(updateItem.Id, updateItem.ApiVersion);

                resource.Tags       = updateItem.Tags;
                resource.Properties = null;  // some resource types support PATCH operations ONLY on tags.
                await client.Resources.UpdateByIdAsync(updateItem.Id, updateItem.ApiVersion, resource);
            }
            catch (Exception ex)
            {
                if (resource == null)
                {
                    log.Error("Failed to get resource: " + updateItem.Id);
                    log.Error("Error is: " + ex.Message);
                }
                else
                {
                    log.Error(resource.Id + " failed with: " + ex.Message);
                }

                InvalidTagResource matchingInvalidResource = null;
                var invalidTagResourcesQuery = await invalidResourceTable.ExecuteQuerySegmentedAsync(new TableQuery <InvalidTagResource>(), null);

                if (invalidTagResourcesQuery.Results != null)
                {
                    matchingInvalidResource = invalidTagResourcesQuery.Results.Where(x => x.Type == updateItem.Type).FirstOrDefault();
                }

                if (matchingInvalidResource == null)
                {
                    InvalidTagResource invalidItem = new InvalidTagResource
                    {
                        Type         = updateItem.Type,
                        Message      = ex.Message,
                        RowKey       = Guid.NewGuid().ToString(),
                        PartitionKey = updateItem.Subscription
                    };

                    TableOperation insertOperation = TableOperation.InsertOrReplace(invalidItem);
                    await invalidResourceTable.ExecuteAsync(insertOperation);
                }
            }
        }