Exemplo n.º 1
0
    public static Azure.IAuthenticated Login(bool loginAzCli)
    {
        AzureCredentials creds;

        if (loginAzCli)
        {
            Log(0, "Login from Azure CLI");
            creds = AzureCliCredentials.Create();
        }
        else
        {
            Log(0, "Login from Environment");
            //$env:servicePrincipalId, $env:servicePrincipalKey and $env:tenantId
            var client = Environment.GetEnvironmentVariable("servicePrincipalId");
            var key    = Environment.GetEnvironmentVariable("servicePrincipalKey");
            var tenant = Environment.GetEnvironmentVariable("tenantId");

            creds = new AzureCredentialsFactory().FromServicePrincipal(client,
                                                                       key,
                                                                       tenant,
                                                                       AzureEnvironment.AzureGlobalCloud);
        }

        var auth = Azure.Configure()
                   .Authenticate(creds)
        ;

        return(auth);
    }
Exemplo n.º 2
0
        public static AzureCredentials GetCredentialsFromSp()
        {
            var credentials = new AzureCredentialsFactory().FromServicePrincipal(ClientId, ClientSecret, TenantId,
                                                                                 AzureEnvironment.AzureGlobalCloud);

            return(credentials);
        }
        private AzureCredentials GetAzureCredentials()
        {
            var factory = new AzureCredentialsFactory();

            Debug.Assert(factory != null);
            Debug.Assert(_hostEnv != null);

            if (_hostEnv.IsDevelopment())
            {
                return(factory.FromFile("./azureauth.json"));
            }
            else
            {
                Debug.Assert(_config != null);

                var tenantId               = _config["SERVICE_PRINCIPAL_TENANT_ID"];
                var servicePrincipalId     = _config["SERVICE_PRINCIPAL_ID"];
                var servicePrincipalSecret = _config["SERVICE_PRINCIPAL_SECRET"];

                return(factory.FromServicePrincipal(servicePrincipalId,
                                                    servicePrincipalSecret,
                                                    tenantId,
                                                    AzureEnvironment.AzureGlobalCloud));
            }
        }
        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));
        }
Exemplo n.º 5
0
        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());
            });
        }
