public static async Task <IAuthenticated> GetAzureClient(ILogger log) { if (_azureClient == null || DateTime.UtcNow >= _tokenExpiry) { if (DateTime.UtcNow >= _tokenExpiry) { log.LogInformation($"Renewing token at {DateTime.UtcNow.ToLongDateString()}"); } else { log.LogInformation($"Creating new azureclient at {DateTime.UtcNow.ToLongDateString()}"); } var tenantId = Environment.GetEnvironmentVariable("tenantId"); var tokenCredentials = new TokenCredentials(await _azureServiceTokenProvider.GetAccessTokenAsync("https://management.azure.com/")); var azureCredentials = new AzureCredentials( tokenCredentials, tokenCredentials, tenantId, AzureEnvironment.AzureGlobalCloud); var client = RestClient .Configure() .WithEnvironment(AzureEnvironment.AzureGlobalCloud) .WithLogLevel(HttpLoggingDelegatingHandler.Level.BodyAndHeaders) .WithCredentials(azureCredentials) .Build(); _tokenExpiry = DateTime.UtcNow.AddMinutes(15); _azureClient = Azure.Authenticate(client, tenantId); } return((IAuthenticated)_azureClient); }
internal async Task SetupServiceBus() { var token = new AzureServiceTokenProvider().GetAccessTokenAsync("https://management.core.windows.net/", string.Empty).Result; var tokenCredentials = new TokenCredentials(token); var client = RestClient.Configure() .WithEnvironment(AzureEnvironment.AzureGlobalCloud) .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic) .WithCredentials(new AzureCredentials(tokenCredentials, tokenCredentials, string.Empty, AzureEnvironment.AzureGlobalCloud)) .Build(); var sbNamespace = Azure.Authenticate(client, string.Empty) .WithSubscription(_settings.AzureSubscriptionId) .ServiceBusNamespaces.List() .SingleOrDefault(n => n.Name == _settings.ServiceBusNamespace); if (sbNamespace == null) { throw new InvalidOperationException($"Couldn't find the service bus namespace {_settings.ServiceBusNamespace} in the subscription with ID {_settings.AzureSubscriptionId}"); } var azureTopic = await sbNamespace.CreateTopicIfNotExists(TypeExtensions.GetEntityName(Id.GetStringId())); await azureTopic.CreateSubscriptionIfNotExists(SubscriptionName); }
public static async Task <IAuthenticated> GetAzureClient(TrialResource resource, ILogger log) { if (_azureClient == null || DateTime.UtcNow >= _tokenExpiry) { if (DateTime.UtcNow >= _tokenExpiry) { log.LogInformation($"Renewing token at {DateTime.UtcNow.ToLongDateString()}"); } else { log.LogInformation($"Creating new azureclient at {DateTime.UtcNow.ToLongDateString()}"); } var tenantId = resource.TenantId; var tokenCredentials = new TokenCredentials(await _azureServiceTokenProvider.GetAccessTokenAsync("https://management.azure.com/")); var azureCredentials = new AzureCredentials( tokenCredentials, tokenCredentials, tenantId, AzureEnvironment.FromName(resource.Template.AzureEnvironment)); var client = RestClient .Configure() .WithEnvironment(AzureEnvironment.FromName(resource.Template.AzureEnvironment)) .WithLogLevel(resource.Template.DeploymentLoggingLevel.ToEnum <HttpLoggingDelegatingHandler.Level>()) .WithCredentials(azureCredentials) .Build(); _tokenExpiry = DateTime.UtcNow.AddMinutes(30); _azureClient = Azure .Authenticate(client, tenantId); } return((IAuthenticated)_azureClient); }
public bool AddAccount(string accountName, string clientid, string clientsecretkey, string tenantid, string subscriptionid) { try { AzureProfile azure = new AzureProfile(); azure.ClientId = clientid; azure.ClientSecretKey = clientsecretkey; azure.TenantId = tenantid; azure.SubscriptionId = subscriptionid; var credentials = SdkContext.AzureCredentialsFactory.FromServicePrincipal(clientid, clientsecretkey, tenantid, AzureEnvironment.AzureGlobalCloud); var response = Azure.Authenticate(credentials).WithSubscription(subscriptionid); if (response.ResourceGroups.List().Count() > 0) { if (SqlHelper.AddNewAccount("Azure", accountName) && SqlHelper.AddAzureAccountDetails(azure, accountName)) { return(true); } return(false); } return(false); } catch (Exception e) { return(false); } }
/// <summary> /// Attempts to refresh the stored <see cref="IServiceBusNamespace"/> fluent construct. /// Will do a full rebuild if any type of failure occurs during the refresh. /// </summary> /// <returns>The refreshed <see cref="IServiceBusNamespace"/>.</returns> internal async Task <IServiceBusNamespace> GetRefreshedServiceBusNamespace() { try { if (AzureServiceBusNamespace != null) { return(await AzureServiceBusNamespace.RefreshAsync().ConfigureAwait(false)); } } catch { /* soak */ } var token = await new AzureServiceTokenProvider().GetAccessTokenAsync("https://management.core.windows.net/", string.Empty).ConfigureAwait(false); var tokenCredentials = new TokenCredentials(token); var client = RestClient.Configure() .WithEnvironment(AzureEnvironment.AzureGlobalCloud) .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic) .WithCredentials(new AzureCredentials(tokenCredentials, tokenCredentials, string.Empty, AzureEnvironment.AzureGlobalCloud)) .Build(); AzureServiceBusNamespace = (await Azure.Authenticate(client, string.Empty) .WithSubscription(SubscriptionId) .ServiceBusNamespaces.ListAsync() .ConfigureAwait(false)) .SingleOrDefault(n => n.Name == NamespaceName); if (AzureServiceBusNamespace == null) { throw new InvalidOperationException($"Couldn't find the service bus namespace {NamespaceName} in the subscription with ID {SubscriptionId}"); } return(AzureServiceBusNamespace); }
public static async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)] HttpRequest req, ILogger log) { log.LogInformation("C# HTTP trigger function processed status request."); var clientId = Environment.GetEnvironmentVariable("AZURE_CLIENT_ID", EnvironmentVariableTarget.Process); var clientSecret = Environment.GetEnvironmentVariable("AZURE_CLIENT_SECRET", EnvironmentVariableTarget.Process); var tenantId = Environment.GetEnvironmentVariable("AZURE_TENANT_ID", EnvironmentVariableTarget.Process); var vmId = Environment.GetEnvironmentVariable("AZURE_VM_ID", EnvironmentVariableTarget.Process); if (string.IsNullOrEmpty(clientId) || string.IsNullOrEmpty(clientSecret) || string.IsNullOrEmpty(tenantId) || string.IsNullOrEmpty(vmId)) { return(new StatusCodeResult(StatusCodes.Status501NotImplemented)); } var credentials = SdkContext.AzureCredentialsFactory.FromServicePrincipal(clientId, clientSecret, tenantId, AzureEnvironment.AzureGlobalCloud); var azure = await Azure.Authenticate(credentials).WithDefaultSubscriptionAsync(); var vm = await azure.VirtualMachines.GetByIdAsync(vmId); if (vm == null) { return(new NotFoundResult()); } return(new OkObjectResult(vm.PowerState.ToString())); }
private IAzure GetAzureContext(string authFilePath) { IAzure azure; try { var currentDirectory = Directory.GetCurrentDirectory(); Logger.Info($"Current directory is: {currentDirectory}"); Logger.Info($"Current function directory is: {_functionDirectory}"); var azureFilePath = Path.Combine(_functionDirectory, authFilePath); Logger.Info($"Authenticating with Azure using credentials in file at {azureFilePath}"); azure = Azure.Authenticate(azureFilePath).WithDefaultSubscription(); var currentSubscription = azure.GetCurrentSubscription(); Logger.Info($"Authenticated with subscription '{currentSubscription.DisplayName}' (ID: {currentSubscription.SubscriptionId})"); } catch (Exception ex) { Logger.Error($"\nFailed to authenticate:\n{ex.Message}"); if (string.IsNullOrEmpty(authFilePath)) { Logger.Error("Have you set the AZURE_AUTH_LOCATION environment variable?"); } throw; } return(azure); }
public void GetResourceGroups() { //Build the base fluent API client again so that we can use a specific subscription var clientSub = RestClient .Configure() .WithEnvironment(AzureEnvironment.AzureGlobalCloud) .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic) .WithCredentials(authContext.FluentCredential) .Build(); //Connect to specific Azure subscription var azureAuthTargetSub = Azure .Authenticate(clientSub, authContext.TenentId) .WithSubscription(SelectedSubscription); ResourceGroups = new Dictionary <string, string>(); //List all resource groups in the subscription we have permissions to see foreach (var resourceGroup in azureAuthTargetSub.ResourceGroups.List()) { Debug.WriteLine($"Resource Group: {resourceGroup.Name} - {resourceGroup.RegionName}"); ResourceGroups.Add(resourceGroup.Id, resourceGroup.Name); } OnNotify("ResourceGroups"); }
public static string CreateAciGroup([ActivityTrigger] Tuple <string, string> args, ILogger log) { var creds = new AzureCredentialsFactory().FromServicePrincipal(Environment.GetEnvironmentVariable("client"), Environment.GetEnvironmentVariable("key"), Environment.GetEnvironmentVariable("tenant"), AzureEnvironment.AzureGlobalCloud); var azure = Azure.Authenticate(creds).WithSubscription(Environment.GetEnvironmentVariable("subscriptionId")); return(CreateContainerGroup(azure, "azure-poc-rg", "extractor" + args.Item1, Environment.GetEnvironmentVariable("d"), args.Item2)); }
private static IAzure GetAzureContext() { IAzure azure = Azure.Authenticate("my.azureauth").WithDefaultSubscription(); var currentSubscription = azure.GetCurrentSubscription(); return(azure); }
/* * Input: AzureResourceInformation, KeyVaultInformation, Logger * Get the necessary credential information for VM management and KeyVault access. */ private async Task Initialize(AzureResourceInformation resourceInfo, KeyVaultInformation vault, ILogger log) { var azureServiceTokenProvider = new AzureServiceTokenProvider(); _kv = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback)); string _id = (await _kv.GetSecretAsync(vault.KeyVaultUri, vault.KV_SecretName_ServicePrinciple)).Value; string _cred = (await _kv.GetSecretAsync(vault.KeyVaultUri, vault.KV_SecretName_ServicePrinciplePwd)).Value; // Get the LabResourceGroup resourceInfo.LabResourceGroup = ParseLabResourceGroup(resourceInfo.ResourceUri); resourceInfo.LabName = await GetLabName(resourceInfo, log); AzureCredentials _azureCred = SdkContext.AzureCredentialsFactory.FromServicePrincipal( _id, _cred, resourceInfo.TenantId, AzureEnvironment.AzureGlobalCloud); _msiazure = Azure.Authenticate(_azureCred).WithSubscription(resourceInfo.SubscriptionId); _clientCred = new ClientCredential(_id, _cred); var context = new AuthenticationContext($"https://login.windows.net/{resourceInfo.TenantId}", false); var token = await context.AcquireTokenAsync("https://management.azure.com/", _clientCred); _accessToken = token.AccessToken; }
private static IAzure GetAzure() { var tokenProvider = new AzureServiceTokenProvider(); var appAuthCreds = new AppAuthenticationAzureCredentials(tokenProvider, AzureEnvironment.AzureGlobalCloud); return(Azure.Authenticate(appAuthCreds).WithDefaultSubscription()); }
public async Task <IAzure> GetAzureContextFromManagedIdentityAsync() { IAzure azure; ISubscription subscription; var azureServiceTokenProvider = new AzureServiceTokenProvider(); var accessToken = await azureServiceTokenProvider.GetAccessTokenAsync("https://management.azure.com/").ConfigureAwait(false); var restTokenCredentials = new Microsoft.Rest.TokenCredentials(accessToken); var azCred = new AzureCredentials(restTokenCredentials, null, this.configuration.AadTenantId, AzureEnvironment.AzureGlobalCloud); var rest = RestClient.Configure().WithEnvironment(AzureEnvironment.AzureGlobalCloud).WithCredentials(azCred).Build(); try { this.logger.LogDebug($"Authenticating with Azure"); azure = Azure.Authenticate(rest, this.configuration.AadTenantId).WithSubscription(this.configuration.AzureSubscriptionId); subscription = azure.GetCurrentSubscription(); } catch (Exception ex) { this.logger.LogError($"Failed to authenticate with Auzre: {ex.Message}"); throw; } this.logger.Log(LogLevel.Debug, $"Successfully authenticated with Azure subscription {subscription.DisplayName}"); return(azure); }
public static IAzure GetAzureInterface(HttpRequest req, RequestBody requestBody) { //Obtain Function Config from Environment Vars string alwaysEmpty = Environment.GetEnvironmentVariable("NeverExists"); string servicePrincipalClientId = Environment.GetEnvironmentVariable("ServicePrincipal_clientId"); string servicePrincipalClientSecret = Environment.GetEnvironmentVariable("ServicePrincipal_clientSecret"); string servicePrincipalTenantId = Environment.GetEnvironmentVariable("ServicePrincipal_tenantId"); //Generating Credential Factory to generate Azure login credentials var credentialsFactory = new AzureCredentialsFactory(); AzureCredentials azureCredentials; if (servicePrincipalClientId != null && servicePrincipalClientSecret != null && servicePrincipalTenantId != null) { //Use servicePrincipal auth for local debugging azureCredentials = credentialsFactory.FromServicePrincipal(servicePrincipalClientId, servicePrincipalClientSecret, servicePrincipalTenantId, AzureEnvironment.AzureGlobalCloud); } else { //Authenticate to Azure using the Azure SDK and Azure Functions "system assigned managed Identity" //Setup of managed Identity needs to be done in the Function settings in the portal or via CLI azureCredentials = credentialsFactory.FromSystemAssignedManagedServiceIdentity(MSIResourceType.AppService, AzureEnvironment.AzureGlobalCloud); } //Authenticate with Azure Credentials to get a working Azure interface (here saved as azure) return(Azure.Authenticate(azureCredentials).WithSubscription(requestBody.subscriptionId)); }
public static void Run([TimerTrigger("0 * * * * *")] TimerInfo myTimer, ILogger log, ExecutionContext context) { _log = log; _cfg = new ConfigurationBuilder() .SetBasePath(context.FunctionAppDirectory) .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true) .AddEnvironmentVariables() .Build(); var creds = SdkContext.AzureCredentialsFactory.FromServicePrincipal(_cfg["CLIENT_ID"], _cfg["CLIENT_SECRET"], _cfg["TENANT_ID"], AzureEnvironment.AzureGlobalCloud); _azure = Azure.Authenticate(creds).WithSubscription(_cfg["SUBSCRIPTION_ID"]); // TODO: Check if another function is already running, and exit so we don't overlap // Azure Functions may already handle this - not sure // TODO: Need to detect if VM creation/deletion fails and cleanup appropriately using (_db = new SqlConnection(_cfg.GetConnectionString("SqlConnectionString"))) { UpdateBuildAgents().Wait(); ReplenishAgentPool().Wait(); } }
private static IAzure GetAzureContext(string authFilePath) { IAzure azure; ISubscription sub; try { Logger.Log($"Authenticating with Azure using credentials in file at {authFilePath}"); azure = Azure.Authenticate(authFilePath).WithDefaultSubscription(); sub = azure.GetCurrentSubscription(); Logger.Log($"Authenticated with subscription '{sub.DisplayName}' (ID: {sub.SubscriptionId})"); } catch (Exception ex) { Logger.Log($"\nFailed to authenticate:\n{ex.Message}"); if (String.IsNullOrEmpty(authFilePath)) { Logger.Log("Have you set the AZURE_AUTH_LOCATION environment variable?"); } throw; } return(azure); }
public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequestMessage req, TraceWriter log, ExecutionContext executionContext) { log.Info("SetAppService started"); string setAppServiceRequestJson = await req.Content.ReadAsStringAsync(); if (!string.IsNullOrEmpty(setAppServiceRequestJson)) { var setAppServiceRequest = JsonConvert.DeserializeObject <SetAppServicePlanRequest>(setAppServiceRequestJson); var appServicePlanName = "#YOURAPPSERVICEPLANNAME#"; var authFile = $"{Directory.GetParent(executionContext.FunctionDirectory).FullName}\\my.azureauth"; var azure = Azure.Authenticate(authFile).WithDefaultSubscription(); var appServicePlan = azure.AppServices.AppServicePlans.List().FirstOrDefault(x => x.Name == appServicePlanName); log.Info(executionContext.FunctionDirectory); PricingTier pricingTier = new PricingTier(setAppServiceRequest.Tier, setAppServiceRequest.Size); //Basic, B1 int capacity = setAppServiceRequest.Capacity; appServicePlan?.Update() .WithPricingTier(pricingTier) .WithCapacity(capacity) .Apply(); return(req.CreateResponse(HttpStatusCode.OK, "SetAppService Successfully Competed")); } else { return(req.CreateResponse(HttpStatusCode.BadRequest, "Something went wrong!")); } }
/// <summary> /// Deletes the storage account. /// </summary> /// <param name="credentials">The credentials.</param> /// <param name="subscriptionId">The subscription identifier.</param> /// <param name="resourceGroup">The resource group.</param> /// <param name="storageAccountName">Name of the storage account.</param> /// <returns>The task.</returns> public async Task DeleteStorageAccount( AzureCredentials credentials, string subscriptionId, string resourceGroup, string storageAccountName) { if (credentials == null) { throw new ArgumentNullException(nameof(credentials)); } if (string.IsNullOrWhiteSpace(subscriptionId)) { throw new ArgumentNullException(nameof(subscriptionId)); } if (string.IsNullOrWhiteSpace(resourceGroup)) { throw new ArgumentNullException(nameof(resourceGroup)); } if (string.IsNullOrWhiteSpace(storageAccountName)) { throw new ArgumentNullException(nameof(storageAccountName)); } var azure = Azure.Authenticate(credentials) .WithSubscription(subscriptionId); await azure.StorageAccounts.DeleteByResourceGroupAsync( resourceGroup, storageAccountName); }
private void button1_Click(object sender, EventArgs e) { var authProperties = "C:\\Users\\" + Environment.UserName + "\\azure\\auth.properties"; IAzure azure = Azure.Authenticate(authProperties).WithDefaultSubscription(); var linuxVM = azure.VirtualMachines.Define(textBox1.Text) //.WithRegion(Microsoft.Azure.Management.ResourceManager.Fluent.Core.Region.UKWest) //.WithRegion("UKWEST") .WithRegion(comboBox1.SelectedItem.ToString()) .WithNewResourceGroup(textBox2.Text) .WithNewPrimaryNetwork("10.0.0.0/28") .WithPrimaryPrivateIPAddressDynamic() .WithNewPrimaryPublicIPAddress(textBox3.Text) //.WithPopularLinuxImage(KnownLinuxVirtualMachineImage.CentOS7_2) .WithPopularLinuxImage((KnownLinuxVirtualMachineImage)comboBox2.SelectedIndex) .WithRootUsername("james") .WithRootPassword("SuperSecret-123();") .WithSize(VirtualMachineSizeTypes.StandardA1v2); miniConsole.AppendText("VM Properties Set\r\n"); try { var machine = azure.VirtualMachines.Create(linuxVM); miniConsole.AppendText("VM Created\r\n"); } catch (Exception exc) { miniConsole.AppendText(exc.Message + "\r\n"); } }
static void Main(string[] args) { // whatever method you're using already for Authentication (like through file or with credentials or with cert // same can be used to get AzureCredentials as well, just change the FromFile to FromServicePrincipal if required IAzure azure = Azure.Authenticate("my.azureauth").WithDefaultSubscription(); var creds = SdkContext.AzureCredentialsFactory.FromFile("my.azureauth"); IGraphRbacManager graphRbacManager = GraphRbacManager.Authenticate(creds, "<your tenant Guid>"); var domains = graphRbacManager.Inner.Domains.ListAsync().GetAwaiter().GetResult(); string defaultDomain = string.Empty; foreach (var domain in domains) { Console.WriteLine(domain.Name); if (domain.IsDefault.HasValue && domain.IsDefault.Value == true) { defaultDomain = domain.Name; } // not breaking out of loop on purpose, just to print all domain names if multiple are there. } string identiferUri = string.Format("https://{0}/myuniqueapp1", defaultDomain); var app = azure.AccessManagement.ActiveDirectoryApplications .Define("My Unique App 1") .WithSignOnUrl("https://myuniqueapp1.azurewebsites.net") .WithAvailableToOtherTenants(true) .WithIdentifierUrl(identiferUri) .DefinePasswordCredential("string") .WithPasswordValue("string") .WithDuration(new TimeSpan(365, 0, 0, 0)) .Attach() .CreateAsync(); Console.ReadLine(); }
public override void Configure(IFunctionsHostBuilder builder) { var appId = Environment.GetEnvironmentVariable("ApplicationId"); var appSecret = Environment.GetEnvironmentVariable("ApplicationSecret"); var tenantId = Environment.GetEnvironmentVariable("TenantId"); var subscriptionId = Environment.GetEnvironmentVariable("SubscriptionId"); var storageAccountConnectionString = Environment.GetEnvironmentVariable("TestsStorageAccount"); var environment = AzureEnvironment.AzureGlobalCloud; var credentials = new AzureCredentialsFactory() .FromServicePrincipal(appId, appSecret, tenantId, environment); var azure = Azure .Authenticate(credentials) .WithSubscription(subscriptionId); builder.Services.AddHttpClient(); builder.Services.AddSingleton <IFileService, FileService>(); builder.Services.AddSingleton <IContainerInstanceService, ContainerInstanceService>(); builder.Services.AddSingleton <IGatlingService, GatlingService>(); builder.Services.AddSingleton(_ => azure); builder.Services.AddSingleton(_ => { var storageAccount = CloudStorageAccount.Parse(storageAccountConnectionString); return(storageAccount.CreateCloudBlobClient()); }); }
public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequestMessage req, TraceWriter log, ExecutionContext executionContext) { log.Info("GetAppService started"); var appServicePlanName = "#YOURAPPSERVICEPLANNAME#"; var authFile = $"{Directory.GetParent(executionContext.FunctionDirectory).FullName}\\my.azureauth"; log.Info(authFile); var azure = Azure.Authenticate(authFile).WithDefaultSubscription(); var appServicePlan = azure.AppServices.AppServicePlans.List().FirstOrDefault(x => x.Name == appServicePlanName); var getAppServiceResponse = new GetAppServiceResponse(); getAppServiceResponse.Capacity = appServicePlan.Capacity; getAppServiceResponse.SkuTier = appServicePlan.PricingTier.SkuDescription.Tier; getAppServiceResponse.SkuSize = appServicePlan.PricingTier.SkuDescription.Size; getAppServiceResponse.SkuName = appServicePlan.PricingTier.SkuDescription.Name; getAppServiceResponse.SkuFamily = appServicePlan.PricingTier.SkuDescription.Family; var appServicePlanResponseJson = JsonConvert.SerializeObject(getAppServiceResponse); return(req.CreateResponse(HttpStatusCode.OK, appServicePlanResponseJson)); }
protected override void Load(ContainerBuilder builder) { builder.Register(c => { var tokenProvider = new AzureServiceTokenProvider(); var tokenProviderAdapter = new AzureServiceTokenProviderAdapter(tokenProvider); return(new TokenCredentials(tokenProviderAdapter)); }); builder.Register(c => { var tokenCredentials = c.Resolve <TokenCredentials>(); var client = RestClient.Configure() .WithEnvironment(AzureEnvironment.AzureGlobalCloud) .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic) .WithCredentials(new AzureCredentials(tokenCredentials, tokenCredentials, string.Empty, AzureEnvironment.AzureGlobalCloud)) .Build(); return(Azure.Authenticate(client, string.Empty)); }); foreach (DeploymentEnvironment env in Enum.GetValues(typeof(DeploymentEnvironment))) { var subscriptionId = EswDevOpsSdk.GetSierraDeploymentSubscriptionId(env); builder.Register(c => { var authenticated = c.Resolve <Azure.IAuthenticated>(); return(authenticated.WithSubscription(subscriptionId)); }).Keyed <IAzure>(env).InstancePerLifetimeScope(); } }
//post public JsonResult create(string tenantID, string subID, [FromBody] VmParams vmParams) { AzureCredentials credentials = new AzureCredentials(getUserLoginInformation(), tenantID, AzureEnvironment.AzureGlobalCloud); var azure = Azure.Authenticate(credentials).WithSubscription(subID); var vnetrgname = "defaultNetworkGp-" + vmParams.region; var vnet = azure.Networks.GetByResourceGroup(vnetrgname, "defaultNetwork"); if (vnet == null) { var regionList = Region.Values.ToList(); int regionIndex = -1; for (var i = 0; i < regionList.Capacity; i++) { if (regionList[i].Name == vmParams.region) { regionIndex = i; break; } } azure.Networks.Define("defaultNetwork").WithRegion(vmParams.region).WithNewResourceGroup(vnetrgname).WithAddressSpace("222." + regionIndex + ".0.0/16").WithSubnet("defaultSubnet", "222." + regionIndex + "." + regionIndex + ".0/24").Create(); vnet = azure.Networks.GetByResourceGroup(vnetrgname, "defaultNetwork"); } var vmName = (vmParams.osType == "windows" ? "WinVM" : "LinVM") + Guid.NewGuid(); var vmrgname = vmName + "-Gp"; var vmrg = azure.ResourceGroups.Define(vmrgname).WithRegion(vmParams.region).Create(); var newVm = azure .VirtualMachines.Define(vmName) .WithRegion(vmParams.region) .WithExistingResourceGroup(vmrg) .WithExistingPrimaryNetwork(vnet) .WithSubnet("defaultSubnet") .WithPrimaryPrivateIPAddressDynamic() .WithNewPrimaryPublicIPAddress(vmName); if (vmParams.osType == "windows") { newVm.WithPopularWindowsImage((KnownWindowsVirtualMachineImage)vmParams.popOsImage).WithAdminUsername("manager").WithAdminPassword("Password123!"); } else { newVm.WithPopularLinuxImage((KnownLinuxVirtualMachineImage)vmParams.popOsImage).WithRootUsername("manager").WithRootPassword("Password123!"); } var newVMwithDisk = addDataDisks(azure, (IWithManagedDataDisk)newVm, vmParams, vmrgname); var result = ((IWithCreate)newVMwithDisk).WithSize(vmParams.vmSzie).Create(); var DNSLabel = vmName + "." + vmParams.region + ".cloudapp.azure.com"; return(new JsonResult() { Data = "VM created and initializing ,you can access it in 5 mins with public IP:" + result.GetPrimaryPublicIPAddress().IPAddress + " or DNS label:" + DNSLabel + " ADMIN ACCOUNT : manager , PASSWORD : Password123! . " }); }
static Azure.IAuthenticated GetAzure(Creds creds) { return(Azure.Authenticate(new AzureCredentials(new ServicePrincipalLoginInformation { ClientId = creds.ClientId, ClientSecret = creds.ClientSecret }, creds.TenantId, AzureEnvironment.AzureGlobalCloud))); }
private static IAzure GetAzureContext(ExecutionContext context) { var azureAuthFile = Path.Combine(context.FunctionAppDirectory, AzureAuthFile); return(Azure .Authenticate(azureAuthFile) .WithSubscription(SubscriptionName)); }
private async Task <IAzure> GetAzureContext() { var creds = GetAzureCredentials(); Debug.Assert(creds != null); return(await Azure.Authenticate(creds).WithDefaultSubscriptionAsync().ConfigureAwait(false)); }
private static IEnumerable <ISubscription> GetSubscriptions(AzureCredentials credentials, ILogger log) { log.LogInformation("Authenticate as service principal"); var azure = Azure.Authenticate(credentials); log.LogInformation("Get subscriptions"); return(azure.Subscriptions.List()); }
static IAzure GetAzure(Cfg cfg) { var sp = cfg.App.ServicePrincipal; var creds = new AzureCredentialsFactory().FromServicePrincipal(sp.ClientId, sp.Secret, sp.TennantId, AzureEnvironment.AzureGlobalCloud); var azure = Azure.Authenticate(creds).WithSubscription(cfg.App.SubscriptionId); return(azure); }
/// <summary> /// TODO: Clean this up. check and errors. /// /// Should check the loadbalancer.inner.status to see if update is already in progress. /// Also should batch the queue items, add and configure multiple up configurations at once if they are in the queue. /// </summary> /// <param name="tenantDeployment"></param> /// <param name="cancellationToken"></param> /// <returns></returns> private async Task <TenantDeployment> ProcessIpDeploymentAsync(TenantDeployment tenantDeployment, CancellationToken cancellationToken) { var spId = Environment.GetEnvironmentVariable("SERVICE_PRINCIPAL_ID"); var spSecret = Environment.GetEnvironmentVariable("SERVICE_PRINCIPAL_SECRET"); var spTenantId = Environment.GetEnvironmentVariable("SERVICE_PRINCIPAL_TENANT_ID"); var subscriptionId = Environment.GetEnvironmentVariable("SUBSCRIPTION_ID"); var creds = new AzureCredentialsFactory().FromServicePrincipal(spId, spSecret, spTenantId, AzureEnvironment.AzureGlobalCloud); var azure = Azure.Authenticate(creds).WithSubscription(subscriptionId); string loadBalancerName = Environment.GetEnvironmentVariable("LOAD_BALANCER"); string backendPool = Environment.GetEnvironmentVariable("BACKENDPOOL"); string resourcegroup = Environment.GetEnvironmentVariable("RESOURCEGROUP"); string tenantname = $"deployment-{tenantDeployment.Name}"; //TODO check provisioning state of load balancer and delay if currently busy //var provisioningState = azure.ResourceGroups.GetByName(loadBalancer.ResourceGroupName).ProvisioningState; try { var loadBalancer = await azure.LoadBalancers.GetByResourceGroupAsync(resourcegroup, loadBalancerName, cancellationToken); ILoadBalancerPublicFrontend publicFrontend = loadBalancer.PublicFrontends.First().Value; var publicIpAddress = publicFrontend.GetPublicIPAddress(); await loadBalancer.Update() .DefineTcpProbe(tenantname + "_mc") .WithPort(tenantDeployment.InternalPort) .Attach() .DefineLoadBalancingRule($"{tenantname}_mc") .WithProtocol(TransportProtocol.Tcp) .FromExistingPublicIPAddress(publicIpAddress) .FromFrontendPort(tenantDeployment.InternalPort) .ToBackend(backendPool) .ToBackendPort(tenantDeployment.InternalPort) .WithProbe(tenantname + "_mc") .Attach() .DefineTcpProbe(tenantname + "_rcon") .WithPort(tenantDeployment.RconPort) .Attach() .DefineLoadBalancingRule($"{tenantname}_rcon") .WithProtocol(TransportProtocol.Tcp) .FromExistingPublicIPAddress(publicIpAddress) .FromFrontendPort(tenantDeployment.RconPort) .ToBackend(backendPool) .ToBackendPort(tenantDeployment.RconPort) .WithProbe(tenantname + "_rcon") .Attach() .ApplyAsync(cancellationToken); return(new TenantDeployment(CreationStatus.Created, tenantDeployment, publicIpAddress.Fqdn)); } catch (Exception e) { ServiceEventSource.Current.ServiceMessage(this.Context, "error provisioning ip addresses.", e.Message); return(new TenantDeployment(CreationStatus.InProcess, tenantDeployment)); } }