public async Task AddTags(TagModel request)
        {
            var resourceManagerClient = new ResourcesManagementClient(request.SubscriptionId, _tokenCredential);
            var resourceGroupRequest  = await resourceManagerClient.ResourceGroups.GetAsync(request.ResourceGroupName);

            if (resourceGroupRequest == null)
            {
                return;
            }
            var resourceGroup = resourceGroupRequest.Value;

            try
            {
                foreach (var t in request.Tags)
                {
                    resourceGroup.Tags.TryAdd(t.Key, t.Value);
                }
                await resourceManagerClient.ResourceGroups.CreateOrUpdateAsync(resourceGroup.Name, resourceGroup);
            }
            catch (Exception ex)
            {
                // todo: what happens when tagging fails? what's recoverable? what's not?
                _log.LogError(ex, ex.Message);
            }
        }
Esempio n. 2
0
        public override void Execute()
        {
            #region SETUP
            ScenarioContext[] contexts = new ScenarioContext[] { new ScenarioContext(), new ScenarioContext("c9cbd920-c00c-427c-852b-8aaf38badaeb") };
            ParallelOptions   options  = new ParallelOptions
            {
                MaxDegreeOfParallelism = 1
            };

            Parallel.ForEach(contexts, options, context =>
            {
                var createMultipleVms = new CreateMultipleVms(context);
                createMultipleVms.Execute();
            });
            #endregion


            var rmClient = new ResourcesManagementClient(Context.SubscriptionId, Context.Credential);

            foreach (var sub in rmClient.Subscriptions.List())
            {
                var compute = new ComputeManagementClient(Context.SubscriptionId, Context.Credential);
                // since compute does not provide any filtering service side, filters must be applied client-side
                foreach (var vm in compute.VirtualMachines.ListAll().Where(v => v.Name.Contains("MyFilterString")))
                {
                    Console.WriteLine($"Found VM {vm.Name}");
                    Console.WriteLine("--------Stopping VM--------");
                    // It is somewhat awkward to have to parse the identity of the VM to get the resoource group to make this call
                    var resourceGroupName = GetResourceGroup(vm.Id);
                    compute.VirtualMachines.StartPowerOff(resourceGroupName, vm.Name).WaitForCompletionAsync().ConfigureAwait(false).GetAwaiter().GetResult();
                }
            }
        }
Esempio n. 3
0
        static async Task DeployInfra(string subscriptionId, string resourceGroupPrefix, IConsole console)
        {
            var client = new ResourcesManagementClient(subscriptionId, _credentials);

            var infraGroup = $"{resourceGroupPrefix}-infra";
            var vmGroup    = $"{resourceGroupPrefix}-vms";

            console.Out.Write($"Ensuring resource groups {infraGroup} and {vmGroup} exist\n");
            await client.ResourceGroups.CreateOrUpdateAsync(infraGroup, new ResourceGroup("westus2"));

            await client.ResourceGroups.CreateOrUpdateAsync(vmGroup, new ResourceGroup("westus2"));

            console.Out.Write($"Deploying resources to {infraGroup}\n");
            var template   = File.ReadAllText(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) !, "azuredeploy.json"));
            var parameters = await GetParametersContent(client, infraGroup);

            var properties = new DeploymentProperties(DeploymentMode.Incremental)
            {
                Template   = template,
                Parameters = parameters,
            };
            var deploymentOperation = await client.Deployments.StartCreateOrUpdateAsync(infraGroup, _deploymentName, new Deployment(properties));

            var deployment = await deploymentOperation.WaitForCompletionAsync();

            var outputs            = JsonDocument.Parse(JsonSerializer.Serialize(deployment.Value.Properties.Outputs)).RootElement;
            var storageAccountName = outputs.GetProperty("storageAccountName").GetProperty("value").GetString();

            console.Out.Write($"Deployed resources successfully {storageAccountName}, migrating SQL");
        }