Exemplo n.º 6
0
        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));
        }
        public static void Run([QueueTrigger("cdnpurgequeue", Connection = "AzureWebJobsStorage")] string id, TraceWriter log, ExecutionContext context)
        {
            var config = GetConfiguration(context);

            var creds = new AzureCredentialsFactory().FromServicePrincipal(config[AZURE_APP_CLIENT_ID_KEY], config[AZURE_APP_KEY_KEY], config[AZURE_AD_TENANT_ID_KEY], AzureEnvironment.AzureGlobalCloud);
            var azure = Microsoft.Azure.Management.Fluent.Azure.Authenticate(creds).WithSubscription(config[AZURE_SUBSCRIPTION_ID_KEY]);

            string contentPath = null;

            if (UseStorageOrigin(config))
            {
                contentPath = $"/{id}/*";
            }
            else
            {
                contentPath = $"/{id}";
            }

            log.Info($"Requesting purge of {contentPath} on CDN endpoint {config[CDN_ENDPOINT_NAME_KEY]}");
            azure.CdnProfiles.PurgeEndpointContent(config[CDN_RESOURCE_GROUP_NAME_KEY], config[CDN_PROFILE_NAME_KEY], config[CDN_ENDPOINT_NAME_KEY], new List <string>()
            {
                contentPath
            });
            log.Info($"Completed purge of {contentPath} on CDN endpoint {config[CDN_ENDPOINT_NAME_KEY]}");
        }
        private static IAzure GetAzureContext(PerformContext context)
        {
            IAzure azure;

            try
            {
                context.WriteLine("Authenticating with Azure using servicePrincipal");

                var azureCredentialsFactory = new AzureCredentialsFactory();
                var clientId         = "29db2293-7e74-4715-9c88-32eece20e270";
                var clientSecret     = "6O1koUAfwco+8wZHPmrjeOECSQVgAvyZYiuS+6vPbL0=";
                var tenantId         = "b170db8b-8e00-4ad4-a076-ccc84281725d";
                var subscriptionId   = "7ebdeab9-8060-4fe5-b6c5-a522c7f206b6";
                var azureCredentials = azureCredentialsFactory.FromServicePrincipal(clientId, clientSecret, tenantId,
                                                                                    AzureEnvironment.AzureGlobalCloud);
                azure = Azure.Configure().WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
                        .WithRetryPolicy(new RetryPolicy(new TransientErrorIgnoreStrategy(),
                                                         new ExponentialBackoffRetryStrategy())).Authenticate(azureCredentials)
                        .WithSubscription(subscriptionId);
                var sub = azure.GetCurrentSubscription();

                context.WriteLine($"Authenticated with subscription '{sub.DisplayName}' (ID: {sub.SubscriptionId})");
            }
            catch (Exception ex)
            {
                context.SetTextColor(ConsoleTextColor.DarkRed);
                context.WriteLine($"\nFailed to authenticate:\n{ex.Message}");
                context.ResetTextColor();

                throw;
            }

            return(azure);
        }
        public static void Main(string[] args)
        {
            try
            {
                //=================================================================
                // Authenticate
                //AzureCredentials credentials = SdkContext.AzureCredentialsFactory.FromFile(Environment.GetEnvironmentVariable("AZURE_AUTH_LOCATION"));
                AzureCredentials credentials = new AzureCredentialsFactory().
                                               FromServicePrincipal("62853b31-30ca-4aa9-a76b-1158f9b38988",
                                                                    "54b50fb1-3e29-476f-8041-44b9e8f0be17",
                                                                    "d872ecb9-4810-48e3-be11-9fc01a9c7e50",
                                                                    AzureEnvironment.AzureGlobalCloud);

                var azure = Azure
                            .Configure()
                            .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
                            .Authenticate(credentials)
                            .WithDefaultSubscription();

                // Print selected subscription
                Utilities.Log("Selected subscription: " + azure.SubscriptionId);

                RunSample(azure);
            }
            catch (Exception ex)
            {
                Utilities.Log(ex);
            }
        }
