private static string createResourceGroupTry(string customerId, string subscriptionId, string groupName, string location) { string token = REST.getArmToken(customerId, UserAuth: true); if (token != null) { var credential = new TokenCredentials(token); var armClient = new Microsoft.Azure.Management.ResourceManager.ResourceManagementClient(credential) { SubscriptionId = subscriptionId }; var resourceGroup = new Microsoft.Azure.Management.ResourceManager.Models.ResourceGroup { Location = location }; try { var rg = armClient.ResourceGroups.CreateOrUpdate(groupName, resourceGroup); return(rg.Id.ToString()); } catch { return(null); } } else { return(null); } }
/// <summary> /// Ensures that a resource group with the specified name exists. If it does not, will attempt to create one. /// </summary> /// <param name="resourceManagementClient">The resource manager client.</param> /// <param name="resourceGroupName">The name of the resource group.</param> /// <param name="resourceGroupLocation">The resource group location. Required when creating a new resource group.</param> public async Task <ResourceGroup> EnsureResourceGroupExists(string resourceGroupName, string resourceGroupLocation, Tags tags) { ServiceClientCredentials serviceClientCredentials = await _authenticationHelper.GetServiceClientCredentials(ApplicationConstants.RESOURCE_URI.MANAGEMENT); Microsoft.Azure.Management.ResourceManager.ResourceManagementClient resourceManagementClient = new Microsoft.Azure.Management.ResourceManager.ResourceManagementClient(serviceClientCredentials); resourceManagementClient.SubscriptionId = _appSettings.Subscriptionid; if (!resourceManagementClient.ResourceGroups.CheckExistence(resourceGroupName)) { var resourceGroup = new ResourceGroup(); var keyValueTags = tags.GetTags(); resourceGroup.Tags = new Dictionary <string, string>(); if (tags != null && keyValueTags.Count > 0) { foreach (KeyValuePair <string, string> tag in keyValueTags) { resourceGroup.Tags.Add(tag); } } resourceGroup.Location = resourceGroupLocation; return(await resourceManagementClient.ResourceGroups.CreateOrUpdateAsync(resourceGroupName, resourceGroup)); } else { return(await resourceManagementClient.ResourceGroups.GetAsync(resourceGroupName)); } }
private async Task CreateOrUpdateResourceGroupAsync(AzureCredentials credentials, string location) { using (var resourceClient = new Microsoft.Azure.Management.ResourceManager.ResourceManagementClient(credentials)) { var parameter = new ResourceGroup(); parameter.Location = location; parameter.Name = resourceGroup; resourceClient.SubscriptionId = subscriptionId; await resourceClient.ResourceGroups.CreateOrUpdateAsync(resourceGroup, parameter); } }
// ---------- public IEnumerable <MSAZURERM.Models.ResourceGroup> ListResourceGroups(string subid) { var rm_client = new MSAZURERM.ResourceManagementClient(this.Authentication.ArmCreds); rm_client.SubscriptionId = subid; var rgs = rm_client.ResourceGroups.List(); foreach (var rg in rgs) { yield return(rg); } }
public static async Task <bool> DeleteResourceGroupAsync(string customerId, string subscriptionId, string groupName) { string token = await REST.getArmTokenAsync(customerId, UserAuth : true); if (token != null) { var credential = new TokenCredentials(token); var armClient = new Microsoft.Azure.Management.ResourceManager.ResourceManagementClient(credential) { SubscriptionId = subscriptionId }; armClient.ResourceGroups.Delete(groupName); return(true); } return(false); }
/// <summary> /// Assigns role to main resource group and newly created resource group /// </summary> /// <param name="mainResourceGroup"></param> /// <param name="ppcReaderRoleId"></param> /// <param name="resourceGroup"></param> /// <param name="contributorRoleId"></param> /// <param name="adGroupId"></param> /// <returns></returns> public async Task AssignRoles(string mainResourceGroup, string ppcReaderRoleId, string resourceGroup, string contributorRoleId, string adGroupId) { ServiceClientCredentials serviceClientCredentials = await _authenticationHelper.GetServiceClientCredentials(ApplicationConstants.RESOURCE_URI.MANAGEMENT); Microsoft.Azure.Management.ResourceManager.ResourceManagementClient resourceManagementClient = new Microsoft.Azure.Management.ResourceManager.ResourceManagementClient(serviceClientCredentials); resourceManagementClient.SubscriptionId = _appSettings.Subscriptionid; ResourceGroup mainRG = await resourceManagementClient.ResourceGroups.GetAsync(mainResourceGroup); await AssignRoles(mainRG.Id, ppcReaderRoleId, adGroupId); ResourceGroup rg = await resourceManagementClient.ResourceGroups.GetAsync(resourceGroup); await AssignRoles(rg.Id, contributorRoleId, adGroupId); }
// Get public IP addresses out of a resource group in Azure public static List <ARM.IpAddress> GetPublicIps(string customerId, string subscriptionId, string groupName) { // Initialize List <IpAddress> output = new List <IpAddress>(); // Get token from ARM API string token = REST.getArmTokenSync(customerId, UserAuth: true); var credential = new TokenCredentials(token); var armClient = new Microsoft.Azure.Management.ResourceManager.ResourceManagementClient(credential) { SubscriptionId = subscriptionId }; // Get resources in resource group var resourceList = armClient.Resources.ListByResourceGroup(groupName).ToList(); foreach (var resource in resourceList) { if (resource.Type == "Microsoft.Network/publicIPAddresses") { //var thisresource = armClient.Resources.GetById(resource.Id); var thisresource = armClient.Resources.GetById(resource.Id, "2018-02-01"); string jsonstring = thisresource.Properties.ToString(); JToken jtoken = JObject.Parse(jsonstring); string ipAddress = (string)jtoken.SelectToken("ipAddress"); if (!thisresource.Name.Contains("slb")) { ARM.IpAddress newIp = new ARM.IpAddress(); newIp.Address = ipAddress; newIp.Name = thisresource.Name.Replace("-pip", ""); output.Add(newIp); } } } // Return everything return(output); }
public static async Task registerRSAsync(string customerId, string subscriptionId, string rpName) { string token = await REST.getArmTokenAsync(customerId, UserAuth : true); var credential = new TokenCredentials(token); var armClient = new Microsoft.Azure.Management.ResourceManager.ResourceManagementClient(credential) { SubscriptionId = subscriptionId }; bool rpRegistered = false; // Check the registration state until it is Registered. Wait 5 seconds before each retry do { var RPlist = (await armClient.Providers.ListAsync()).ToList(); foreach (var provider in RPlist) { if (provider.NamespaceProperty == rpName) { if (provider.RegistrationState == "NotRegistered") { await armClient.Providers.RegisterAsync(rpName); } else { if (provider.RegistrationState == "Registered") { rpRegistered = true; } else { Thread.Sleep(5000); } } } } } while (rpRegistered == false); }
public void UsingAzureCredentials() { var azureAuthenticator = new AzureAuthenticator(); var azureCredentials = azureAuthenticator.GetAzureCredentials(); var azureFluent = Azure.Authenticate(azureCredentials).WithDefaultSubscription(); var resourceGroups = azureFluent.ResourceGroups.List(); foreach (var resourceGroup in resourceGroups) { Console.WriteLine($"I found resource group {resourceGroup.Name} in subscription {_subscriptionName}"); } var resourceManagementClient = new ResourceManagementClient(azureCredentials) { SubscriptionId = azureFluent.SubscriptionId }; var resources = resourceManagementClient.Resources.List(); foreach (var resource in resources) { Console.WriteLine($"I found resource group {resource.Name} in subscription {_subscriptionName}"); } }
public static async Task <string> createVMsAsync(string customerId, string subscriptionId, string groupName, string vmName, string location) { // Get Template into a string // Otherwise, the property "TemplateLink" might be used as well in the deployment creation // See https://docs.microsoft.com/en-us/dotnet/api/microsoft.azure.management.resourcemanager.models.deploymentproperties.templatelink?view=azure-dotnet var myTemplate = ""; string templateUrl = "https://raw.githubusercontent.com/erjosito/AzureBlackMagic/master/genericLinuxVM-count-templ.json"; var webRequest = System.Net.WebRequest.Create(templateUrl); using (var response = webRequest.GetResponse()) using (var content = response.GetResponseStream()) using (var reader = new StreamReader(content)) { myTemplate = reader.ReadToEnd(); } // Get token from ARM API string token = await REST.getArmTokenAsync(customerId, UserAuth : true); var credential = new TokenCredentials(token); var armClient = new Microsoft.Azure.Management.ResourceManager.ResourceManagementClient(credential) { SubscriptionId = subscriptionId }; // Define parameters for template string vmAdminUsername = System.Configuration.ConfigurationManager.AppSettings["vmAdminUsername"]; string vmAdminPassword = System.Configuration.ConfigurationManager.AppSettings["vmAdminPassword"]; var myParameters = new Dictionary <string, Dictionary <string, object> > { { "vmName", new Dictionary <string, object> { { "value", vmName } } }, { "vmType", new Dictionary <string, object> { { "value", "centos" } } }, { "vmSize", new Dictionary <string, object> { { "value", "Standard_B1s" } } }, { "installExtension", new Dictionary <string, object> { { "value", "yes" } } }, { "adminUsername", new Dictionary <string, object> { { "value", vmAdminUsername } } }, { "adminPassword", new Dictionary <string, object> { { "value", vmAdminPassword } } }, { "vmCount", new Dictionary <string, object> { { "value", 5 } } }, }; // Create resource group var resourceGroupResponse = await armClient.ResourceGroups.CreateOrUpdateAsync(groupName, new Microsoft.Azure.Management.ResourceManager.Models.ResourceGroup { Location = location }); // Deploy template // The try loop should catch ARM deployment timeouts try { /* * Task<Microsoft.Azure.Management.ResourceManager.Models.DeploymentExtended> deploymentTask = armClient.Deployments.CreateOrUpdateAsync(groupName, vmName, * new Microsoft.Azure.Management.ResourceManager.Models.Deployment * { * Properties = new Microsoft.Azure.Management.ResourceManager.Models.DeploymentProperties * { * Mode = Microsoft.Azure.Management.ResourceManager.Models.DeploymentMode.Incremental, * Template = myTemplate, * Parameters = myParameters * } * }); * * ForgetTask(deploymentTask); */ Task.Run(() => armClient.Deployments.CreateOrUpdateAsync(groupName, vmName, new Microsoft.Azure.Management.ResourceManager.Models.Deployment { Properties = new Microsoft.Azure.Management.ResourceManager.Models.DeploymentProperties { Mode = Microsoft.Azure.Management.ResourceManager.Models.DeploymentMode.Incremental, Template = myTemplate, Parameters = myParameters } })); /* * var hasSucceeded = deploymentExtended.Properties.ProvisioningState == "Succeeded"; * if (hasSucceeded) * { * return vmName; * } * else * { * return null; * } */ return(null); } catch { return(null); } }
/// <summary> /// Deploy the template from the template file template.json. Write the keys returned by the deployment into files /// </summary> public static void DeployTemplate() { spin.setMessage("Deploying Template..."); spin.Start(); // string templatePath = "https://" + acccountStorageName + ".blob.core.windows.net/templates/templateIotHub.json"; // string paramPath = "https://" + acccountStorageName + ".blob.core.windows.net/templates/parameters.json"; // var deployment = azure.Deployments.Define("Deployment_01") // .WithExistingResourceGroup(resourceGroup) // .WithTemplateLink(templatePath, "1.0.0.0") // .WithParametersLink(paramPath, "1.0.0.0") // .WithMode(DeploymentMode.Incremental) // .Create(); // IDeployment toto = await azure.Deployments.GetByNameAsync("Deployment_01"); Microsoft.Azure.Management.ResourceManager.ResourceManagementClient client; var authContext = new AuthenticationContext(string.Format("https://login.microsoftonline.com/{0}", tenantId)); var credential = new ClientCredential(applicationId, password); AuthenticationResult token = authContext.AcquireTokenAsync("https://management.core.windows.net/", credential).Result; if (token == null) { Console.WriteLine("Failed to obtain the token"); return; } var creds = new TokenCredentials(token.AccessToken); client = new Microsoft.Azure.Management.ResourceManager.ResourceManagementClient(creds); client.SubscriptionId = subscriptionId; var createResponse = client.Deployments.CreateOrUpdate(rgName, deploymentName, new Microsoft.Azure.Management.ResourceManager.Models.Deployment() { Properties = new DeploymentProperties { Mode = Microsoft.Azure.Management.ResourceManager.Models.DeploymentMode.Incremental, TemplateLink = new Microsoft.Azure.Management.ResourceManager.Models.TemplateLink { Uri = "https://" + accountStorageName + ".blob.core.windows.net/templates/template.json" }, ParametersLink = new Microsoft.Azure.Management.ResourceManager.Models.ParametersLink { Uri = "https://" + accountStorageName + ".blob.core.windows.net/templates/parameters.json" } } }); spin.Stop(); string state = createResponse.Properties.ProvisioningState; Console.WriteLine("Deployment state: {0}", state); if (state != "Succeeded") { Console.WriteLine("Failed to deploy the template"); } Console.WriteLine(createResponse.Properties.Outputs); WriteKeysIntoFiles(createResponse.Properties.Outputs); Console.WriteLine("Done"); //Console.ReadLine(); }
public static async Task CreateVmAsync( string subscriptionId, string resourceGroup, string location, string vmName) { var credentials = SdkContext.AzureCredentialsFactory .FromFile("azureauth.properties"); var resourceClient = new ResourceManagementClient(credentials); var networkClient = new NetworkManagementClient(credentials); var computeClient = new ComputeManagementClient(credentials); resourceClient.SubscriptionId = subscriptionId; networkClient.SubscriptionId = subscriptionId; computeClient.SubscriptionId = subscriptionId; // Create Resource Group await resourceClient.ResourceGroups.CreateOrUpdateAsync(resourceGroup, new ResourceGroup(location)); // Create Availability Set var availabilitySet = new AvailabilitySet(location) { PlatformUpdateDomainCount = 5, PlatformFaultDomainCount = 2, Sku = new Sku("Aligned"), }; availabilitySet = await computeClient.AvailabilitySets .CreateOrUpdateAsync(resourceGroup, vmName + "_aSet", availabilitySet); // Create IP Address var ipAddress = new PublicIPAddress() { PublicIPAddressVersion = IPVersion.IPv4, PublicIPAllocationMethod = IPAllocationMethod.Dynamic, Location = location, }; ipAddress = await networkClient .PublicIPAddresses.BeginCreateOrUpdateAsync(resourceGroup, vmName + "_ip", ipAddress); // Create VNet var vnet = new VirtualNetwork() { Location = location, AddressSpace = new AddressSpace() { AddressPrefixes = new List <string>() { "10.0.0.0/16" } }, Subnets = new List <Subnet>() { new Subnet() { Name = "mySubnet", AddressPrefix = "10.0.0.0/24", } }, }; vnet = await networkClient.VirtualNetworks .BeginCreateOrUpdateAsync(resourceGroup, vmName + "_vent", vnet); // Create Network interface var nic = new NetworkInterface() { Location = location, IpConfigurations = new List <NetworkInterfaceIPConfiguration>() { new NetworkInterfaceIPConfiguration() { Name = "Primary", Primary = true, Subnet = new Subnet() { Id = vnet.Subnets.First().Id }, PrivateIPAllocationMethod = IPAllocationMethod.Dynamic, PublicIPAddress = new PublicIPAddress() { Id = ipAddress.Id } } } }; nic = await networkClient.NetworkInterfaces .BeginCreateOrUpdateAsync(resourceGroup, vmName + "_nic", nic); var vm = new VirtualMachine(location) { NetworkProfile = new NetworkProfile { NetworkInterfaces = new[] { new NetworkInterfaceReference() { Id = nic.Id } } }, AvailabilitySet = new SubResource { Id = availabilitySet.Id }, OsProfile = new OSProfile { ComputerName = "testVM", AdminUsername = "******", AdminPassword = "******", LinuxConfiguration = new LinuxConfiguration { DisablePasswordAuthentication = false, ProvisionVMAgent = true } }, StorageProfile = new StorageProfile() { ImageReference = new ImageReference() { Offer = "UbuntuServer", Publisher = "Canonical", Sku = "18.04-LTS", Version = "latest" }, DataDisks = new List <DataDisk>() }, HardwareProfile = new HardwareProfile() { VmSize = VirtualMachineSizeTypes.StandardB1ms }, }; await computeClient.VirtualMachines.BeginCreateOrUpdateAsync(resourceGroup, vmName, vm); }