Esempio n. 4
0
        public static async Task CreateResourceAsync(
            string subscriptionId,
            string resourceGroupName,
            string location)
        {
            Console.WriteLine("test");
            var credentials = new DefaultAzureCredential(true);

            //create
            var resourceGroupClient = new ResourcesManagementClient(subscriptionId, credentials).GetResourceGroupsClient();
            var resourceGroup       = new ResourceGroup(location);

            resourceGroup = await resourceGroupClient.CreateOrUpdateAsync("test_rng_name", resourceGroup);

            //var createdResourceGroup = res.Value;

            Console.WriteLine(resourceGroup.Name);

            //update
            var tags = new Dictionary <string, string>();

            tags.Add("env", "prod");
            tags.Add("scenario", "test");
            resourceGroup.Tags = tags;
            var updatedResourceGroup = await resourceGroupClient.CreateOrUpdateAsync("test_rng_name", resourceGroup);


            //get
            AsyncPageable <ResourceGroup> response = await resourceGroupClient.ListAsync();

            await foreach (ResourceGroupPatchable resourceGroup in response)
            {
                Console.WriteLine(resourceGroup.Name);
            }
        }
        private static async Task <ResourceGroup> SelectResourceGroupAsync(ResourcesManagementClient rmClient)
        {
            Console.WriteLine("Available groups:");
            var storageAccounts = new ConcurrentBag <ResourceGroup>();

            await foreach (var item in rmClient.ResourceGroups.ListAsync().ConfigureAwait(false))
            {
                Console.WriteLine($"{item.Name}");
                storageAccounts.Add(item);
            }

            Console.WriteLine("Select resource group:");
            var name = Console.ReadLine();

            while (!storageAccounts.Any(a => a.Name.Equals(name)))
            {
                Console.WriteLine($"Invalid resource group name: {name}.");
                Console.WriteLine("Select resource group:");
                name = Console.ReadLine();
            }

            var resourceGroup = storageAccounts.FirstOrDefault(a => a.Name.Equals(name));

            Console.WriteLine($"Selected resource group: {resourceGroup?.Name}.");
            return(resourceGroup);
        }
        static async Task Main(string[] args)
        {
            var subscriptionId = Environment.GetEnvironmentVariable("AZURE_SUBSCRIPTION_ID");
            var resourceClient = new ResourcesManagementClient(subscriptionId, new DefaultAzureCredential());

            // Create Resource Group
            Console.WriteLine("--------Start create group--------");
            var resourceGroups    = resourceClient.ResourceGroups;
            var location          = "westus2";
            var resourceGroupName = "QuickStartRG";
            var resourceGroup     = new ResourceGroup(location);

            resourceGroup = await resourceGroups.CreateOrUpdateAsync(resourceGroupName, resourceGroup);

            Console.WriteLine("--------Finish create group--------");

            // Create a Virtual Machine
            await Program.CreateVmAsync(subscriptionId, "QuickStartRG", location, "quickstartvm");

            // Delete resource group if necessary
            //Console.WriteLine("--------Start delete group--------");
            //await (await resourceGroups.StartDeleteAsync(resourceGroupName)).WaitForCompletionAsync();
            //Console.WriteLine("--------Finish delete group--------");
            //Console.ReadKey();
        }
        protected async Task initNewRecord()
        {
            Subscription sub = await ResourcesManagementClient.GetDefaultSubscriptionAsync();

            ResourceGroupsOperations = sub.GetResourceGroups();
            CosmosDBManagementClient = GetCosmosDBManagementClient();
        }
Esempio n. 8
0
        public override void Execute()
        {
            var createVm = new CreateSingleVmExample(Context);

            createVm.Execute();

            var rmClient      = new ResourcesManagementClient(Context.SubscriptionId, Context.Credential);
            var computeClient = new ComputeManagementClient(Context.SubscriptionId, Context.Credential);
            var rg            = rmClient.ResourceGroups.Get(Context.RgName).Value;

            foreach (var entity in rmClient.Resources.ListByResourceGroup(rg.Name, filter: "resourceType eq 'Microsoft.Compute/virtualMachines'"))
            {
                Console.WriteLine($"{entity.Name}");
                var vmUpdate = new VirtualMachineUpdate();
                foreach (var pair in entity?.Tags)
                {
                    vmUpdate.Tags.Add(pair.Key, pair.Value);
                }

                vmUpdate.Tags.Add("name", "value");

                // note that it is also possible to use the generic resource Update command, however,
                // this requires additional parameters that are difficult to discover, including rp-specific api-version
                computeClient.VirtualMachines.StartUpdate(rg.Name, entity.Name, vmUpdate).WaitForCompletionAsync().ConfigureAwait(false).GetAwaiter().GetResult();
            }
        }
