Exemplo n.º 1
0
        protected async Task <AzureCredentials> ReadAzureCredentials(ArgumentSyntax syntax)
        {
            var azSettings = await UserSettings.GetAzureSettings();

            var tenantId = syntax.GetOption <string>(AzureTenantIdOption)
                           ?? azSettings.TenantId;
            var clientId = syntax.GetOption <string>(AzureClientIdOption)
                           ?? azSettings.ClientId;
            var secret = syntax.GetOption <string>(AzureSecretOption)
                         ?? azSettings.ClientSecret;
            var subscriptionId = syntax.GetOption <string>(AzureSubscriptionIdOption)
                                 ?? azSettings.SubscriptionId;

            ValidateOption(tenantId, AzureTenantIdOption);
            ValidateOption(clientId, AzureClientIdOption);
            ValidateOption(secret, AzureSecretOption);
            ValidateOption(subscriptionId, AzureSubscriptionIdOption);

            var loginInfo = new ServicePrincipalLoginInformation
            {
                ClientId     = clientId,
                ClientSecret = secret,
            };

            var credentials = new AzureCredentials(
                loginInfo, tenantId, AzureEnvironment.AzureGlobalCloud)
                              .WithDefaultSubscription(subscriptionId);

            return(credentials);
        }
Exemplo n.º 2
0
        public static IAzure AzureLogin(
            Subscription subscription,
            AzureEnvironment azureEnvironment,
            ILogger logger
            )
        {
            logger.LogDebug("Attempting to authenticate for subscription: {0}", (string)subscription.subscription_id);

            // Create service principal
            ServicePrincipalLoginInformation spn = new ServicePrincipalLoginInformation {
                ClientId     = subscription.client_id,
                ClientSecret = subscription.client_secret
            };

            /// Create the Azure credentials
            AzureCredentials azureCredential = new AzureCredentials(
                spn,
                subscription.tenant_id,
                azureEnvironment
                );

            // Create and return the Azure object
            IAzure azure = Microsoft.Azure.Management.Fluent.Azure
                           .Configure()
                           .Authenticate(azureCredential)
                           .WithSubscription(subscription.subscription_id);

            return(azure);
        }
Exemplo n.º 3
0
        // </snippet_delete>

        static void Main(string[] args)
        {
            /* For more information about authenticating, see:
             * https://docs.microsoft.com/en-us/dotnet/azure/dotnet-sdk-azure-authenticate?view=azure-dotnet
             */

            // <snippet_assigns>
            var service_principal_credentials = new ServicePrincipalLoginInformation();

            service_principal_credentials.ClientId     = service_principal_application_id;
            service_principal_credentials.ClientSecret = service_principal_secret;

            var credentials = SdkContext.AzureCredentialsFactory.FromServicePrincipal(service_principal_application_id, service_principal_secret, tenant_id, AzureEnvironment.AzureGlobalCloud);
            var client      = new CognitiveServicesManagementClient(credentials);

            client.SubscriptionId = subscription_id;
            // </snippet_assigns>

            // <snippet_calls>
            // Uncomment to list all available resource kinds, SKUs, and locations for your Azure account:
            //list_available_kinds_skus_locations(client);

            // Create a resource with kind TextTranslation, F0 (free tier), location global.
            create_resource(client, "test_resource", "TextTranslation", "F0", "Global");

            // List all resources for your Azure account and resource group:
            list_resources(client);

            // Delete the resource.
            delete_resource(client, "test_resource");

            Console.WriteLine("Press any key to exit.");
            Console.ReadKey();
            // </snippet_calls>
        }
Exemplo n.º 4
0
        private IAzure Azure()
        {
            try
            {
                var servicePrincipal = new ServicePrincipalLoginInformation
                {
                    ClientId     = _credentials.ClientId,
                    ClientSecret = _credentials.Key
                };

                var credentials = new AzureCredentials(servicePrincipal, _credentials.TenantId, AzureEnvironment.AzureGlobalCloud);

                var azure = Microsoft.Azure.Management.Fluent.Azure
                            .Configure()
                            .WithLogLevel(HttpLoggingDelegatingHandler.Level.BASIC)
                            .Authenticate(credentials)
                            .WithSubscription(_credentials.SubscriptionId);

                Connected = !string.IsNullOrEmpty(azure.GetCurrentSubscription().SubscriptionId);

                return(azure);
            }
            catch (Exception)
            {
                Connected = false;
            }

            return(null);
        }
Exemplo n.º 5
0
        public async Task <object> Execute(ArgumentSyntax syntax)
        {
            var talentId       = syntax.GetOption <string>(AzureTalentIdOption);
            var clientId       = syntax.GetOption <string>(AzureClientIdOption);
            var secret         = syntax.GetOption <string>(AzureSecretOption);
            var subscriptionId = syntax.GetOption <string>(AzureSubscriptionIdOption);

            var loginInfo = new ServicePrincipalLoginInformation
            {
                ClientId     = clientId,
                ClientSecret = secret,
            };

            var credentials = new AzureCredentials(
                loginInfo, talentId, AzureEnvironment.AzureGlobalCloud)
                              .WithDefaultSubscription(subscriptionId);

            var resourceGroups = await LoadResourceGroups(credentials);

            var azSettings = new AzureSettings
            {
                ClientId       = clientId,
                TalentId       = talentId,
                ClientSecret   = secret,
                SubscriptionId = subscriptionId,
            };

            await userSettings.SetAzureSettings(azSettings);

            return(new
            {
                resourceGroups
            });
        }
Exemplo n.º 6
0
        protected async Task <RestClient> CreateAzureRestClient(ArgumentSyntax syntax)
        {
            var azSettings = await UserSettings.GetAzureSettings();

            var tenantId = syntax.GetOption <string>(AzureTenantIdOption)
                           ?? azSettings.TenantId;
            var clientId = syntax.GetOption <string>(AzureClientIdOption)
                           ?? azSettings.ClientId;
            var secret = syntax.GetOption <string>(AzureSecretOption)
                         ?? azSettings.ClientSecret;
            var subscriptionId = syntax.GetOption <string>(AzureSubscriptionIdOption)
                                 ?? azSettings.SubscriptionId;

            ValidateOption(tenantId, AzureTenantIdOption);
            ValidateOption(clientId, AzureClientIdOption);
            ValidateOption(secret, AzureSecretOption);
            ValidateOption(subscriptionId, AzureSubscriptionIdOption);

            var loginInfo = new ServicePrincipalLoginInformation
            {
                ClientId     = clientId,
                ClientSecret = secret,
            };

            return(CreateRestClient(tenantId, subscriptionId, loginInfo));
        }