Exemplo n.º 10
0
        public void Login()
        {
            string client = "9ab5958d-4850-4f61-9f33-f95692b6d33b";
            string secret = ".75_UTS.Hi_BKZHcWntL-3L~kr7txEV-V~";
            //string tenant = "greggschneider89gmail.onmicrosoft.com";
            string tenant         = "6b188bb3-722f-43ec-8c64-5ec81dc576fe";
            var    creds          = new AzureCredentialsFactory().FromServicePrincipal(client, secret, tenant, AzureEnvironment.AzureGlobalCloud);
            string subscriptionId = "be6cb7f8-c55a-4882-90eb-3777b108b32f";

            Console.WriteLine(creds);
            //azure = Azure.Authenticate(creds).WithDefaultSubscription();
            //azure = Azure.Authenticate(creds).WithSubscription(subscriptionId);
            Console.WriteLine(azure);

            //Console.WriteLine("Creating a Windows VM");

            //var windowsVM = azure.VirtualMachines.Define("TestServerForAsureSDK")
            //	.WithRegion(Region.EuropeWest)
            //	.WithExistingResourceGroup("CTF_platform")
            //	.WithNewPrimaryNetwork("10.0.0.0/28")
            //	.WithPrimaryPrivateIPAddressDynamic()
            //	.WithoutPrimaryPublicIPAddress()
            //	.WithPopularWindowsImage(KnownWindowsVirtualMachineImage.WindowsServer2012R2Datacenter)
            //	.WithAdminUsername("rootz")
            //	.WithAdminPassword("GreggXCyberSparrow!1989SomEr03")
            //	.WithSize(VirtualMachineSizeTypes.StandardD3V2)
            //	.Create();

            //Console.WriteLine("Created a Windows VM: " + windowsVM.Id);
        }
        protected void ConfigureAzure()
        {
            // First try to acquire a token from the MSI endpoint
            var creds             = default(AzureCredentials);
            var credentialFactory = new AzureCredentialsFactory();

            // If the ResourceManagementClient does exist, already, just return it.
            if (this.AzureMgmt != null)
            {
                return;
            }
            else
            {
                this.logger.LogInformation("ResourcesRepository.ConfigureAzure() instantiating Azure Management Client...");
            }

            // Try acquiring a token (requires refactoring, learning new Fluent libraries as lots has changed from last time (a while ago))
            this.ClientId     = Environment.GetEnvironmentVariable(Constants.CLIENT_ID_ENV);
            this.ClientSecret = Environment.GetEnvironmentVariable(Constants.CLIENT_SECRET_ENV);
            this.TenantId     = Environment.GetEnvironmentVariable(Constants.TENANT_ID_ENV);

            // The tenant Id is always required (due to eventual RBAC assignments using Graph library which needs the tenant ID)
            if (string.IsNullOrWhiteSpace(this.TenantId))
            {
                throw new Exception($"Missing configuration for {Constants.TENANT_ID_ENV} which is always required!");
            }

            // If not all details for a service principal are present, try MSI.
            this.CredentialsUseSp = !(string.IsNullOrWhiteSpace(this.ClientId) || string.IsNullOrWhiteSpace(this.ClientSecret));
            if (this.CredentialsUseSp)
            {
                creds = credentialFactory.FromServicePrincipal(this.ClientId, this.ClientSecret, this.TenantId, AzureEnvironment.AzureGlobalCloud);
            }
            else
            {
                this.logger.LogInformation($"Incomplete details for service principal in environment (clientId, clientSecret or tenantId misssing), trying managed service identity.");
                try
                {
                    this.logger.LogInformation("ResourceGroupRepository - acquire token from local MSI.");
                    creds = credentialFactory.FromMSI(new MSILoginInformation(MSIResourceType.VirtualMachine),
                                                      AzureEnvironment.AzureGlobalCloud,
                                                      tenantId: this.TenantId)
                            .WithDefaultSubscription(this.SubscriptionId);
                }
                catch (MSILoginException msiex)
                {
                    this.logger.LogError($"Failed to acquire token for ResourceProviderRepository with managed service identity: {msiex.Message}!");
                    throw new Exception("Failed acquiring token!", msiex);
                }
            }

            // Token acquired, successfully. Now configure the API Endpoint
            this.AzureMgmt = Azure.Configure()
                             .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
                             .Authenticate(creds)
                             .WithSubscription(this.SubscriptionId);

            this.logger.LogInformation("ResourcesRepository.ConfigureAzure() succeeded creating fluent Azure Management Client!");
        }
Exemplo n.º 12
0
        public static object Authenticate(string clientId, string clientSecret, string tenantId, string subscriptionId)
        {
            var credentials = new AzureCredentialsFactory().FromServicePrincipal(clientId, clientSecret, tenantId, AzureEnvironment.AzureGlobalCloud);

            var azure = Microsoft.Azure.Management.Fluent.Azure.Authenticate(credentials).WithSubscription(subscriptionId);

            return(azure);
        }
Exemplo n.º 13
0
        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);
        }
Exemplo n.º 14
0
        /// <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));
            }
        }
        public ContainerRunnerLib()
        {
#if (DEBUG)
            _azure = Azure.Authenticate("./credentials.json").WithDefaultSubscription();
#else
            var credentials = new AzureCredentialsFactory().FromSystemAssignedManagedServiceIdentity(MSIResourceType.AppService, AzureEnvironment.AzureGlobalCloud);
            _azure = Azure.Authenticate(credentials).WithDefaultSubscription();
#endif
        }