Esempio n. 9
0
        public static void GetDatafactory(IAzure azure, DefaultAzureCredential credential, string subscriptionId, Microsoft.Azure.Management.ResourceManager.Fluent.Authentication.AzureCredentials credentials)
        {
            ResourcesManagementClient resourceClient     = new ResourcesManagementClient(subscriptionId, credential);
            Pageable <ResourceGroup>  listResourceGroups = resourceClient.ResourceGroups.List();

            //var rm = ResourceManager.Configure()
            //.WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
            //.Authenticate(credentials)
            //.WithDefaultSubscription();

            foreach (var Group in listResourceGroups)
            {
                Debug.WriteLine("Resource group: " + Group.Name);
                var resources = resourceClient.Resources.ListByResourceGroup(Group.Name);
                foreach (var rsrce in resources)
                {
                    //Debug.WriteLine(rsrce.Type);
                    if (String.Compare(rsrce.Type, "Microsoft.DataFactory/factories") == 0)
                    {
                        Debug.WriteLine("Resource Name" + rsrce.Name + " Resource Type" + rsrce.Type);
                    }
                }


                //var resourcename = resources.ListByResourceGroup(Group.Name);
                //var resources1=rm.GenericResources.List();
                //foreach (var resource in resourcename)
                //{
                //	Debug.WriteLine(resourcename);

                //}
            }
        }
        public static async Task RunSample(TokenCredential credential)
        {
            var rgName         = Utilities.RandomResourceName("rgRSAT", 24);
            var deploymentName = Utilities.RandomResourceName("dpRSAT", 24);
            var location       = "westus";
            var subscriptionId = Environment.GetEnvironmentVariable("AZURE_SUBSCRIPTION_ID");
            var templateJson   = Utilities.GetArmTemplate("ArmTemplate.json");

            var resourceClient = new ResourcesManagementClient(subscriptionId, credential);
            var resourceGroups = resourceClient.ResourceGroups;
            var deployments    = resourceClient.Deployments;

            try
            {
                //=============================================================
                // Create resource group.

                Utilities.Log("Creating a resource group with name: " + rgName);

                var resourceGroup = new ResourceGroup(location);
                resourceGroup = await resourceGroups.CreateOrUpdateAsync(rgName, resourceGroup);

                Utilities.Log("Created a resource group with name: " + rgName);

                //=============================================================
                // Create a deployment for an Azure App Service via an ARM
                // template.

                Utilities.Log("Starting a deployment for an Azure App Service: " + deploymentName);

                var parameters = new Deployment
                                 (
                    new DeploymentProperties(DeploymentMode.Incremental)
                {
                    Template   = templateJson,
                    Parameters = "{}"
                }
                                 );
                var rawResult = await deployments.StartCreateOrUpdateAsync(rgName, deploymentName, parameters);

                await rawResult.WaitForCompletionAsync();

                Utilities.Log("Completed the deployment: " + deploymentName);
            }
            finally
            {
                try
                {
                    Utilities.Log("Deleting Resource Group: " + rgName);

                    await(await resourceGroups.StartDeleteAsync(rgName)).WaitForCompletionAsync();

                    Utilities.Log("Deleted Resource Group: " + rgName);
                }
                catch (Exception ex)
                {
                    Utilities.Log(ex);
                }
            }
        }