Exemplo n.º 7
0
        private static IAzure GetAzureContext(Microsoft.Azure.WebJobs.ExecutionContext context)
        {
            //var azureAuthFile = Path.Combine(context.FunctionAppDirectory, AzureAuthFile);
            //var credentials = SdkContext.AzureCredentialsFactory
            //    .FromFile(Environment.GetEnvironmentVariable(azureAuthFile));

            var servicePrinciple = new ServicePrincipalLoginInformation()
            {
                ClientId     = ClientId,
                ClientSecret = Secret,
            };

            var azureCredentials = new AzureCredentials(servicePrinciple, TenantId, AzureEnvironment.AzureGlobalCloud);

            try
            {
                return(Microsoft.Azure.Management.Fluent.Azure
                       .Configure()
                       .Authenticate(azureCredentials).WithSubscription(SubscriptionName));
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            return(null);
        }
Exemplo n.º 8
0
        static async Task Main(string[] args)
        {
            var servicePrincipal = new ServicePrincipalLoginInformation {
                ClientId = "a72b5fad-ea6d-4dc6-ad29-a61ec5764996", ClientSecret = "r=gVw3Z7E=AvZxegH_-paS2B8HOJNw-4"
            };
            var creds      = new AzureCredentials(servicePrincipal, tenantId: "865a8d92-047d-4700-bdd5-1642317b02fb", AzureEnvironment.AzureGlobalCloud);
            var restClient = Microsoft.Azure.Management.ResourceManager.Fluent.Core.RestClient
                             .Configure()
                             .WithEnvironment(AzureEnvironment.AzureGlobalCloud)
                             .WithCredentials(creds)
                             .Build();
            var listResources = new ResourceManagementClient(restClient);

            listResources.SubscriptionId = "6fca20d4-4d6e-48ff-94ef-53850004a3dd";
            // var rgs = await resourceManagementClient.ResourceGroups.ListAsync();
            // var test =  new ResourceManagementClient(restClient).Resources.ListAsync()
            var resourcegrouplist = "ARCONPAMAZURE";
            // var rgs =  azure.ResourceGroups.GetByName(resourcegrouplist);
            var id = new String[2];
            var i  = 0;
            //  var resourceList = listResources.Resources.ListByResourceGroup(resourcegrouplist[i]);
            var resourceList = await listResources.Resources.ListByResourceGroupAsync(resourcegrouplist);

            foreach (var resource in resourceList)
            {
                if (resource.Type.Equals("Microsoft.Compute/virtualMachineScaleSets"))
                {
                    id[i] = resource.Id;
                    i++;
                    Console.WriteLine(resource.Name.ToString());
                }
            }
            var listvms1 = await listResources.Resources.GetByIdAsync(id[0], "2020-06-01");

            var listvms2 = await listResources.Resources.GetByIdAsync(id[1], "2020-06-01");

            var tokenclient = new RestSharp.RestClient("https://login.microsoftonline.com/865a8d92-047d-4700-bdd5-1642317b02fb/oauth2/v2.0/token");
            var request     = new RestRequest(Method.POST);

            request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
            request.AddParameter("scope", "https://management.azure.com/.default");
            request.AddParameter("client_secret", "r=gVw3Z7E=AvZxegH_-paS2B8HOJNw-4");
            request.AddParameter("client_id", "a72b5fad-ea6d-4dc6-ad29-a61ec5764996");
            request.AddParameter("grant_type", "client_credentials");
            IRestResponse response = tokenclient.Execute(request);

            Console.WriteLine(response.Content);
            JObject tokenjson = JObject.Parse(response.Content);
            var     token     = tokenjson.GetValue("access_token").ToString();
            var     VMclient  = new RestSharp.RestClient("https://management.azure.com/subscriptions/6fca20d4-4d6e-48ff-94ef-53850004a3dd/resourceGroups/" + resourcegrouplist + "/providers/Microsoft.Compute/virtualMachineScaleSets/" + listvms1.Name + "/virtualmachines/0?api-version=2020-06-01");
            var     VMrequest = new RestRequest(Method.GET);

            VMrequest.AddHeader("Authorization", "Bearer " + token);
            IRestResponse passchangeclientresponse = VMclient.Execute(VMrequest);

            Console.WriteLine(response.Content);
        }
Exemplo n.º 9
0
 private static IAzure GetAzure()
 {
     var tenantId = ConfigurationManager.AppSettings["TenantId"];
     var sp = new ServicePrincipalLoginInformation
     {
         ClientId = ConfigurationManager.AppSettings["ClientId"],
         ClientSecret = ConfigurationManager.AppSettings["ClientSecret"]
     };
     return Azure.Authenticate(new AzureCredentials(sp, tenantId, AzureEnvironment.AzureGlobalCloud)).WithDefaultSubscription();
 }
Exemplo n.º 10
0
        public AzureScaler(string AzureClientId, string AzureClientKey, string TenantId)
        {
            this.spli = new ServicePrincipalLoginInformation
            {
                ClientId     = AzureClientId,
                ClientSecret = AzureClientKey
            };

            this.creds = new AzureCredentials(spli, TenantId, AzureEnvironment.AzureGlobalCloud);

            this.azureClient = Azure.Authenticate(this.creds).WithDefaultSubscription();
        }
Exemplo n.º 11
0
        public static async Task <HttpResponseData> SetupDns(
            [HttpTrigger(AuthorizationLevel.Anonymous, "put", Route = "dns-01/{algo}")] HttpRequestData req,
            string algo,
            FunctionContext executionContext)
        {
            Dictionary <string, string> tokens;

            using (var reader = new StreamReader(req.Body))
            {
                var json = await reader.ReadToEndAsync();

                tokens = JsonConvert.DeserializeObject <Dictionary <string, string> >(json);
            }

            var keyType    = (KeyAlgorithm)Enum.Parse(typeof(KeyAlgorithm), algo, true);
            var accountKey = GetTestKey(keyType);

            var loginInfo = new ServicePrincipalLoginInformation
            {
                ClientId     = Env("CERTES_AZURE_CLIENT_ID"),
                ClientSecret = Env("CERTES_AZURE_CLIENT_SECRET"),
            };

            var credentials = new AzureCredentials(loginInfo, Env("CERTES_AZURE_TENANT_ID"), AzureEnvironment.AzureGlobalCloud);
            var builder     = RestClient.Configure();
            var resClient   = builder.WithEnvironment(AzureEnvironment.AzureGlobalCloud)
                              .WithCredentials(credentials)
                              .Build();

            using (var client = new DnsManagementClient(resClient))
            {
                client.SubscriptionId = Env("CERTES_AZURE_SUBSCRIPTION_ID");

                foreach (var p in tokens)
                {
                    var name = "_acme-challenge." + p.Key.Replace(".dymetis.com", "");
                    await client.RecordSets.CreateOrUpdateAsync(
                        "dymetis",
                        "dymetis.com",
                        name,
                        RecordType.TXT,
                        new RecordSetInner(
                            name : name,
                            tTL : 1,
                            txtRecords : new[] { new TxtRecord(new[] { accountKey.SignatureKey.DnsTxt(p.Value) }) }));
                }
            }

            var response = req.CreateResponse(HttpStatusCode.OK);

            return(response);
        }
Exemplo n.º 12
0
        public static ISignalRManagementClient CreateSignalRManagementClient(AppyAzureCredentials appyCredentials)
        {
            var sp = new ServicePrincipalLoginInformation
            {
                ClientId     = appyCredentials.ClientId,
                ClientSecret = appyCredentials.ClientSecret,
            };
            var azureCredentials = new AzureCredentials(sp, appyCredentials.TenantId, AzureEnvironment.AzureGlobalCloud);

            return(new SignalRManagementClient(azureCredentials)
            {
                SubscriptionId = appyCredentials.SubscriptionId
            });
        }
        private IAzure GetAzureClient()
        {
            var loginInfo = new ServicePrincipalLoginInformation()
            {
                ClientId     = configuration["ARMServicePrincipalClientId"],
                ClientSecret = configuration["ARMServicePrincipalClientSecret"]
            };

            var azureCredentials = new AzureCredentials(loginInfo, configuration["TenantId"], AzureEnvironment.AzureGlobalCloud);

            return(Azure
                   .Configure()
                   .Authenticate(azureCredentials)
                   .WithDefaultSubscription());
        }
Exemplo n.º 14
0
        private static IAzure Authenticate()
        {
            //https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-create-service-principal-portal

            var servicePrincipal = new ServicePrincipalLoginInformation();

            servicePrincipal.ClientId     = "c60c8d66-caab-4359-9e1d-27e3b73fa42c";
            servicePrincipal.ClientSecret = "dBB45loRs1uc0yZjiXfIrMXPm3CvL5tOEMWv10MH5Hc=";

            AzureCredentials credentials =
                new AzureCredentials(servicePrincipal, "f988fbf0-6866-43df-8926-e451715257e8"
                                     , AzureEnvironment.AzureGlobalCloud);

            IAzure azure = Azure.Authenticate(credentials).WithDefaultSubscription();

            return(azure);
        }
Exemplo n.º 15
0
        private async Task Dns(HttpContext context)
        {
            var request = context.Request;

            if (request.Method == "PUT")
            {
                Dictionary <string, string> tokens;
                using (var reader = new StreamReader(request.Body))
                {
                    var json = await reader.ReadToEndAsync();

                    tokens = JsonConvert.DeserializeObject <Dictionary <string, string> >(json);
                }

                var path       = request.Path.ToUriComponent();
                var keyType    = Enum.Parse <KeyAlgorithm>(path.Substring(1), true);
                var accountKey = GetTestKey(keyType);

                var loginInfo = new ServicePrincipalLoginInformation
                {
                    ClientId     = Configuration["clientId"],
                    ClientSecret = Configuration["clientSecret"],
                };

                var credentials = new AzureCredentials(loginInfo, Configuration["tenantId"], AzureEnvironment.AzureGlobalCloud);
                using (var client = new DnsManagementClient(credentials))
                {
                    client.SubscriptionId = Configuration["subscriptionId"];

                    foreach (var p in tokens)
                    {
                        var name = "_acme-challenge." + p.Key.Replace(".dymetis.com", "");
                        await client.RecordSets.CreateOrUpdateAsync(
                            "dymetis",
                            "dymetis.com",
                            name,
                            RecordType.TXT,
                            new RecordSetInner(
                                name : name,
                                tTL : 1,
                                txtRecords : new[] { new TxtRecord(new[] { accountKey.SignatureKey.DnsTxt(p.Value) }) }));
                    }
                }
            }
        }
Exemplo n.º 16
0
        public virtual IAzure GetAzureService(IAzureCredential credentials)
        {
            var servicePrincipal = new ServicePrincipalLoginInformation
            {
                ClientId     = credentials.ClientId,
                ClientSecret = credentials.Key
            };

            var azureCredentials = new AzureCredentials(servicePrincipal, credentials.TenantId, AzureEnvironment.AzureGlobalCloud);

            var azure = Microsoft.Azure.Management.Fluent.Azure
                        .Configure()
                        .WithLogLevel(HttpLoggingDelegatingHandler.Level.BASIC)
                        .Authenticate(azureCredentials)
                        .WithSubscription(credentials.SubscriptionId);

            return(azure);
        }
        private void Authenticate()
        {
            string  passwordsString = File.ReadAllText(Path.Combine(config, "passwords.json"));
            JObject json            = JObject.Parse(passwordsString);
            var     user            = new ServicePrincipalLoginInformation();

            user.ClientId     = json["clientId"].Value <string>();
            user.ClientSecret = json["clientSecret"].Value <string>();
            string tenantId    = json["tenantId"].Value <string>();
            var    env         = json["azureEnvironment"].ToObject <AzureEnvironment>();
            var    credentials = new AzureCredentials(user, tenantId, env);

            azure = Azure
                    .Configure()
                    .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
                    .Authenticate(credentials)
                    .WithDefaultSubscription();
        }
Exemplo n.º 18
0
        // </snippet_purge>

        static void Main(string[] args)
        {
            /* For more information about authenticating, see:
             * https://docs.microsoft.com/en-us/dotnet/azure/dotnet-sdk-azure-authenticate?view=azure-dotnet
             */

            // <snippet_assigns>
            var service_principal_credentials = new ServicePrincipalLoginInformation();

            service_principal_credentials.ClientId     = service_principal_application_id;
            service_principal_credentials.ClientSecret = service_principal_secret;

            var credentials = SdkContext.AzureCredentialsFactory.FromServicePrincipal(service_principal_application_id, service_principal_secret, tenant_id, AzureEnvironment.AzureGlobalCloud);
            var client      = new CognitiveServicesManagementClient(credentials);

            client.SubscriptionId = subscription_id;
            // </snippet_assigns>

            // <snippet_calls>
            string resource_name   = "test_resource";
            string resource_kind   = "TextTranslation";
            string resource_sku    = "F0";
            string resource_region = "Global";

            // Uncomment to list all available resource kinds, SKUs, and locations for your Azure account:
            // list_available_kinds_skus_locations(client);

            // Create a resource with kind TextTranslation, F0 (free tier), location global.
            create_resource(client, resource_name, resource_kind, resource_sku, resource_region);

            // Uncomment to list all resources for your Azure account and resource group:
            // list_resources(client);

            // Delete the resource.
            delete_resource(client, resource_name);

            /* NOTE: When you delete a resource, it is only soft-deleted. You must also purge it. Otherwise, if you try to create another
             * resource with the same name or custom subdomain, you will receive an error stating that such a resource already exists. */
            purge_resource(client, resource_name, resource_region);

            Console.WriteLine("Press any key to exit.");
            Console.ReadKey();
            // </snippet_calls>
        }
Exemplo n.º 19
0
        public Command Define()
        {
            var cmd = new Command(CommandText, Strings.HelpCommandAzureSet)
            {
                new Option <string>(AzureTenantIdOption, Strings.HelpAzureTenantId),
                new Option <string>(AzureClientIdOption, Strings.HelpAzureClientId),
                new Option <string>(AzureSecretOption, Strings.HelpAzureSecret),
                new Option <string>(AzureSubscriptionIdOption, Strings.HelpAzureSubscriptionId),
            };

            cmd.Handler = CommandHandler.Create(async(
                                                    AzureSettings azureOptions,
                                                    IConsole console) =>
            {
                var loginInfo = new ServicePrincipalLoginInformation
                {
                    ClientId     = azureOptions.ClientId,
                    ClientSecret = azureOptions.ClientSecret,
                };

                var credentials = new AzureCredentials(
                    loginInfo, azureOptions.TenantId, AzureEnvironment.AzureGlobalCloud)
                                  .WithDefaultSubscription(azureOptions.SubscriptionId);

                var builder   = RestClient.Configure();
                var resClient = builder.WithEnvironment(AzureEnvironment.AzureGlobalCloud)
                                .WithCredentials(credentials)
                                .Build();

                var resourceGroups = await LoadResourceGroups(resClient);

                await UserSettings.SetAzureSettings(azureOptions);

                var output = new
                {
                    resourceGroups
                };

                console.WriteAsJson(output);
            });

            return(cmd);
        }
        private static ServicePrincipalLoginInformation ParseAuthFile(string authFile)
        {
            var info = new ServicePrincipalLoginInformation();

            var lines = File.ReadLines(authFile);

            if (lines.First().Trim().StartsWith("{"))
            {
                string json       = string.Join("", lines);
                var    jsonConfig = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <Dictionary <string, string> >(json);
                info.ClientId = jsonConfig["clientId"];
                if (jsonConfig.ContainsKey("clientSecret"))
                {
                    info.ClientSecret = jsonConfig["clientSecret"];
                }
            }
            else
            {
                lines.All(line =>
                {
                    if (line.Trim().StartsWith("#"))
                    {
                        return(true); // Ignore comments
                    }
                    var keyVal = line.Trim().Split(new char[] { '=' }, 2);
                    if (keyVal.Length < 2)
                    {
                        return(true); // Ignore lines that don't look like $$$=$$$
                    }
                    if (keyVal[0].Equals("client", StringComparison.OrdinalIgnoreCase))
                    {
                        info.ClientId = keyVal[1];
                    }
                    if (keyVal[0].Equals("key", StringComparison.OrdinalIgnoreCase))
                    {
                        info.ClientSecret = keyVal[1];
                    }
                    return(true);
                });
            }

            return(info);
        }
Exemplo n.º 21
0
        public static IAzure AuthenticateWithAzure(ILogger logger, AppyAzureCredentials appyCredentials)
        {
            logger.Info($"Authenticating with azure credentials");
            var sp = new ServicePrincipalLoginInformation
            {
                ClientId     = appyCredentials.ClientId,
                ClientSecret = appyCredentials.ClientSecret
            };
            var credentials        = new AzureCredentials(sp, appyCredentials.TenantId, AzureEnvironment.AzureGlobalCloud);
            var authenticatedAzure = Azure
                                     .Configure()
                                     .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
                                     .Authenticate(credentials);

            var azure = authenticatedAzure.WithSubscription(appyCredentials.SubscriptionId);

            logger.Info($"Authenticated with azure credentials");

            return(azure);
        }
Exemplo n.º 22
0
        public IAzure GetAzureContextFromServicePrincipal()
        {
            IAzure        azure;
            ISubscription subscription;

            var servicePrincipalLoginInformation = new ServicePrincipalLoginInformation()
            {
                ClientId     = this.configuration.AadClientId,
                ClientSecret = this.configuration.AadClientSecret,
            };

            var environment = new AzureEnvironment()
            {
                AuthenticationEndpoint = Constants.AadEndpointUrl,
                GraphEndpoint          = Constants.AadGraphResourceId,
                KeyVaultSuffix         = Constants.KeyVaultSuffix,
                ManagementEndpoint     = Constants.ManagementEndpointUrl,
                Name = this.configuration.AzureSubscriptionName,
                ResourceManagerEndpoint = Constants.ResourceManagerEndpointUrl,
                StorageEndpointSuffix   = Constants.StorageEndpointSuffix,
            };

            var azureCredentials = new AzureCredentials(servicePrincipalLoginInformation, this.configuration.AadTenantId, environment);

            try
            {
                this.logger.Log(LogLevel.Information, $"Authenticating with Azure");

                azure        = Azure.Authenticate(azureCredentials).WithDefaultSubscription();
                subscription = azure.GetCurrentSubscription();
            }
            catch (Exception ex)
            {
                this.logger.Log(LogLevel.Error, $"Failed to authenticate with Azure: {ex.Message}");
                throw;
            }

            this.logger.Log(LogLevel.Debug, $"Successfully authenticated with Azure subscription {subscription.DisplayName}");

            return(azure);
        }
Exemplo n.º 23
0
        // Methods

        public UpdateResult UpdateHost(string host, string ipAddress)
        {
            var hostDomain            = _configuration["Update-Settings.Host-Domain"];
            var principalConfigPrefix = "Update-Settings.";
            var clientId       = _configuration[principalConfigPrefix + ""];
            var clientSecret   = _configuration[principalConfigPrefix + ""];
            var tenantId       = _configuration[principalConfigPrefix + ""];
            var subscriptionId = _configuration[principalConfigPrefix + ""];

            var sp = new ServicePrincipalLoginInformation
            {
                ClientId     = clientId,
                ClientSecret = clientSecret
            };

            var azure = Azure.Authenticate(new AzureCredentials(sp, tenantId, AzureEnvironment.AzureGlobalCloud)).WithSubscription(subscriptionId);

            var dnsZones = azure.DnsZones.List();
            var dnsZone  = dnsZones.SingleOrDefault(z => z.Name == hostDomain);

            if (dnsZone == null)
            {
                return(UpdateResult.DnsZoneNotFound);
            }

            var recordSets = dnsZone.ARecordSets.List();
            var recordSet  = recordSets.SingleOrDefault(rs => rs.Name == host);

            if (recordSet == null)
            {
                return(UpdateResult.RecordSetNotFound);
            }

            dnsZone.Update().UpdateARecordSet(recordSet.Name)
            .WithoutIPv4Address(recordSet.IPv4Addresses[0]).WithIPv4Address(ipAddress).WithTimeToLive(60 * 5)
            .Parent().Apply();

            return(UpdateResult.Success);
        }
Exemplo n.º 24
0
        public static void Run([TimerTrigger("0 * * * * *")] TimerInfo myTimer, ILogger log)
        {
            try
            {
                log.LogInformation($"Fault Injector - VM function started at: {DateTime.Now}");
                string subListStr = Environment.GetEnvironmentVariable("targetSubscriptionIDList");
                string rgListStr  = Environment.GetEnvironmentVariable("targetRGList");
                string clientId   = Environment.GetEnvironmentVariable("clientId");
                string tenantId   = Environment.GetEnvironmentVariable("tenantId");
                string clientPwd  = Environment.GetEnvironmentVariable("clientPassword");
                string ingestConn = Environment.GetEnvironmentVariable("ingestConn");
                log.LogInformation($"Params: SubscriptionIDList: {subListStr}; RGList: {rgListStr}");

                ServicePrincipalLoginInformation spi = new ServicePrincipalLoginInformation
                {
                    ClientId     = clientId,
                    ClientSecret = clientPwd
                };
                AzureCredentials myAzCreds = new AzureCredentials(spi, tenantId, AzureEnvironment.AzureGlobalCloud);
                Microsoft.Azure.Management.Fluent.IAzure myAz = Azure.Configure().Authenticate(myAzCreds).WithSubscription(subListStr);

                foreach (string curRGName in rgListStr.Split(","))
                {
                    log.LogInformation($"Iterating over RG {curRGName}");
                    FIVM vmFuzzer = new FIVM(log, myAz, curRGName, ingestConn, "annandale", "faultInjections");
                    vmFuzzer.Fuzz(1);

                    FINSG nsgFuzzer = new FINSG(log, myAz, curRGName, ingestConn, "annandale", "faultInjections");
                    nsgFuzzer.Fuzz(25);
                }


                log.LogInformation($"Fault Injector - VM function finished at: {DateTime.Now}");
            }
            catch (Exception err)
            {
                log.LogError(err.ToString());
            }
        }
        public IAzure CreateServicePrincipal()
        {
            try
            {
                ServicePrincipalLoginInformation loginInfo = new ServicePrincipalLoginInformation()
                {
                    ClientId     = Environment.GetEnvironmentVariable("ClientId", EnvironmentVariableTarget.Machine),
                    ClientSecret = Environment.GetEnvironmentVariable("ClientSecret", EnvironmentVariableTarget.Machine)
                };

                var credentials = new AzureCredentials(loginInfo, Environment.GetEnvironmentVariable("TenantId", EnvironmentVariableTarget.Machine), AzureEnvironment.AzureGlobalCloud);
                var azureAuth   = Azure.Configure().WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic).Authenticate(credentials);
                var azure       = azureAuth.WithSubscription(Environment.GetEnvironmentVariable("SubscriptionId", EnvironmentVariableTarget.Machine));

                return(azure);
            }
            catch (Exception)
            {
            }

            return(null);
        }