Exemplo n.º 16
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            int operationDelay   = 60000; //1min
            var resoureGroupName = System.Environment.GetEnvironmentVariable("RESOURCE_GROUP_NAME", EnvironmentVariableTarget.Process);
            var vmScalesetName   = System.Environment.GetEnvironmentVariable("VMSS_NAME", EnvironmentVariableTarget.Process);
            var subscriptionId   = System.Environment.GetEnvironmentVariable("SUBSCRIPTION_ID", EnvironmentVariableTarget.Process);

            string  COUNT       = req.Query["COUNT"];
            string  requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            dynamic data        = JsonConvert.DeserializeObject(requestBody);

            COUNT = COUNT ?? data?.COUNT;

            int ftdCountInt = Convert.ToInt32(COUNT);

            log.LogWarning("FtdScaleOut:::: count str {0}, count int {1}", COUNT, ftdCountInt);
            log.LogWarning("FtdScaleOut:::: FTD ScaleOut Started (RG : {0}, VMSS: {1}, Count: {2})", resoureGroupName.ToString(), vmScalesetName.ToString(), ftdCountInt);

            var factory          = new AzureCredentialsFactory();
            var msiCred          = factory.FromMSI(new MSILoginInformation(MSIResourceType.AppService), AzureEnvironment.AzureGlobalCloud);
            var azure            = Azure.Configure().WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic).Authenticate(msiCred).WithSubscription(subscriptionId);
            var vMachineScaleSet = azure.VirtualMachineScaleSets.GetByResourceGroup(resoureGroupName, vmScalesetName);

            log.LogWarning("FtdScaleOut:::: Current VMSS Capacity : {0}", vMachineScaleSet.Capacity.ToString());
            var computeManagementClient = new ComputeManagementClient(msiCred)
            {
                SubscriptionId = azure.SubscriptionId
            };
            var update = computeManagementClient.VirtualMachineScaleSets.CreateOrUpdateWithHttpMessagesAsync(resoureGroupName, vmScalesetName,
                                                                                                             new VirtualMachineScaleSet
            {
                Location      = vMachineScaleSet.RegionName,
                Overprovision = false,
                Sku           = new Sku
                {
                    Capacity = vMachineScaleSet.Capacity + ftdCountInt,
                    Name     = vMachineScaleSet.Sku.Sku.Name,
                    Tier     = vMachineScaleSet.Sku.Sku.Tier
                }
            });

            log.LogInformation("FtdScaleOut:::: FTD Scale Out Started... Please wait");
            update.Wait(operationDelay);
            log.LogInformation("FtdScaleOut:::: FTD Scale Out Status : {0}", update.Status.ToString());

            if ("WaitingForActivation" != update.Status.ToString())
            {
                log.LogError("FtdScaleOut:::: ScaleOut Operation failed (Status : {0})", update.Status.ToString());
                return((ActionResult) new BadRequestObjectResult("ERROR: ScaleOut Operation failed"));
            }

            vMachineScaleSet = azure.VirtualMachineScaleSets.GetByResourceGroup(resoureGroupName, vmScalesetName);
            log.LogWarning("FtdScaleOut:::: Post ScaleOut VMSS Capacity : {0}", vMachineScaleSet.Capacity.ToString());
            return((ActionResult) new OkObjectResult("SUCCESS"));
        }
Exemplo n.º 17
0
        public static async Task <IActionResult> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequestMessage req, ILogger log)
        {
            AzureCredentialsFactory factory = new AzureCredentialsFactory();
            AzureCredentials        msiCred = factory.FromMSI(new MSILoginInformation(MSIResourceType.AppService), AzureEnvironment.AzureGlobalCloud);
            var azure = Azure.Configure().WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic).Authenticate(msiCred).WithDefaultSubscription();

            var nsg = azure.NetworkSecurityGroups.GetByResourceGroup("TestNSGRG", "RSTestNSG1");

            return((ActionResult) new OkObjectResult(string.Format("NSG {0} found with {1} default security rules", nsg.Name, nsg.DefaultSecurityRules.Count)));
        }