Esempio n. 11
0
        public async Task Setup()
        {
            resourceGroupName = Guid.NewGuid().ToString();

            clientId       = ExternalVariables.Get(ExternalVariable.AzureSubscriptionClientId);
            clientSecret   = ExternalVariables.Get(ExternalVariable.AzureSubscriptionPassword);
            tenantId       = ExternalVariables.Get(ExternalVariable.AzureSubscriptionTenantId);
            subscriptionId = ExternalVariables.Get(ExternalVariable.AzureSubscriptionId);

            var resourceGroupLocation = Environment.GetEnvironmentVariable("AZURE_NEW_RESOURCE_REGION") ?? "eastus";

            authToken = await GetAuthToken(tenantId, clientId, clientSecret);

            var resourcesClient = new ResourcesManagementClient(subscriptionId,
                                                                new ClientSecretCredential(tenantId, clientId, clientSecret));

            resourceGroupClient = resourcesClient.ResourceGroups;

            var resourceGroup = new ResourceGroup(resourceGroupLocation);

            resourceGroup = await resourceGroupClient.CreateOrUpdateAsync(resourceGroupName, resourceGroup);

            webMgmtClient = new WebSiteManagementClient(new TokenCredentials(authToken))
            {
                SubscriptionId = subscriptionId,
                HttpClient     = { BaseAddress = new Uri(DefaultVariables.ResourceManagementEndpoint) },
            };

            var svcPlan = await webMgmtClient.AppServicePlans.BeginCreateOrUpdateAsync(resourceGroup.Name,
                                                                                       resourceGroup.Name, new AppServicePlan(resourceGroup.Location)
            {
                Kind     = "linux",
                Reserved = true,
                Sku      = new SkuDescription
                {
                    Name = "S1",
                    Tier = "Standard"
                }
            });

            site = await webMgmtClient.WebApps.BeginCreateOrUpdateAsync(resourceGroup.Name, resourceGroup.Name,
                                                                        new Site(resourceGroup.Location)
            {
                ServerFarmId = svcPlan.Id,
                SiteConfig   = new SiteConfig
                {
                    LinuxFxVersion = @"DOCKER|mcr.microsoft.com/azuredocs/aci-helloworld",
                    AppSettings    = new List <NameValuePair>
                    {
                        new NameValuePair("DOCKER_REGISTRY_SERVER_URL", "https://index.docker.io"),
                        new NameValuePair("WEBSITES_ENABLE_APP_SERVICE_STORAGE", "false")
                    },
                    AlwaysOn = true
                }
            });

            webappName = site.Name;

            await AssertSetupSuccessAsync();
        }
Esempio n. 12
0
        static async Task Main(string[] args)
        {
            string subscriptionId = Environment.GetEnvironmentVariable("AZURE_SUBSCRIPTION_ID");

            Console.WriteLine("Subscription ID:" + subscriptionId);
            var credential = new DefaultAzureCredential();

            var resourcesManagementClient = new ResourcesManagementClient(subscriptionId, credential);

            Console.WriteLine("Subscription : " + subscriptionId);

            Console.WriteLine("Welcome to AutoCloud.! Manage All your Cloud Infrastructure from Here.");
            Console.WriteLine("1. List Your Resources.");
            Console.WriteLine("2. Create a New Resource.");
            Console.WriteLine("3. Modify an Existing Resource");
            Console.WriteLine("4. Delete a Resource");
            Console.WriteLine("5. Configure your Cloud Account");
            Console.WriteLine("6. Exit");

            int action = 0;

            action = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine(action);
            switch (action)
            {
            case 1:
                Console.WriteLine("Listing your resources");
                await CreateResourceGroupAsync(resourcesManagementClient);

                break;

            default:
                break;
            }
        }
Esempio n. 13
0
        static void Main(string[] args)
        {
            Scenario scenario = null;

            try
            {
                scenario = ScenarioFactory.GetScenario(Scenarios.CreateSingleVmExample);
                scenario.Execute();
            }
            finally
            {
                var client = new ResourcesManagementClient(scenario.Context.SubscriptionId, scenario.Context.Credential);
                foreach (var rgId in Scenario.CleanUp)
                {
                    var name = GetResourceName(rgId);
                    try
                    {
                        var rg = client.ResourceGroups.Get(name).Value;
                        if (rg != null)
                        {
                            Console.WriteLine($"--------Deleting {rg.Name}--------");
                            _ = client.ResourceGroups.StartDelete(rg.Name).WaitForCompletionAsync().ConfigureAwait(false).GetAwaiter().GetResult();
                        }
                    }
                    catch
                    {
                        // ignore errors in get/delete
                    }
                }
            }
        }
        public async Task <Azure.ResourceManager.Resources.Models.ResourceGroup> GetResourceGroup(string subscriptionId,
                                                                                                  string resourceGroupName)
        {
            var resourceManagerClient = new ResourcesManagementClient(subscriptionId, _tokenCredential);
            var groupResponse         = await resourceManagerClient.ResourceGroups.GetAsync(resourceGroupName);

            return(groupResponse.Value);
        }
 // todo: explore changes required for using resource ID for _any_ resource
 public async Task DeleteResource(string subscriptionId, string resourceGroupName)
 {
     // todo: what-if? --> log deletion, but don't execute
     // connect to azure
     _log.LogInformation($"Request to delete {resourceGroupName} from subscription {subscriptionId}");
     var resourceManagerClient = new ResourcesManagementClient(subscriptionId, _tokenCredential);
     await resourceManagerClient.ResourceGroups.StartDeleteAsync(resourceGroupName);
 }