Exemplo n.º 26
0
        public static AzureClient FetchAzureClient()
        {
            try
            {
                //=================================================================
                // Authenticate
                var clientId       = Environment.GetEnvironmentVariable("ARM_CLIENT_ID");
                var clientSecret   = Environment.GetEnvironmentVariable("ARM_CLIENT_SECRET");
                var subscriptionId = Environment.GetEnvironmentVariable("ARM_SUBSCRIPTION_ID");
                var tenantId       = Environment.GetEnvironmentVariable("ARM_TENANT_ID");

                ServicePrincipalLoginInformation loginInfo = new ServicePrincipalLoginInformation()
                {
                    ClientId     = clientId,
                    ClientSecret = clientSecret
                };
                var credentials = new AzureCredentials(loginInfo, tenantId, AzureEnvironment.AzureGlobalCloud);
                var azureAuth   = Microsoft.Azure.Management.Fluent.Azure.Configure()
                                  .WithLogLevel(HttpLoggingDelegatingHandler.Level.BodyAndHeaders)
                                  .Authenticate(credentials);

                var azure = Microsoft.Azure.Management.Fluent.Azure
                            .Configure()
                            .WithLogLevel(HttpLoggingDelegatingHandler.Level.BodyAndHeaders)
                            .Authenticate(credentials)
                            .WithSubscription(subscriptionId);
                return(new AzureClient()
                {
                    AzureInstance = azure,
                    AzureCredentials = credentials
                });
            }
            catch (Exception ex)
            {
                Utilities.Log(ex);
            }
            return(null);
        }