Exemplo n.º 18
0
        public static string SayHello3([ActivityTrigger] string name, 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"));

            DeleteContainerGroup(azure, "azure-poc-rg", "extractor" + name);

            log.LogInformation($"Saying hello to {name}.");
            return($"Hello {name}!");
        }
        private IAzure GetContext()
        {
            var credentials = new AzureCredentialsFactory().FromServicePrincipal(
                config.ClientId,
                config.ClientSecret,
                config.TenantId,
                AzureEnvironment.AzureGlobalCloud);

            return(Azure.Authenticate(credentials).WithDefaultSubscription());
        }
Exemplo n.º 20
0
        public static AzureCredentials GetAzureCredentials(string clientId, string appSecret, string tenantId, string subscriptionId)
        {
            var credentials = new AzureCredentialsFactory()
                              .FromServicePrincipal(clientId,
                                                    appSecret,
                                                    tenantId,
                                                    AzureEnvironment.AzureGlobalCloud);

            return(credentials.WithDefaultSubscription(subscriptionId));
        }
Exemplo n.º 21
0
        public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequestMessage req, TraceWriter log)
        {
            log.Info("Getting request body params");
            dynamic data = await req.Content.ReadAsAsync <object>();

            string subscriptionId    = data?.subscriptionId;
            string resourceGroupName = data?.resourceGroupName;
            string vmName            = data?.vmName;

            if (subscriptionId == null || resourceGroupName == null || vmName == null)
            {
                return(req.CreateResponse(HttpStatusCode.BadRequest, "Please pass all 3 required parameters in the request body"));
            }

            log.Info("Setting authentication to use MSI");
            AzureCredentialsFactory f = new AzureCredentialsFactory();
            var msi = new MSILoginInformation(MSIResourceType.AppService);

            var msiCred = f.FromMSI(msi, AzureEnvironment.AzureGlobalCloud);

            var azureAuth = Azure.Configure()
                            .WithLogLevel(HttpLoggingDelegatingHandler.Level.BodyAndHeaders)
                            .Authenticate(msiCred);

            log.Info("Authenticating with Azure using MSI");
            var azure = azureAuth.WithSubscription(subscriptionId);

            log.Info("Acquiring VM from Azure");
            var vm = azure.VirtualMachines.GetByResourceGroup(resourceGroupName, vmName);

            log.Info("Checking VM Id");
            log.Info(vm.Id.ToString());

            log.Info("Checking VM Powerstate");
            log.Info("VM Powerstate : " + vm.PowerState.ToString());

            bool vmStarting = false;

            if (vm.PowerState.ToString() == "PowerState/running")
            {
                log.Info("VM is already running");
            }
            else
            {
                log.Info("Starting vm " + vmName);
                await vm.StartAsync();

                vmStarting = true;
            }

            return(vmStarting == false
            ? req.CreateResponse(HttpStatusCode.OK, "VM was already started")
            : req.CreateResponse(HttpStatusCode.OK, "VM started"));
        }
Exemplo n.º 22
0
        /// <summary>
        /// Initialize values for use with sdk
        /// </summary>
        /// <param name="subscription"></param>
        /// <param name="tenant"></param>
        /// <param name="client"></param>
        /// <param name="key"></param>
        public static void InitializeValues(string subscription, string tenant, string client, string key)
        {
            subscriptionId = subscription;
            tenantId       = tenant;
            clientId       = client;
            clientKey      = key;
            var creds = new AzureCredentialsFactory()
                        .FromServicePrincipal(clientId, clientKey, tenantId, AzureEnvironment.AzureGlobalCloud);

            azure  = Microsoft.Azure.Management.Fluent.Azure.Authenticate(creds).WithSubscription(subscriptionId);
            allVms = azure.VirtualMachines.ListAsync().GetAwaiter().GetResult().ToArray();
        }