Esempio n. 16
0
 /// <summary>
 /// Generates the parameters content for azuredeploy.json. Specifies the SQL server password using
 /// a key vault reference if possible, otherwise generates a new password.
 /// </summary>
 /// <returns>The stringified parameters content</returns>
 static async Task <string> GetParametersContent(ResourcesManagementClient client, string resourceGroupName)
 {
     return(JsonSerializer.Serialize(new
     {
         sqlServerPassword = await GeneratePasswordParameter(client, resourceGroupName, "sqlServerPasswordName"),
         vmPassword = await GeneratePasswordParameter(client, resourceGroupName, "vmPasswordName"),
     }));
 }
        protected async Task InitializeClients()
        {
            SubscriptionId            = TestEnvironment.SubscriptionId;
            ResourcesManagementClient = GetResourceManagementClient();
            Subscription sub = await ResourcesManagementClient.GetDefaultSubscriptionAsync();

            ResourceGroupsOperations = sub.GetResourceGroups();
            CosmosDBManagementClient = GetCosmosDBManagementClient();
        }
Esempio n. 18
0
        /// <summary>
        /// Deletes the resource group (and all of its included resources).
        /// </summary>
        /// <param name="resourcesManagementClient">A credentialed ResourcesManagementClient.</param>
        /// <param name="resourceGroupName">The name of the resource group containing the storage account.</param>
        /// <returns></returns>
        private static async Task DeleteResourceGroupAsync(ResourcesManagementClient resourcesManagementClient, string resourceGroupName)
        {
            Console.WriteLine($"Deleting resource group {resourceGroupName}...");
            ResourceGroupsDeleteOperation deleteOperation = await resourcesManagementClient.ResourceGroups.StartDeleteAsync(resourceGroupName);

            await deleteOperation.WaitForCompletionAsync();

            Console.WriteLine("Done!");
        }
Esempio n. 19
0
        protected void InitializeClients()
        {
            SubscriptionId = TestEnvironment.SubscriptionId;
            Location       = TestEnvironment.Location;
            NotificationHubsResourceGroupName = TestEnvironment.NotificationHubsResourceGroupName;
            NotificationHubsResourceId        = TestEnvironment.NotificationHubsResourceId;
            NotificationHubsConnectionString  = TestEnvironment.NotificationHubsConnectionString;

            ResourcesManagementClient = GetResourceManagementClient();
        }
 public AzureClientInitializer(
     TokenCredential credential,
     StorageManagementClient storageManagementClient,
     ResourcesManagementClient resourcesManagementClient)
 {
     _credential = credential ?? throw new ArgumentNullException(nameof(credential));
     _storageManagementClient = storageManagementClient
                                ?? throw new ArgumentNullException(nameof(storageManagementClient));
     _resourcesManagementClient = resourcesManagementClient
                                  ?? throw new ArgumentNullException(nameof(resourcesManagementClient));
 }