Exemplo n.º 27
0
        private static IAzure GetAzure()
        {
            var tenantId     = Environment.GetEnvironmentVariable("TenantId");
            var clientId     = Environment.GetEnvironmentVariable("ClientId");
            var clientSecret = Environment.GetEnvironmentVariable("ClientSecret");
            AzureCredentials credentials;

            if (!string.IsNullOrEmpty(tenantId) &&
                !string.IsNullOrEmpty(clientId) &&
                !string.IsNullOrEmpty(clientSecret))
            {
                var sp = new ServicePrincipalLoginInformation
                {
                    ClientId     = clientId,
                    ClientSecret = clientSecret
                };
                credentials = new AzureCredentials(sp, tenantId, AzureEnvironment.AzureGlobalCloud);
            }
            else
            {
                credentials = SdkContext
                              .AzureCredentialsFactory
                              .FromMSI(new MSILoginInformation(MSIResourceType.AppService),
                                       AzureEnvironment.AzureGlobalCloud);
            }
            var authenticatedAzure = Azure
                                     .Configure()
                                     .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
                                     .Authenticate(credentials);
            var subscriptionId = System.Environment.GetEnvironmentVariable("SubscriptionId");

            if (!string.IsNullOrEmpty(subscriptionId))
            {
                return(authenticatedAzure.WithSubscription(subscriptionId));
            }
            return(authenticatedAzure.WithDefaultSubscription());
        }