Exemplo n.º 23
0
        /// <summary>
        /// Gets an <see cref="IAzure"/> by authenticating against Azure AD with a Service Principal
        /// </summary>
        /// <param name="clientId">The clientId from the AppRegistration in AzureAD</param>
        /// <param name="clientSecret">The clientSecret from the AppRegistration in AzureAD</param>
        /// <param name="tenantId">The Azure TenantId aka DirectoryId</param>
        /// <param name="subscriptionId">(optional) The Subscription to use. Default one is used if empty</param>
        /// <returns>An <see cref="IAzure"/> Interface for communication with the Azure Cloud</returns>
        public static IAzure GetAzureInterface(string clientId, string clientSecret, string tenantId, string subscriptionId = null)
        {
            AzureCredentials azureCredentials = new AzureCredentialsFactory()
                                                .FromServicePrincipal(clientId, clientSecret, tenantId, AzureEnvironment.AzureGlobalCloud);
            var authenticated = Azure.Authenticate(azureCredentials);

            if (subscriptionId == null)
            {
                return(authenticated.WithDefaultSubscription());
            }
            return(authenticated.WithSubscription(subscriptionId));
        }
Exemplo n.º 24
0
        public static AzureCredentials GetAzureCredentials()
        {
            var subscriptionId = "[Subscription_Id]";
            var appId          = "[App_Id]";
            var appSecret      = "[App_Secret]";
            var tenantId       = "[Tenant_Id]";
            var environment    = AzureEnvironment.AzureGlobalCloud;

            var credentials = new AzureCredentialsFactory().FromServicePrincipal(appId, appSecret, tenantId, environment);

            return(credentials.WithDefaultSubscription(subscriptionId));
        }
Exemplo n.º 25
0
        public VirtualMachineService(IOptions <AzureSettings> azureSettings)
        {
            AzureSettings = azureSettings.Value;

            var credentials = new AzureCredentialsFactory().FromServicePrincipal(
                AzureSettings.ClientId,
                AzureSettings.ClientSecret,
                AzureSettings.TenantId,
                AzureEnvironment.AzureGlobalCloud);

            _Azure = Azure.Authenticate(credentials).WithDefaultSubscription();
        }
Exemplo n.º 26
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            int     operationDelay   = 90000; //1.5min
            var     resoureGroupName = System.Environment.GetEnvironmentVariable("RESOURCE_GROUP_NAME", EnvironmentVariableTarget.Process);
            var     vmScalesetName   = System.Environment.GetEnvironmentVariable("VMSS_NAME", EnvironmentVariableTarget.Process);
            var     subscriptionId   = System.Environment.GetEnvironmentVariable("SUBSCRIPTION_ID", EnvironmentVariableTarget.Process);
            string  instanceid       = req.Query["instanceid"];
            string  requestBody      = await new StreamReader(req.Body).ReadToEndAsync();
            dynamic data             = JsonConvert.DeserializeObject(requestBody);

            instanceid = instanceid ?? data?.instanceid;
            int vmssCapacity = 0;

            if (null == instanceid)
            {
                log.LogError("FtdScaleIn:::: Invalid FTD Instance Id for ScaleIn");
                return((ActionResult) new BadRequestObjectResult("ERROR: Invalid FTD Instance Id for ScaleIn"));
            }

            log.LogWarning("FtdScaleIn:::: FTD Scale-In Started (RG : {0}, VMSS: {1}, FTD InstanceId to Delete: {2} )", resoureGroupName.ToString(), vmScalesetName.ToString(), instanceid);

            var factory = new AzureCredentialsFactory();
            var msiCred = factory.FromMSI(new MSILoginInformation(MSIResourceType.AppService), AzureEnvironment.AzureGlobalCloud);
            var azure   = Azure.Configure().WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic).Authenticate(msiCred).WithSubscription(subscriptionId);

            var vMachineScaleSet = azure.VirtualMachineScaleSets.GetByResourceGroup(resoureGroupName, vmScalesetName);

            vmssCapacity = vMachineScaleSet.Capacity;
            log.LogInformation("FtdScaleIn:::: Current VMSS Capacity : {0}", vmssCapacity);

            var computeManagementClient = new ComputeManagementClient(msiCred)
            {
                SubscriptionId = azure.SubscriptionId
            };
            //var del = computeManagementClient.VirtualMachineScaleSetVMs.DeleteWithHttpMessagesAsync(resoureGroupName, vmScalesetName, instanceid).Result;
            var del = computeManagementClient.VirtualMachineScaleSetVMs.DeleteWithHttpMessagesAsync(resoureGroupName, vmScalesetName, instanceid);

            del.Wait(operationDelay);

            vMachineScaleSet = azure.VirtualMachineScaleSets.GetByResourceGroup(resoureGroupName, vmScalesetName);
            log.LogInformation("FtdScaleIn:::: Post ScaleIn VMSS Capacity : {0}", vMachineScaleSet.Capacity.ToString());

            if ((vmssCapacity - 1) != vMachineScaleSet.Capacity)
            {
                log.LogError("FtdScaleIn:::: Failed ScaleIn Operation (vmss capacity: {0})", vMachineScaleSet.Capacity);
                return((ActionResult) new BadRequestObjectResult("ERROR: Failed ScaleIn Operation. Don't worry, Azure may be taking longer time to delete, but eventually it may delete"));
            }

            return((ActionResult) new OkObjectResult("SUCCESS"));
        }