Esempio n. 21
0
        /// <summary>
        /// Creates a new resource group with a random name.
        /// </summary>
        /// <param name="resourcesManagementClient">A credentialed ResourcesManagementClient.</param>
        /// <returns></returns>
        private static async Task <string> CreateResourceGroupAsync(ResourcesManagementClient resourcesManagementClient)
        {
            string resourceGroupName = RandomName("rg", 20);

            Console.WriteLine($"Creating resource group {resourceGroupName}...");
            await resourcesManagementClient.ResourceGroups.CreateOrUpdateAsync(resourceGroupName, new ResourceGroup(ResourceRegion));

            Console.WriteLine("Done!");

            return(resourceGroupName);
        }
        public async Task LinkNotificationHub()
        {
            // Setup resource group for the test. This resource group is deleted by CleanupResourceGroupsAsync after the test ends
            Subscription sub = await ResourcesManagementClient.GetDefaultSubscriptionAsync();

            var lro = await sub.GetResourceGroups().CreateOrUpdateAsync(
                NotificationHubsResourceGroupName,
                new ResourceGroupData(Location));

            ResourceGroup rg = lro.Value;

            CommunicationManagementClient acsClient = GetCommunicationManagementClient();
            var resourceName = Recording.GenerateAssetName("sdk-test-link-notif-hub-");

            // Create a new resource with a our test parameters
            CommunicationServiceCreateOrUpdateOperation result = await acsClient.CommunicationService.StartCreateOrUpdateAsync(
                rg.Data.Name,
                resourceName,
                new CommunicationServiceResource { Location = ResourceLocation, DataLocation = ResourceDataLocation });

            await result.WaitForCompletionAsync();

            // Check that our resource has been created successfully
            Assert.IsTrue(result.HasCompleted);
            Assert.IsTrue(result.HasValue);
            CommunicationServiceResource resource = result.Value;

            // Retrieve
            var resourceRetrieved = await acsClient.CommunicationService.GetAsync(rg.Data.Name, resourceName);

            Assert.AreEqual(
                resourceName,
                resourceRetrieved.Value.Name);
            Assert.AreEqual(
                "Succeeded",
                resourceRetrieved.Value.ProvisioningState.ToString());

            // Link NotificationHub
            var linkNotificationHubResponse = await acsClient.CommunicationService.LinkNotificationHubAsync(
                rg.Data.Name,
                resourceName,
                new LinkNotificationHubParameters(NotificationHubsResourceId, NotificationHubsConnectionString));

            Assert.AreEqual(NotificationHubsResourceId, linkNotificationHubResponse.Value.ResourceId);

            // Delete
            CommunicationServiceDeleteOperation deleteResult = await acsClient.CommunicationService.StartDeleteAsync(rg.Data.Name, resourceName);

            await deleteResult.WaitForCompletionAsync();

            // Check that our resource has been deleted successfully
            Assert.IsTrue(deleteResult.HasCompleted);
            Assert.IsTrue(deleteResult.HasValue);
        }
Esempio n. 23
0
        protected async Task initNewRecord()
        {
            ResourcesManagementClient = this.GetResourceManagementClient();
            //ResourcesOperations = ResourcesManagementClient.Resources;
            //ResourceProvidersOperations = ResourcesManagementClient.Providers;
            SubscriptionResource sub = await ResourcesManagementClient.GetDefaultSubscriptionAsync();

            ResourceGroupsOperations = sub.GetResourceGroups();
            DnsManagementClient      = this.GetDnsManagementClient();
            RecordSetsOperations     = DnsManagementClient.RecordSets;
            ZonesOperations          = DnsManagementClient.Zones;
        }
Esempio n. 24
0
        public async Task CreateVmss(ResourcesManagementClient resourcesClient, string resourceGroupName, string deploymentName)
        {
            string templateString = File.ReadAllText(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "TestData", "VmssDeploymentTemplate.json"));

            DeploymentProperties deploymentProperties = new DeploymentProperties(DeploymentMode.Incremental)
            {
                Template = templateString
            };
            Deployment deploymentModel = new Deployment(deploymentProperties);
            Operation <DeploymentExtended> deploymentWait = await resourcesClient.Deployments.StartCreateOrUpdateAsync(resourceGroupName, deploymentName, deploymentModel);

            await WaitForCompletionAsync(deploymentWait);
        }
Esempio n. 25
0
        protected async Task InitializeClients()
        {
            SubscriptionId            = TestEnvironment.SubscriptionId;
            ResourcesManagementClient = this.GetResourceManagementClient();
            //ResourcesOperations = ResourcesManagementClient.Resources;
            //ResourceProvidersOperations = ResourcesManagementClient.Providers;
            SubscriptionResource sub = await ResourcesManagementClient.GetDefaultSubscriptionAsync();

            ResourceGroupsOperations = sub.GetResourceGroups();
            DnsManagementClient      = this.GetDnsManagementClient();
            RecordSetsOperations     = DnsManagementClient.RecordSets;
            ZonesOperations          = DnsManagementClient.Zones;
        }