Exemplo n.º 28
0
        static void Main(string[] args)
        {
            ServicePrincipalLoginInformation login = new ServicePrincipalLoginInformation();

            login.ClientId     = "ClientID";
            login.ClientSecret = "Client Secret";

            var tenant = "Tenant ID";

            AzureCredentials credentials = new AzureCredentials(login, tenant, AzureEnvironment.AzureGlobalCloud);
            var azure = Azure.Authenticate(credentials).WithSubscription("Subscription ID");

            var windowsVM = azure.VirtualMachines.Define("ExemploFluentCDS")
                            .WithRegion(Region.BrazilSouth)
                            .WithNewResourceGroup("ResourceVMTeste")
                            .WithNewPrimaryNetwork("10.0.0.0/28")
                            .WithPrimaryPrivateIpAddressDynamic()
                            .WithNewPrimaryPublicIpAddress("exemplofluentcds")
                            .WithPopularWindowsImage(KnownWindowsVirtualMachineImage.WindowsServer2012R2Datacenter)
                            .WithAdminUsername("administrador")
                            .WithAdminPassword("Cds123456")
                            .WithSize(VirtualMachineSizeTypes.BasicA1)
                            .Create();

            var blob = azure.StorageAccounts.Define("minhaconta")
                       .WithRegion(Region.BrazilSouth)
                       .WithNewResourceGroup("ResourceBlob")
                       .Create();

            var webApp = azure.WebApps.Define("meusitecds")
                         .WithNewResourceGroup("ResurceSite")
                         .WithNewAppServicePlan("AppServicePlanNovo")
                         .WithRegion(Region.BrazilSouth)
                         .WithPricingTier(AppServicePricingTier.SharedD1)
                         .Create();
        }