Exemplo n.º 27
0
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            var creds = new AzureCredentialsFactory().FromServicePrincipal(AZURE_CLIENT_ID, AZURE_CLIENT_SECRET, AZURE_TENANT_ID, AzureEnvironment.AzureGlobalCloud);
            var azure = Azure.Authenticate(creds).WithSubscription(AZURE_SUBSCRIPTION_ID);

            List <string> purgedContent = new List <string> {
                "/images/*"
            };

            azure.CdnProfiles.PurgeEndpointContent("RESOURCE_GROUP_NAME", "CDN_PROFILE_NAME", "CDN_ENDPOINT_NAME", purgedContent);
        }
Exemplo n.º 28
0
        public AUTH()
        {
            ServiceClientCredentials credentials = ApplicationTokenProvider.LoginSilentAsync(domain, new ClientCredential(clientId, clientSecret), ActiveDirectoryServiceSettings.AzureChina).Result;

            serviceClientCredentials = credentials;

            AzureCredentials creds = new AzureCredentialsFactory().FromServicePrincipal(clientId, clientSecret, domain, AzureEnvironment.AzureChinaCloud);

            azureCredentials = creds;

            IAzure Iazure = Azure.Authenticate(azureCredentials).WithSubscription(subscriptionId);

            azure = Iazure;
        }
Exemplo n.º 29
0
        public async Task <IEnumerable <IVirtualMachine> > GetList()
        {
            var credentials = new AzureCredentialsFactory()
                              .FromServicePrincipal(_azureConfiguration.ClientId,
                                                    _azureConfiguration.ClientSecret,
                                                    _azureConfiguration.TenantId,
                                                    AzureEnvironment.AzureGlobalCloud);

            var azure = Azure.Authenticate(credentials).WithSubscription(_azureConfiguration.Subscription);

            var vms = await azure.VirtualMachines.ListAsync();

            return(vms.ToList());
        }
Exemplo n.º 30
0
        public IAzure SignIn()
        {
            _log.Info("Connecting to Azure subscription");
            var creds = new AzureCredentialsFactory().FromServicePrincipal(
                _configuration.ClientId,
                _configuration.ClientSecret,
                _configuration.TenantId,
                AzureEnvironment.AzureGlobalCloud);
            var azure = Microsoft.Azure.Management.Fluent.Azure.Authenticate(creds)
                        .WithSubscription(_configuration.SubscriptionId);

            _log.Info("Connected to Azure subscription");
            return(azure);
        }