Esempio n. 26
0
        /// <summary>
        /// Main program.
        /// </summary>
        static async Task <int> Main()
        {
            string subscriptionId = Environment.GetEnvironmentVariable("AZURE_SUBSCRIPTION_ID");

            var credential = new DefaultAzureCredential();

            // Azure.ResourceManager.Resources is currently in preview.
            var resourcesManagementClient = new ResourcesManagementClient(subscriptionId, credential);

            // Azure.ResourceManager.Storage is currently in preview.
            var storageManagementClient = new StorageManagementClient(subscriptionId, credential);

            int       repeat = 0;
            const int total  = 3;

            while (++repeat <= total)
            {
                Console.WriteLine("Repeat #{0}...", repeat);
                try
                {
                    // Create a Resource Group
                    string resourceGroupName = await CreateResourceGroupAsync(resourcesManagementClient);

                    // Create a Storage account
                    string storageName = await CreateStorageAccountAsync(storageManagementClient, resourceGroupName);

                    // Create a container and upload a blob using a storage connection string
                    await UploadBlobUsingStorageConnectionStringAsync(storageManagementClient, resourceGroupName, storageName);

                    // Upload a blob using Azure.Identity.DefaultAzureCredential
                    await UploadBlobUsingDefaultAzureCredentialAsync(storageManagementClient, resourceGroupName, storageName, credential);

                    Console.WriteLine("Delete the resources...");

                    // Delete the resource group
                    await DeleteResourceGroupAsync(resourcesManagementClient, resourceGroupName);
                }
                catch (RequestFailedException ex)
                {
                    Console.WriteLine($"Request failed! {ex.Message} {ex.StackTrace}");
                    return(-1);
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Unexpected exception! {ex.Message} {ex.StackTrace}");
                    return(-1);
                }
            }
            Console.WriteLine("Success!");
            return(0);
        }
        public async Task <string> GetRawTagValue(string subscriptionId, string resourceGroupName, string tagName)
        {
            var resourceManagerClient = new ResourcesManagementClient(subscriptionId, _tokenCredential);
            var resourceGroupRequest  = await resourceManagerClient.ResourceGroups.GetAsync(resourceGroupName);

            if (resourceGroupRequest == null)
            {
                return(string.Empty);
            }
            var resourceGroup = resourceGroupRequest.Value;

            resourceGroup.Tags.TryGetValue(tagName, out var tagValue);
            return(tagValue ?? string.Empty);
        }
Esempio n. 28
0
 protected async Task CleanupResourceGroupsAsync()
 {
     if (CleanupPolicy != null && Mode != RecordedTestMode.Playback)
     {
         var resourceGroupsClient = new ResourcesManagementClient(
             TestEnvironment.SubscriptionId,
             TestEnvironment.Credential,
             new ResourcesManagementClientOptions()).ResourceGroups;
         foreach (var resourceGroup in CleanupPolicy.ResourceGroupsCreated)
         {
             await resourceGroupsClient.StartDeleteAsync(resourceGroup);
         }
     }
 }
        public async Task <string> ExportResourceGroupTemplateByName(string subscriptionId, string groupName)
        {
            // POST https://management.azure.com/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/exportTemplate?api-version=2020-06-01
            var resourceManagerClient = new ResourcesManagementClient(subscriptionId, _tokenCredential);
            var resourceTypesToExport = new Azure.ResourceManager.Resources.Models.ExportTemplateRequest();

            resourceTypesToExport.Resources.Add("*");
            var exportedTemplate = await resourceManagerClient.ResourceGroups.StartExportTemplateAsync(groupName, resourceTypesToExport);

            if (exportedTemplate.HasValue)
            {
                return((string)exportedTemplate.Value.Template);
            }
            return(string.Empty);
        }
        static async Task GetResourceGroups(DefaultAzureCredential credential, string subscriptionId)
        {
            // Create the resource client that will be used to fetch the resource groups
            ResourcesManagementClient resourceClient = new ResourcesManagementClient(subscriptionId, credential);


            // Fetch the resource groups and print them out to the screen
            Pageable <ResourceGroup> listResourceGroups = resourceClient.ResourceGroups.List();


            // Print out results to the console
            foreach (var Group in listResourceGroups)
            {
                Console.WriteLine("Resource group: " + Group.Name);
            }
        }