Exemplo n.º 29
0
        private static RestClient CreateRestClient(string tenantId, string subscriptionId, ServicePrincipalLoginInformation loginInfo)
        {
            var credentials = new AzureCredentials(
                loginInfo, tenantId, AzureEnvironment.AzureGlobalCloud)
                              .WithDefaultSubscription(subscriptionId);

            var builder   = RestClient.Configure();
            var resClient = builder.WithEnvironment(AzureEnvironment.AzureGlobalCloud)
                            .WithCredentials(credentials)
                            .Build();

            return(resClient);
        }
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation($"{DateAndTime()} | C# HTTP trigger function processed a request.");

            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();

            ProvisioningModel provisioningModel = JsonConvert.DeserializeObject <ProvisioningModel>(requestBody);


            if (string.IsNullOrEmpty(provisioningModel.ClientId) ||
                string.IsNullOrEmpty(provisioningModel.ClientSecret) ||
                string.IsNullOrEmpty(provisioningModel.TenantId) ||
                string.IsNullOrEmpty(provisioningModel.SubscriptionId) ||
                string.IsNullOrEmpty(provisioningModel.ClustrerName) ||
                string.IsNullOrEmpty(provisioningModel.ResourceGroupName) ||
                string.IsNullOrEmpty(provisioningModel.MainVhdURL) ||
                string.IsNullOrEmpty(provisioningModel.SmtpServer) ||
                string.IsNullOrEmpty(provisioningModel.SmtpPort.ToString()) ||
                string.IsNullOrEmpty(provisioningModel.SmtpEmail) ||
                string.IsNullOrEmpty(provisioningModel.SmtpPassword))
            {
                log.LogInformation($"{DateAndTime()} | Error |  Missing parameter | \n{requestBody}");
                return(new BadRequestObjectResult(false));
            }
            else
            {
                bool isSingleInstance;

                switch (provisioningModel.InstanceCount)
                {
                case "1": { isSingleInstance = true; break; }

                case "3": {
                    isSingleInstance = false;
                    if (
                        string.IsNullOrEmpty(provisioningModel.MysqlVhdURL) ||
                        string.IsNullOrEmpty(provisioningModel.MongoVhdURL))
                    {
                        log.LogInformation($"{DateAndTime()} | Error | Missing parameter for 3 instance (MysqlVhdURL/MongoVhdURL) | \n{requestBody}");
                        return(new BadRequestObjectResult(false));
                    }
                    break;
                }

                default:
                {
                    log.LogInformation($"{DateAndTime()} | Error | Please set valid instance count (1 or 3) | \n{requestBody}");
                    return(new BadRequestObjectResult(false));
                }
                }

                SmtpClient smtpClient = new SmtpClient()
                {
                    Host                  = provisioningModel.SmtpServer,
                    Port                  = provisioningModel.SmtpPort,
                    EnableSsl             = true,
                    UseDefaultCredentials = false,
                    Credentials           = new NetworkCredential(provisioningModel.SmtpEmail, provisioningModel.SmtpPassword)
                };

                MailMessage mailMessage = new MailMessage();

                mailMessage.From = new MailAddress(provisioningModel.SmtpEmail);
                mailMessage.To.Add(new MailAddress(provisioningModel.SmtpEmail));
                mailMessage.Subject = "Branch Academy Installation";

                try
                {
                    string resourceGroupName = provisioningModel.ResourceGroupName;
                    string clusterName       = provisioningModel.ClustrerName;
                    string MainVhdURL        = provisioningModel.MainVhdURL;
                    string MysqlVhdURL       = provisioningModel.MysqlVhdURL;
                    string MongoVhdURL       = provisioningModel.MongoVhdURL;
                    string subnet            = "default";
                    string username          = provisioningModel.Username;
                    string password          = provisioningModel.Password;

                    string contactPerson = provisioningModel.SmtpEmail;

                    log.LogInformation("deploying Main instance");
                    Utils.Email(smtpClient, "Main Instance Deployed Successfully", log, mailMessage);

                    ServicePrincipalLoginInformation principalLogIn = new ServicePrincipalLoginInformation();
                    principalLogIn.ClientId     = provisioningModel.ClientId;
                    principalLogIn.ClientSecret = provisioningModel.ClientSecret;

                    AzureEnvironment environment = AzureEnvironment.AzureGlobalCloud;
                    AzureCredentials credentials = new AzureCredentials(principalLogIn, provisioningModel.TenantId, environment);

                    IAzure _azureProd = Azure.Configure()
                                        .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
                                        .Authenticate(credentials)
                                        .WithSubscription(provisioningModel.SubscriptionId);


                    IResourceGroup resourceGroup = _azureProd.ResourceGroups.GetByName(resourceGroupName);
                    Region         region        = resourceGroup.Region;

                    #region comment

                    #region Create Virtual Network
                    INetwork virtualNetwork = _azureProd.Networks.Define($"{clusterName}-vnet")
                                              .WithRegion(region)
                                              .WithExistingResourceGroup(resourceGroupName)
                                              .WithAddressSpace("10.0.0.0/16")
                                              .DefineSubnet(subnet)
                                              .WithAddressPrefix("10.0.0.0/24")
                                              .Attach()
                                              .WithTag("_contact_person", contactPerson)
                                              .Create();

                    #endregion

                    log.LogInformation($"{DateAndTime()} | Created | VNET");

                    #region Create VM IP
                    IPublicIPAddress publicIpAddress = _azureProd.PublicIPAddresses.Define($"{clusterName}-vm-ip")
                                                       .WithRegion(region)
                                                       .WithExistingResourceGroup(resourceGroupName)
                                                       .WithDynamicIP()
                                                       .WithLeafDomainLabel(clusterName)
                                                       .WithTag("_contact_person", contactPerson)
                                                       .Create();
                    #endregion

                    log.LogInformation($"{DateAndTime()} | Created | VM IP Address");

                    #region NSG
                    INetworkSecurityGroup networkSecurityGroup = _azureProd.NetworkSecurityGroups.Define($"{clusterName}-nsg")
                                                                 .WithRegion(region)
                                                                 .WithExistingResourceGroup(resourceGroupName)
                                                                 .DefineRule("ALLOW-SSH")
                                                                 .AllowInbound()
                                                                 .FromAnyAddress()
                                                                 .FromAnyPort()
                                                                 .ToAnyAddress()
                                                                 .ToPort(22)
                                                                 .WithProtocol(SecurityRuleProtocol.Tcp)
                                                                 .WithPriority(100)
                                                                 .WithDescription("Allow SSH")
                                                                 .Attach()
                                                                 .DefineRule("LMS")
                                                                 .AllowInbound()
                                                                 .FromAnyAddress()
                                                                 .FromAnyPort()
                                                                 .ToAnyAddress()
                                                                 .ToPort(80)
                                                                 .WithProtocol(SecurityRuleProtocol.Tcp)
                                                                 .WithPriority(101)
                                                                 .WithDescription("LMS")
                                                                 .Attach()
                                                                 .DefineRule("CMS")
                                                                 .AllowInbound()
                                                                 .FromAnyAddress()
                                                                 .FromAnyPort()
                                                                 .ToAnyAddress()
                                                                 .ToPort(18010)
                                                                 .WithProtocol(SecurityRuleProtocol.Tcp)
                                                                 .WithPriority(102)
                                                                 .WithDescription("CMS")
                                                                 .Attach()
                                                                 .DefineRule("CMSSSLPort")
                                                                 .AllowInbound()
                                                                 .FromAnyAddress()
                                                                 .FromAnyPort()
                                                                 .ToAnyAddress()
                                                                 .ToPort(48010)
                                                                 .WithProtocol(SecurityRuleProtocol.Tcp)
                                                                 .WithPriority(112)
                                                                 .WithDescription("CMSSSLPort")
                                                                 .Attach()
                                                                 .DefineRule("LMSSSLPort")
                                                                 .AllowInbound()
                                                                 .FromAnyAddress()
                                                                 .FromAnyPort()
                                                                 .ToAnyAddress()
                                                                 .ToPort(443)
                                                                 .WithProtocol(SecurityRuleProtocol.Tcp)
                                                                 .WithPriority(122)
                                                                 .WithDescription("LMSSSLPort")
                                                                 .Attach()
                                                                 .DefineRule("Certs")
                                                                 .AllowInbound()
                                                                 .FromAnyAddress()
                                                                 .FromAnyPort()
                                                                 .ToAnyAddress()
                                                                 .ToPort(18090)
                                                                 .WithProtocol(SecurityRuleProtocol.Tcp)
                                                                 .WithPriority(132)
                                                                 .WithDescription("Certs")
                                                                 .Attach()
                                                                 .DefineRule("Discovery")
                                                                 .AllowInbound()
                                                                 .FromAnyAddress()
                                                                 .FromAnyPort()
                                                                 .ToAnyAddress()
                                                                 .ToPort(18381)
                                                                 .WithProtocol(SecurityRuleProtocol.Tcp)
                                                                 .WithPriority(142)
                                                                 .WithDescription("Discovery")
                                                                 .Attach()
                                                                 .DefineRule("Ecommerce")
                                                                 .AllowInbound()
                                                                 .FromAnyAddress()
                                                                 .FromAnyPort()
                                                                 .ToAnyAddress()
                                                                 .ToPort(18130)
                                                                 .WithProtocol(SecurityRuleProtocol.Tcp)
                                                                 .WithPriority(152)
                                                                 .WithDescription("Ecommerce")
                                                                 .Attach()
                                                                 .DefineRule("edx-release")
                                                                 .AllowInbound()
                                                                 .FromAnyAddress()
                                                                 .FromAnyPort()
                                                                 .ToAnyAddress()
                                                                 .ToPort(8099)
                                                                 .WithProtocol(SecurityRuleProtocol.Tcp)
                                                                 .WithPriority(162)
                                                                 .WithDescription("edx-release")
                                                                 .Attach()
                                                                 .DefineRule("Forum")
                                                                 .AllowInbound()
                                                                 .FromAnyAddress()
                                                                 .FromAnyPort()
                                                                 .ToAnyAddress()
                                                                 .ToPort(18080)
                                                                 .WithProtocol(SecurityRuleProtocol.Tcp)
                                                                 .WithPriority(172)
                                                                 .WithDescription("Forum")
                                                                 .Attach()
                                                                 .WithTag("_contact_person", contactPerson)
                                                                 .DefineRule("Xqueue")
                                                                 .AllowInbound()
                                                                 .FromAnyAddress()
                                                                 .FromAnyPort()
                                                                 .ToAnyAddress()
                                                                 .ToPort(18040)
                                                                 .WithProtocol(SecurityRuleProtocol.Tcp)
                                                                 .WithPriority(182)
                                                                 .WithDescription("Xqueue")
                                                                 .Attach()
                                                                 .WithTag("_contact_person", contactPerson)
                                                                 .Create();
                    #endregion

                    log.LogInformation($"{DateAndTime()} | Created | Network Security Group");

                    #region nic
                    INetworkInterface networkInterface = _azureProd.NetworkInterfaces.Define($"{clusterName}-nic")
                                                         .WithRegion(region)
                                                         .WithExistingResourceGroup(resourceGroupName)
                                                         .WithExistingPrimaryNetwork(virtualNetwork)
                                                         .WithSubnet(subnet)
                                                         .WithPrimaryPrivateIPAddressDynamic()
                                                         .WithExistingPrimaryPublicIPAddress(publicIpAddress)
                                                         .WithExistingNetworkSecurityGroup(networkSecurityGroup)
                                                         .WithTag("_contact_person", contactPerson)
                                                         .Create();
                    #endregion

                    log.LogInformation($"{DateAndTime()} | Created | Network Interface");

                    IStorageAccount storageAccount = _azureProd.StorageAccounts.GetByResourceGroup(resourceGroupName, $"{clusterName}vhdsa");

                    #region vm
                    IVirtualMachine createVm = _azureProd.VirtualMachines.Define($"{clusterName}-jb")
                                               .WithRegion(region)
                                               .WithExistingResourceGroup(resourceGroupName)
                                               .WithExistingPrimaryNetworkInterface(networkInterface)
                                               .WithStoredLinuxImage(MainVhdURL)
                                               .WithRootUsername(username)
                                               .WithRootPassword(password)
                                               .WithComputerName(username)
                                               .WithBootDiagnostics(storageAccount)
                                               .WithSize(VirtualMachineSizeTypes.StandardD2sV3)
                                               .WithTag("_contact_person", contactPerson)
                                               .Create();
                    #endregion

                    log.LogInformation($"{DateAndTime()} | Created | Main Virtual Machine");

                    #region LMS IP
                    IPublicIPAddress publicIPAddressLMS = _azureProd.PublicIPAddresses.Define($"{clusterName}-lms-ip")
                                                          .WithRegion(region)
                                                          .WithExistingResourceGroup(resourceGroupName)
                                                          .WithDynamicIP()
                                                          .WithLeafDomainLabel($"{clusterName}-lms-ip")
                                                          .WithTag("_contact_person", contactPerson)
                                                          .Create();
                    #endregion

                    log.LogInformation($"{DateAndTime()} | Created | LMS Public IP Address");

                    #region CMS IP
                    IPublicIPAddress publicIPAddressCMS = _azureProd.PublicIPAddresses.Define($"{clusterName}-cms-ip")
                                                          .WithRegion(region)
                                                          .WithExistingResourceGroup(resourceGroupName)
                                                          .WithDynamicIP()
                                                          .WithLeafDomainLabel($"{clusterName}-cms-ip")
                                                          .WithTag("_contact_person", contactPerson)
                                                          .Create();
                    #endregion

                    log.LogInformation($"{DateAndTime()} | Created | CMS Public IP Address");

                    #region LoadBalancer
                    ILoadBalancer loadBalancer = _azureProd.LoadBalancers.Define($"{clusterName}-lb")
                                                 .WithRegion(region)
                                                 .WithExistingResourceGroup(resourceGroupName)

                                                 .DefineLoadBalancingRule("LBRuleCMS")
                                                 .WithProtocol(TransportProtocol.Tcp)
                                                 .FromFrontend("CMS")
                                                 .FromFrontendPort(80)
                                                 .ToBackend($"{clusterName}-bepool")
                                                 .ToBackendPort(18010)
                                                 .WithProbe("tcpProbeCMS")
                                                 .WithFloatingIPDisabled()
                                                 .Attach()

                                                 .DefineLoadBalancingRule("LBRuleCMS_SSL")
                                                 .WithProtocol(TransportProtocol.Tcp)
                                                 .FromFrontend("CMS")
                                                 .FromFrontendPort(443)
                                                 .ToBackend($"{clusterName}-bepool")
                                                 .ToBackendPort(48010)
                                                 .WithProbe("tcpProbeCMSSSL")
                                                 .WithFloatingIPDisabled()
                                                 .Attach()

                                                 .DefineLoadBalancingRule("LBRuleLMS")
                                                 .WithProtocol(TransportProtocol.Tcp)
                                                 .FromFrontend("LMS")
                                                 .FromFrontendPort(80)
                                                 .ToBackend($"{clusterName}-bepool")
                                                 .ToBackendPort(80)
                                                 .WithProbe("tcpProbeLMS")
                                                 .WithFloatingIPDisabled()
                                                 .Attach()

                                                 .DefineLoadBalancingRule("LBRuleLMS_SSL")
                                                 .WithProtocol(TransportProtocol.Tcp)
                                                 .FromFrontend("LMS")
                                                 .FromFrontendPort(443)
                                                 .ToBackend($"{clusterName}-bepool")
                                                 .ToBackendPort(443)
                                                 .WithProbe("tcpProbeLMSSSL")
                                                 .WithFloatingIPDisabled()
                                                 .Attach()

                                                 .DefineBackend($"{clusterName}-bepool")
                                                 .WithExistingVirtualMachines(createVm)
                                                 .Attach()

                                                 .DefinePublicFrontend("LMS")
                                                 .WithExistingPublicIPAddress(publicIPAddressLMS)
                                                 .Attach()

                                                 .DefinePublicFrontend("CMS")
                                                 .WithExistingPublicIPAddress(publicIPAddressCMS)
                                                 .Attach()

                                                 .DefineHttpProbe("tcpProbeCMS")
                                                 .WithRequestPath("/heartbeat")
                                                 .WithPort(18010)
                                                 .WithIntervalInSeconds(5)
                                                 .WithNumberOfProbes(6)
                                                 .Attach()

                                                 .DefineTcpProbe("tcpProbeCMSSSL")
                                                 .WithPort(48010)
                                                 .WithIntervalInSeconds(5)
                                                 .WithNumberOfProbes(6)
                                                 .Attach()

                                                 .DefineHttpProbe("tcpProbeLMS")
                                                 .WithRequestPath("/heartbeat")
                                                 .WithPort(80)
                                                 .WithIntervalInSeconds(5)
                                                 .WithNumberOfProbes(6)
                                                 .Attach()

                                                 .DefineTcpProbe("tcpProbeLMSSSL")
                                                 .WithPort(443)
                                                 .WithIntervalInSeconds(5)
                                                 .WithNumberOfProbes(6)
                                                 .Attach()
                                                 .WithTag("_contact_person", contactPerson)
                                                 .Create();
                    #endregion

                    log.LogInformation($"{DateAndTime()} | Created | Load Balancer");

                    #region tm
                    IWithEndpoint tmDefinitionLMS = _azureProd.TrafficManagerProfiles
                                                    .Define($"{clusterName}-lms-tm")
                                                    .WithExistingResourceGroup(resourceGroupName)
                                                    .WithLeafDomainLabel($"{clusterName}-lms-tm")
                                                    .WithPriorityBasedRouting();
                    ICreatable <ITrafficManagerProfile> tmCreatableLMS = null;

                    tmCreatableLMS = tmDefinitionLMS
                                     .DefineExternalTargetEndpoint($"{clusterName}-lms-tm")
                                     .ToFqdn(publicIPAddressLMS.Fqdn)
                                     .FromRegion(region)
                                     .WithRoutingPriority(1)
                                     .Attach()
                                     .WithTag("_contact_person", contactPerson);

                    ITrafficManagerProfile trafficManagerProfileLMS = tmCreatableLMS.Create();

                    log.LogInformation($"{DateAndTime()} | Created | LMS Traffic Manager");

                    IWithEndpoint tmDefinitionCMS = _azureProd.TrafficManagerProfiles
                                                    .Define($"{clusterName}-cms-tm")
                                                    .WithExistingResourceGroup(resourceGroupName)
                                                    .WithLeafDomainLabel($"{clusterName}-cms-tm")
                                                    .WithPriorityBasedRouting();
                    ICreatable <ITrafficManagerProfile> tmCreatableCMS = null;

                    tmCreatableCMS = tmDefinitionCMS
                                     .DefineExternalTargetEndpoint($"{clusterName}-cms-tm")
                                     .ToFqdn(publicIPAddressCMS.Fqdn)
                                     .FromRegion(region)
                                     .WithRoutingPriority(1)
                                     .Attach()
                                     .WithTag("_contact_person", contactPerson);

                    ITrafficManagerProfile trafficManagerProfileCMS = tmCreatableCMS.Create();

                    log.LogInformation($"{DateAndTime()} | Created | CMS Traffic Manager");

                    #endregion

                    #endregion

                    if (!isSingleInstance)
                    {
                        #region mysql
                        INetworkSecurityGroup networkSecurityGroupmysql = _azureProd.NetworkSecurityGroups.Define($"{clusterName}-mysql-nsg")
                                                                          .WithRegion(region)
                                                                          .WithExistingResourceGroup(resourceGroup)
                                                                          .DefineRule("ALLOW-SSH")
                                                                          .AllowInbound()
                                                                          .FromAnyAddress()
                                                                          .FromAnyPort()
                                                                          .ToAnyAddress()
                                                                          .ToPort(22)
                                                                          .WithProtocol(SecurityRuleProtocol.Tcp)
                                                                          .WithPriority(100)
                                                                          .WithDescription("Allow SSH")
                                                                          .Attach()
                                                                          .DefineRule("mysql")
                                                                          .AllowInbound()
                                                                          .FromAnyAddress()
                                                                          .FromAnyPort()
                                                                          .ToAnyAddress()
                                                                          .ToPort(3306)
                                                                          .WithProtocol(SecurityRuleProtocol.Tcp)
                                                                          .WithPriority(101)
                                                                          .WithDescription("mysql")
                                                                          .Attach()
                                                                          .WithTag("_contact_person", contactPerson)
                                                                          .Create();

                        log.LogInformation($"{DateAndTime()} | Created | MySQL Network Security Group");

                        INetworkInterface networkInterfacemysql = _azureProd.NetworkInterfaces.Define($"{clusterName}-mysql-nic")
                                                                  .WithRegion(region)
                                                                  .WithExistingResourceGroup(resourceGroup)
                                                                  .WithExistingPrimaryNetwork(virtualNetwork)
                                                                  .WithSubnet(subnet)
                                                                  .WithPrimaryPrivateIPAddressDynamic()
                                                                  .WithExistingNetworkSecurityGroup(networkSecurityGroupmysql)
                                                                  .WithTag("_contact_person", contactPerson)
                                                                  .Create();

                        log.LogInformation($"{DateAndTime()} | Created | MySQL Network Interface");

                        IVirtualMachine createVmmysql = _azureProd.VirtualMachines.Define($"{clusterName}-mysql")
                                                        .WithRegion(region)
                                                        .WithExistingResourceGroup(resourceGroup)
                                                        .WithExistingPrimaryNetworkInterface(networkInterfacemysql)
                                                        .WithStoredLinuxImage(MysqlVhdURL)
                                                        .WithRootUsername(username)
                                                        .WithRootPassword(password)
                                                        .WithComputerName("mysql")
                                                        .WithBootDiagnostics(storageAccount)
                                                        .WithSize(VirtualMachineSizeTypes.StandardD2V2)
                                                        .WithTag("_contact_person", contactPerson)
                                                        .Create();

                        log.LogInformation($"{DateAndTime()} | Created | MySQL Virtual Machine");

                        #endregion

                        #region mongodb
                        INetworkSecurityGroup networkSecurityGroupmongo = _azureProd.NetworkSecurityGroups.Define($"{clusterName}-mongo-nsg")
                                                                          .WithRegion(region)
                                                                          .WithExistingResourceGroup(resourceGroup)
                                                                          .DefineRule("ALLOW-SSH")
                                                                          .AllowInbound()
                                                                          .FromAnyAddress()
                                                                          .FromAnyPort()
                                                                          .ToAnyAddress()
                                                                          .ToPort(22)
                                                                          .WithProtocol(SecurityRuleProtocol.Tcp)
                                                                          .WithPriority(100)
                                                                          .WithDescription("Allow SSH")
                                                                          .Attach()
                                                                          .DefineRule("mongodb")
                                                                          .AllowInbound()
                                                                          .FromAnyAddress()
                                                                          .FromAnyPort()
                                                                          .ToAnyAddress()
                                                                          .ToPort(27017)
                                                                          .WithProtocol(SecurityRuleProtocol.Tcp)
                                                                          .WithPriority(101)
                                                                          .WithDescription("mongodb")
                                                                          .Attach()
                                                                          .WithTag("_contact_person", contactPerson)
                                                                          .Create();

                        log.LogInformation($"{DateAndTime()} | Created | MongoDB Network Security Group");

                        INetworkInterface networkInterfacemongo = _azureProd.NetworkInterfaces.Define($"{clusterName}-mongo-nic")
                                                                  .WithRegion(region)
                                                                  .WithExistingResourceGroup(resourceGroup)
                                                                  .WithExistingPrimaryNetwork(virtualNetwork)
                                                                  .WithSubnet(subnet)
                                                                  .WithPrimaryPrivateIPAddressDynamic()
                                                                  .WithExistingNetworkSecurityGroup(networkSecurityGroupmongo)
                                                                  .WithTag("_contact_person", contactPerson)
                                                                  .Create();

                        log.LogInformation($"{DateAndTime()} | Created | MongoDB Network Interface");

                        IVirtualMachine createVmmongo = _azureProd.VirtualMachines.Define($"{clusterName}-mongo")
                                                        .WithRegion(region)
                                                        .WithExistingResourceGroup(resourceGroup)
                                                        .WithExistingPrimaryNetworkInterface(networkInterfacemongo)
                                                        .WithStoredLinuxImage(MongoVhdURL)
                                                        .WithRootUsername(username)
                                                        .WithRootPassword(password)
                                                        .WithComputerName("mongo")
                                                        .WithBootDiagnostics(storageAccount)
                                                        .WithSize(VirtualMachineSizeTypes.StandardD2V2)
                                                        .WithTag("_contact_person", contactPerson)
                                                        .Create();

                        log.LogInformation($"{DateAndTime()} | Created | MongoDB Virtual Machine");

                        #endregion

                        log.LogInformation("deploying 3 instance");

                        Utils.Email(smtpClient, "MySQL Instance Deployed Successfully", log, mailMessage);
                    }


                    string cmsUrl = trafficManagerProfileCMS.DnsLabel;
                    string lmsUrl = trafficManagerProfileLMS.DnsLabel;

                    Utils.Email(smtpClient, "Your Learning Platform is Ready to use." +
                                "<br/>"
                                + $"<a href=\"{lmsUrl}\">LMS</a>" +
                                "<br/>" +
                                $"<a href=\"{cmsUrl}\">CMS</a>"
                                , log, mailMessage);
                    log.LogInformation($"Done");
                }
                catch (Exception e)
                {
                    log.LogInformation($"{DateAndTime()} | Error | {e.Message}");

                    return(new BadRequestObjectResult(false));
                }

                log.LogInformation($"{DateAndTime()} | Done");
                return(new OkObjectResult(true));
            }
        }