public async Task Setup()
        {
            azureConfigPath = TemporaryDirectory.Create();
            Environment.SetEnvironmentVariable("AZURE_CONFIG_DIR", azureConfigPath.DirectoryPath);

            clientId       = ExternalVariables.Get(ExternalVariable.AzureSubscriptionClientId);
            clientSecret   = ExternalVariables.Get(ExternalVariable.AzureSubscriptionPassword);
            tenantId       = ExternalVariables.Get(ExternalVariable.AzureSubscriptionTenantId);
            subscriptionId = ExternalVariables.Get(ExternalVariable.AzureSubscriptionId);
            var resourceGroupName = SdkContext.RandomResourceName(nameof(DeployAzureWebCommandFixture), 60);

            var credentials = SdkContext.AzureCredentialsFactory.FromServicePrincipal(clientId, clientSecret, tenantId,
                                                                                      AzureEnvironment.AzureGlobalCloud);

            azure = Azure
                    .Configure()
                    .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
                    .Authenticate(credentials)
                    .WithSubscription(subscriptionId);

            resourceGroup = await azure.ResourceGroups
                            .Define(resourceGroupName)
                            .WithRegion(Region.USWest)
                            .CreateAsync();

            appServicePlan = await azure.AppServices.AppServicePlans
                             .Define(SdkContext.RandomResourceName(nameof(DeployAzureWebCommandFixture), 60))
                             .WithRegion(resourceGroup.Region)
                             .WithExistingResourceGroup(resourceGroup)
                             .WithPricingTier(PricingTier.StandardS1)
                             .WithOperatingSystem(OperatingSystem.Windows)
                             .CreateAsync();
        }
Exemplo n.º 2
0
        public static void Print(IAppServicePlan resource)
        {
            var builder = new StringBuilder().Append("App service certificate order: ").Append(resource.Id)
                          .Append("Name: ").Append(resource.Name)
                          .Append("\n\tResource group: ").Append(resource.ResourceGroupName)
                          .Append("\n\tRegion: ").Append(resource.Region)
                          .Append("\n\tPricing tier: ").Append(resource.PricingTier);

            Utilities.Log(builder.ToString());
        }
Exemplo n.º 3
0
 ///GENMHASH:934D38FBA69BF2F25673598C416DD202:E29466D1FE6AACE8059987F066EC1188
 public virtual FluentImplT WithExistingAppServicePlan(IAppServicePlan appServicePlan)
 {
     Inner.ServerFarmId = appServicePlan.Id;
     WithOperatingSystem(appServicePlan.OperatingSystem);
     if (newGroup != null && IsInCreateMode)
     {
         ((IndexableRefreshableWrapper <IResourceGroup, ResourceGroupInner>)newGroup).Inner.Location = appServicePlan.RegionName;
     }
     this.WithRegion(appServicePlan.RegionName);
     return((FluentImplT)this);
 }
        public static void ScaleUpDown(IAppServicePlan appServicePlan)
        {
            WriteSection("Applying a possible scale up/down fix");
            PricingTier _default = appServicePlan.PricingTier;
            PricingTier _next    = GetNextTier(_default);

            Log("Scaling Up App Service Plan: " + _next.ToString());
            appServicePlan.Update().WithPricingTier(_next).Apply();
            LetsWaitALittle();
            Log("Scaling Down App Service Plan: " + _default.ToString());
            appServicePlan.Update().WithPricingTier(_default).Apply();
            LetsWaitALittle();
        }
Exemplo n.º 5
0
        public async ValueTask <IAppServicePlan> ProvisionPlanAsync(
            string projectName,
            string environment,
            IResourceGroup resourceGroup)
        {
            string planName = $"{projectName}-PLAN-{environment}".ToUpper();

            this.loggingBroker.LogActivity(message: $"Provisioning {planName}...");

            IAppServicePlan plan =
                await this.cloudBroker.CreatePlanAsync(planName, resourceGroup);

            this.loggingBroker.LogActivity(message: $"{plan} Provisioned");

            return(plan);
        }
Exemplo n.º 6
0
 public async ValueTask <IWebApp> CreateWebAppAsync(
     string webAppName,
     string databaseConnectionString,
     IAppServicePlan plan,
     IResourceGroup resourceGroup)
 {
     return(await this.azure.AppServices.WebApps
            .Define(webAppName)
            .WithExistingWindowsPlan(plan)
            .WithExistingResourceGroup(resourceGroup)
            .WithNetFrameworkVersion(NetFrameworkVersion.Parse("v6.0"))
            .WithConnectionString(
                name: "DefaultConnect",
                value: databaseConnectionString,
                type: ConnectionStringType.SQLAzure)
            .CreateAsync());
 }
        public static void RunQuickFix(IAzure azure, string rg, string app)
        {
            IWebApp app1 = azure.WebApps
                           .GetByResourceGroup(rg, app);

            IAppServicePlan plan = azure.AppServices.AppServicePlans.GetById(app1.AppServicePlanId);

            WriteSection("APP SERVICE INFO");
            Log("Web App: " + app1.Name);
            Log("App Service Plan: " + plan.Name);
            Log("App Service Plan Tier: " + plan.PricingTier.ToString());

            StopStart(app1);
            ScaleUpDown(plan);

            WriteSection("QUICK FIX COMPLETED! CHECK SITE\n" +
                         "https://" + app1.Name + ".azurewebsites.net/");
        }
Exemplo n.º 8
0
        private async ValueTask ProvisionAsync(
            string projectName,
            CloudAction cloudAction)
        {
            List <string> environments = RetrieveEnvironments(cloudAction);

            foreach (string environmentName in environments)
            {
                IResourceGroup resourceGroup = await this.cloudManagementService
                                               .ProvisionResourceGroupAsync(
                    projectName,
                    environmentName);

                IAppServicePlan appServicePlan = await this.cloudManagementService
                                                 .ProvisionPlanAsync(
                    projectName,
                    environmentName,
                    resourceGroup);

                ISqlServer sqlServer = await this.cloudManagementService
                                       .ProvisionSqlServerAsync(
                    projectName,
                    environmentName,
                    resourceGroup);

                SqlDatabase sqlDatabase = await this.cloudManagementService
                                          .ProvisionSqlDatabaseAsync(
                    projectName,
                    environmentName,
                    sqlServer);

                IWebApp webApp = await this.cloudManagementService
                                 .ProvisionWebAppAsync(
                    projectName,
                    environmentName,
                    sqlDatabase.ConnectionString,
                    resourceGroup,
                    appServicePlan);
            }
        }
Exemplo n.º 9
0
        public async ValueTask <IWebApp> ProvisionWebAppAsync(
            string projectName,
            string environment,
            string databaseConnectionString,
            IResourceGroup resourceGroup,
            IAppServicePlan appServicePlan)
        {
            string webAppName = $"{projectName}-{environment}".ToLower();

            this.loggingBroker.LogActivity(message: $"Provisioning {webAppName}");

            IWebApp webApp =
                await this.cloudBroker.CreateWebAppAsync(
                    webAppName,
                    databaseConnectionString,
                    appServicePlan,
                    resourceGroup);

            this.loggingBroker.LogActivity(message: $"{webAppName} Provisioned");

            return(webApp);
        }
Exemplo n.º 10
0
        // Creates a web app under a new app service plan and cleans up those resources when done
        public static void ConfigureAppService(IAzure azure)
        {
            string appName = "MyConfiguredApp";
            string rgName  = "MyConfiguredRG";

            Console.WriteLine("Creating resource group, app service plan and web app.");

            // Create Web app in a new resource group with a new app service plan
            var webApp = azure.WebApps.Define(appName).WithRegion(Region.USWest).WithNewResourceGroup(rgName).WithNewWindowsPlan(PricingTier.StandardS1).Create();
            var plan   = webApp.AppServicePlanId;

            Console.WriteLine("Resources created. Check portal.azure.com");
            Console.WriteLine("Press any key to scale up app service.");
            Console.ReadLine();
            Console.WriteLine("Scaling up the app service.");

            // Scale out the app service
            IAppServicePlan appPlan = azure.AppServices.AppServicePlans.GetById(plan);

            appPlan.Update().WithCapacity(appPlan.Capacity * 2).Apply();


            Console.WriteLine("App service scaled up.");
            Console.WriteLine("Press any key to clean up resources.");
            Console.ReadLine();
            Console.WriteLine("Cleaning up resources.");

            // Delete resources one-by-one
            // Note: might be most efficient to delete by resource group, but wanted to learn code for each piece. (This is a learning exercise afterall!)
            azure.WebApps.DeleteById(webApp.Id);

            azure.AppServices.AppServicePlans.DeleteById(plan);

            azure.ResourceGroups.DeleteByName(rgName);

            Console.WriteLine("Resources cleaned.");
        }
Exemplo n.º 11
0
 private static IWebApp CreateWebApp(IAzure azure, IAppServiceDomain domain, string rgName, string name, IAppServicePlan plan)
 {
     return(azure.WebApps.Define(name)
            .WithExistingWindowsPlan(plan)
            .WithExistingResourceGroup(rgName)
            .WithManagedHostnameBindings(domain, name)
            .DefineSslBinding()
            .ForHostname(name + "." + domain.Name)
            .WithPfxCertificateToUpload(Path.Combine(Utilities.ProjectPath, "Asset", pfxPath), CERT_PASSWORD)
            .WithSniBasedSsl()
            .Attach()
            .DefineSourceControl()
            .WithPublicGitRepository("https://github.Com/jianghaolu/azure-site-test")
            .WithBranch("master")
            .Attach()
            .Create());
 }
Exemplo n.º 12
0
 ///GENMHASH:8E1D3700A243EE806EC812A6D7F6CAE3:CB5ABC6F0B7D23F2B39F2E5148275C79
 public WebAppImpl WithExistingLinuxPlan(IAppServicePlan appServicePlan)
 {
     return(WithExistingAppServicePlan(appServicePlan));
 }
Exemplo n.º 13
0
 ///GENMHASH:2460CA25AB23358958E16CE251EDCDED:CB5ABC6F0B7D23F2B39F2E5148275C79
 public WebAppImpl WithExistingWindowsPlan(IAppServicePlan appServicePlan)
 {
     return(WithExistingAppServicePlan(appServicePlan));
 }
        /**
         * Azure App Service basic sample for managing function apps.
         *  - Create 3 function apps under the same new app service plan:
         *    - 1, 2 are in the same resource group, 3 in a different one
         *    - 1, 3 are under the same consumption plan, 2 under a basic app service plan
         *  - List function apps
         *  - Delete a function app
         */

        public static void RunSample(IAzure azure)
        {
            // New resources
            string app1Name = SdkContext.RandomResourceName("webapp1-", 20);
            string app2Name = SdkContext.RandomResourceName("webapp2-", 20);
            string app3Name = SdkContext.RandomResourceName("webapp3-", 20);
            string rg1Name  = SdkContext.RandomResourceName("rg1NEMV_", 24);
            string rg2Name  = SdkContext.RandomResourceName("rg2NEMV_", 24);

            try
            {
                //============================================================
                // Create a function app with a new app service plan

                Utilities.Log("Creating function app " + app1Name + " in resource group " + rg1Name + "...");

                IFunctionApp app1 = azure.AppServices.FunctionApps
                                    .Define(app1Name)
                                    .WithRegion(Region.USWest)
                                    .WithNewResourceGroup(rg1Name)
                                    .Create();

                Utilities.Log("Created function app " + app1.Name);
                Utilities.Print(app1);

                //============================================================
                // Create a second function app with the same app service plan

                Utilities.Log("Creating another function app " + app2Name + " in resource group " + rg1Name + "...");
                IAppServicePlan plan = azure.AppServices.AppServicePlans.GetById(app1.AppServicePlanId);
                IFunctionApp    app2 = azure.AppServices.FunctionApps
                                       .Define(app2Name)
                                       .WithRegion(Region.USWest)
                                       .WithExistingResourceGroup(rg1Name)
                                       .WithNewAppServicePlan(PricingTier.BasicB1)
                                       .Create();

                Utilities.Log("Created function app " + app2.Name);
                Utilities.Print(app2);

                //============================================================
                // Create a third function app with the same app service plan, but
                // in a different resource group

                Utilities.Log("Creating another function app " + app3Name + " in resource group " + rg2Name + "...");
                IFunctionApp app3 = azure.AppServices.FunctionApps
                                    .Define(app3Name)
                                    .WithExistingAppServicePlan(plan)
                                    .WithNewResourceGroup(rg2Name)
                                    .Create();

                Utilities.Log("Created function app " + app3.Name);
                Utilities.Print(app3);

                //============================================================
                // stop and start app1, restart app 2
                Utilities.Log("Stopping function app " + app1.Name);
                app1.Stop();
                Utilities.Log("Stopped function app " + app1.Name);
                Utilities.Print(app1);
                Utilities.Log("Starting function app " + app1.Name);
                app1.Start();
                Utilities.Log("Started function app " + app1.Name);
                Utilities.Print(app1);
                Utilities.Log("Restarting function app " + app2.Name);
                app2.Restart();
                Utilities.Log("Restarted function app " + app2.Name);
                Utilities.Print(app2);

                //=============================================================
                // List function apps

                Utilities.Log("Printing list of function apps in resource group " + rg1Name + "...");

                foreach (IFunctionApp functionApp in azure.AppServices.FunctionApps.ListByResourceGroup(rg1Name))
                {
                    Utilities.Print(functionApp);
                }

                Utilities.Log("Printing list of function apps in resource group " + rg2Name + "...");

                foreach (IFunctionApp functionApp in azure.AppServices.FunctionApps.ListByResourceGroup(rg2Name))
                {
                    Utilities.Print(functionApp);
                }

                //=============================================================
                // Delete a function app

                Utilities.Log("Deleting function app " + app1Name + "...");
                azure.AppServices.FunctionApps.DeleteByResourceGroup(rg1Name, app1Name);
                Utilities.Log("Deleted function app " + app1Name + "...");

                Utilities.Log("Printing list of function apps in resource group " + rg1Name + " again...");
                foreach (IFunctionApp functionApp in azure.AppServices.FunctionApps.ListByResourceGroup(rg1Name))
                {
                    Utilities.Print(functionApp);
                }
            }
            finally
            {
                try
                {
                    Utilities.Log("Deleting Resource Group: " + rg2Name);
                    azure.ResourceGroups.DeleteByName(rg2Name);
                    Utilities.Log("Deleted Resource Group: " + rg2Name);
                    Utilities.Log("Deleting Resource Group: " + rg1Name);
                    azure.ResourceGroups.DeleteByName(rg1Name);
                    Utilities.Log("Deleted Resource Group: " + rg1Name);
                }
                catch (NullReferenceException)
                {
                    Utilities.Log("Did not create any resources in Azure. No clean up is necessary");
                }
                catch (Exception g)
                {
                    Utilities.Log(g);
                }
            }
        }
        /**
         * Azure App Service basic sample for managing web apps.
         *  - Create 3 linux web apps under the same new app service plan:
         *    - 1, 2 are in the same resource group, 3 in a different one
         *    - Stop and start 1, restart 2
         *    - Add Java support to app 3
         *  - List web apps
         *  - Delete a web app
         */

        public static void RunSample(IAzure azure)
        {
            string app1Name = SdkContext.RandomResourceName("webapp1-", 20);
            string app2Name = SdkContext.RandomResourceName("webapp2-", 20);
            string app3Name = SdkContext.RandomResourceName("webapp3-", 20);
            string rg1Name  = SdkContext.RandomResourceName("rg1NEMV_", 24);
            string rg2Name  = SdkContext.RandomResourceName("rg2NEMV_", 24);

            try
            {
                //============================================================
                // Create a web app with a new app service plan

                Utilities.Log("Creating web app " + app1Name + " in resource group " + rg1Name + "...");

                IWebApp app1 = azure.WebApps
                               .Define(app1Name)
                               .WithRegion(Region.USWest)
                               .WithNewResourceGroup(rg1Name)
                               .WithNewLinuxPlan(PricingTier.StandardS1)
                               .WithBuiltInImage(RuntimeStack.NodeJS_6_9)
                               .Create();

                Utilities.Log("Created web app " + app1.Name);
                Utilities.Print(app1);

                //============================================================
                // Create a second web app with the same app service plan

                Utilities.Log("Creating another web app " + app2Name + " in resource group " + rg1Name + "...");
                IAppServicePlan plan = azure.AppServices.AppServicePlans.GetById(app1.AppServicePlanId);
                IWebApp         app2 = azure.WebApps
                                       .Define(app2Name)
                                       .WithExistingLinuxPlan(plan)
                                       .WithExistingResourceGroup(rg1Name)
                                       .WithBuiltInImage(RuntimeStack.NodeJS_6_9)
                                       .Create();

                Utilities.Log("Created web app " + app2.Name);
                Utilities.Print(app2);

                //============================================================
                // Create a third web app with the same app service plan, but
                // in a different resource group

                Utilities.Log("Creating another web app " + app3Name + " in resource group " + rg2Name + "...");
                IWebApp app3 = azure.WebApps
                               .Define(app3Name)
                               .WithExistingLinuxPlan(plan)
                               .WithNewResourceGroup(rg2Name)
                               .WithBuiltInImage(RuntimeStack.NodeJS_6_9)
                               .Create();

                Utilities.Log("Created web app " + app3.Name);
                Utilities.Print(app3);

                //============================================================
                // stop and start app1, restart app 2
                Utilities.Log("Stopping web app " + app1.Name);
                app1.Stop();
                Utilities.Log("Stopped web app " + app1.Name);
                Utilities.Print(app1);
                Utilities.Log("Starting web app " + app1.Name);
                app1.Start();
                Utilities.Log("Started web app " + app1.Name);
                Utilities.Print(app1);
                Utilities.Log("Restarting web app " + app2.Name);
                app2.Restart();
                Utilities.Log("Restarted web app " + app2.Name);
                Utilities.Print(app2);

                //============================================================
                // Configure app 3 to have Java 8 enabled
                Utilities.Log("Adding Java support to web app " + app3Name + "...");
                app3.Update()
                .WithJavaVersion(JavaVersion.V8Newest)
                .WithWebContainer(WebContainer.Tomcat8_0Newest)
                .Apply();
                Utilities.Log("Java supported on web app " + app3Name + "...");

                //=============================================================
                // List web apps

                Utilities.Log("Printing list of web apps in resource group " + rg1Name + "...");

                foreach (IWebApp webApp in azure.WebApps.ListByResourceGroup(rg1Name))
                {
                    Utilities.Print(webApp);
                }

                Utilities.Log("Printing list of web apps in resource group " + rg2Name + "...");

                foreach (IWebApp webApp in azure.WebApps.ListByResourceGroup(rg2Name))
                {
                    Utilities.Print(webApp);
                }

                //=============================================================
                // Delete a web app

                Utilities.Log("Deleting web app " + app1Name + "...");
                azure.WebApps.DeleteByResourceGroup(rg1Name, app1Name);
                Utilities.Log("Deleted web app " + app1Name + "...");

                Utilities.Log("Printing list of web apps in resource group " + rg1Name + " again...");
                foreach (IWebApp webApp in azure.WebApps.ListByResourceGroup(rg1Name))
                {
                    Utilities.Print(webApp);
                }
            }
            finally
            {
                try
                {
                    Utilities.Log("Deleting Resource Group: " + rg2Name);
                    azure.ResourceGroups.DeleteByName(rg2Name);
                    Utilities.Log("Deleted Resource Group: " + rg2Name);
                    Utilities.Log("Deleting Resource Group: " + rg1Name);
                    azure.ResourceGroups.DeleteByName(rg1Name);
                    Utilities.Log("Deleted Resource Group: " + rg1Name);
                }
                catch (NullReferenceException)
                {
                    Utilities.Log("Did not create any resources in Azure. No clean up is necessary");
                }
                catch (Exception g)
                {
                    Utilities.Log(g);
                }
            }
        }
Exemplo n.º 16
0
 public Task <IWebApp> TryFetchWebAppAsync(IAzure azureMgn, IResourceGroup rg, IAppServicePlan asp) =>
 SetupAsync <IWebApp>(
     "web app",
     _configuration.WebAppName,
     existAsync: async() => (await azureMgn.WebApps.ListByResourceGroupAsync(_configuration.ResourceGroupName))
     .Any(a => a.Name == _configuration.WebAppName),
     createAsync: () => azureMgn.WebApps
     .Define(_configuration.WebAppName)
     .WithExistingWindowsPlan(asp)
     .WithExistingResourceGroup(rg)
     .WithWebAppAlwaysOn(true)
     .CreateAsync(),
     getAsync: () => azureMgn.WebApps.GetByResourceGroupAsync(_configuration.ResourceGroupName, _configuration.WebAppName));
        /**
         * Azure App Service basic sample for managing function apps.
         *  - Create 4 function apps under the same new app service plan:
         *    - Deploy to 1 using FTP
         *    - Deploy to 2 using local Git repository
         *    - Deploy to 3 using a publicly available Git repository
         *    - Deploy to 4 using a GitHub repository with continuous integration
         */

        public static void RunSample(IAzure azure)
        {
            // New resources
            string suffix   = ".azurewebsites.net";
            string app1Name = SdkContext.RandomResourceName("webapp1-", 20);
            string app2Name = SdkContext.RandomResourceName("webapp2-", 20);
            string app3Name = SdkContext.RandomResourceName("webapp3-", 20);
            string app4Name = SdkContext.RandomResourceName("webapp4-", 20);
            string app1Url  = app1Name + suffix;
            string app2Url  = app2Name + suffix;
            string app3Url  = app3Name + suffix;
            string app4Url  = app4Name + suffix;
            string rgName   = SdkContext.RandomResourceName("rg1NEMV_", 24);

            try {
                //============================================================
                // Create a function app with a new app service plan

                Utilities.Log("Creating function app " + app1Name + " in resource group " + rgName + "...");

                IFunctionApp app1 = azure.AppServices.FunctionApps.Define(app1Name)
                                    .WithRegion(Region.USWest)
                                    .WithNewResourceGroup(rgName)
                                    .Create();

                Utilities.Log("Created function app " + app1.Name);
                Utilities.Print(app1);

                //============================================================
                // Deploy to app 1 through FTP

                Utilities.Log("Deploying a function app to " + app1Name + " through FTP...");

                IPublishingProfile profile = app1.GetPublishingProfile();
                Utilities.UploadFileToFtp(profile, Path.Combine(Utilities.ProjectPath, "Asset", "square-function-app", "host.json"));
                Utilities.UploadFileToFtp(profile, Path.Combine(Utilities.ProjectPath, "Asset", "square-function-app", "square", "function.json"), "square/function.json");
                Utilities.UploadFileToFtp(profile, Path.Combine(Utilities.ProjectPath, "Asset", "square-function-app", "square", "index.js"), "square/index.js");

                Utilities.Log("Deployment square app to web app " + app1.Name + " completed");
                Utilities.Print(app1);

                // warm up
                Utilities.Log("Warming up " + app1Url + "/api/square...");
                Utilities.PostAddress("http://" + app1Url + "/api/square", "625");
                SdkContext.DelayProvider.Delay(5000);
                Utilities.Log("CURLing " + app1Url + "/api/square...");
                Utilities.Log(Utilities.PostAddress("http://" + app1Url + "/api/square", "625"));

                //============================================================
                // Create a second function app with local git source control

                Utilities.Log("Creating another function app " + app2Name + " in resource group " + rgName + "...");
                IAppServicePlan plan = azure.AppServices.AppServicePlans.GetById(app1.AppServicePlanId);
                IFunctionApp    app2 = azure.AppServices.FunctionApps.Define(app2Name)
                                       .WithExistingAppServicePlan(plan)
                                       .WithExistingResourceGroup(rgName)
                                       .WithExistingStorageAccount(app1.StorageAccount)
                                       .WithLocalGitSourceControl()
                                       .Create();

                Utilities.Log("Created function app " + app2.Name);
                Utilities.Print(app2);

                //============================================================
                // Deploy to app 2 through local Git

                Utilities.Log("Deploying a local Tomcat source to " + app2Name + " through Git...");

                profile = app2.GetPublishingProfile();
                Utilities.DeployByGit(profile, "square-function-app");

                Utilities.Log("Deployment to function app " + app2.Name + " completed");
                Utilities.Print(app2);

                // warm up
                Utilities.Log("Warming up " + app2Url + "/api/square...");
                Utilities.PostAddress("http://" + app2Url + "/api/square", "725");
                SdkContext.DelayProvider.Delay(5000);
                Utilities.Log("CURLing " + app2Url + "/api/square...");
                Utilities.Log("Square of 725 is " + Utilities.PostAddress("http://" + app2Url + "/api/square", "725"));

                //============================================================
                // Create a 3rd function app with a public GitHub repo in Azure-Samples

                Utilities.Log("Creating another function app " + app3Name + "...");
                IFunctionApp app3 = azure.AppServices.FunctionApps.Define(app3Name)
                                    .WithExistingAppServicePlan(plan)
                                    .WithNewResourceGroup(rgName)
                                    .WithExistingStorageAccount(app2.StorageAccount)
                                    .DefineSourceControl()
                                    .WithPublicGitRepository("https://github.com/jianghaolu/square-function-app-sample")
                                    .WithBranch("master")
                                    .Attach()
                                    .Create();

                Utilities.Log("Created function app " + app3.Name);
                Utilities.Print(app3);

                // warm up
                Utilities.Log("Warming up " + app3Url + "/api/square...");
                Utilities.PostAddress("http://" + app3Url + "/api/square", "825");
                SdkContext.DelayProvider.Delay(5000);
                Utilities.Log("CURLing " + app3Url + "/api/square...");
                Utilities.Log("Square of 825 is " + Utilities.PostAddress("http://" + app3Url + "/api/square", "825"));

                //============================================================
                // Create a 4th function app with a personal GitHub repo and turn on continuous integration

                Utilities.Log("Creating another function app " + app4Name + "...");
                IFunctionApp app4 = azure.AppServices.FunctionApps
                                    .Define(app4Name)
                                    .WithExistingAppServicePlan(plan)
                                    .WithExistingResourceGroup(rgName)
                                    .WithExistingStorageAccount(app3.StorageAccount)
                                    // Uncomment the following lines to turn on 4th scenario
                                    //.DefineSourceControl()
                                    //    .WithContinuouslyIntegratedGitHubRepository("username", "reponame")
                                    //    .WithBranch("master")
                                    //    .WithGitHubAccessToken("YOUR GITHUB PERSONAL TOKEN")
                                    //    .Attach()
                                    .Create();

                Utilities.Log("Created function app " + app4.Name);
                Utilities.Print(app4);

                // warm up
                Utilities.Log("Warming up " + app4Url + "...");
                Utilities.CheckAddress("http://" + app4Url);
                SdkContext.DelayProvider.Delay(5000);
                Utilities.Log("CURLing " + app4Url + "...");
                Utilities.Log(Utilities.CheckAddress("http://" + app4Url));
            }
            finally
            {
                try
                {
                    Utilities.Log("Deleting Resource Group: " + rgName);
                    azure.ResourceGroups.DeleteByName(rgName);
                    Utilities.Log("Deleted Resource Group: " + rgName);
                }
                catch (NullReferenceException)
                {
                    Utilities.Log("Did not create any resources in Azure. No clean up is necessary");
                }
                catch (Exception g)
                {
                    Utilities.Log(g);
                }
            }
        }
Exemplo n.º 18
0
 /// <summary>
 /// Uses an existing app service plan for the web app.
 /// </summary>
 /// <param name="appServicePlan">The existing app service plan.</param>
 /// <return>The next stage of the definition.</return>
 WebApp.Definition.IExistingWindowsPlanWithGroup WebApp.Definition.IBlank.WithExistingWindowsPlan(IAppServicePlan appServicePlan)
 {
     return(this.WithExistingWindowsPlan(appServicePlan) as WebApp.Definition.IExistingWindowsPlanWithGroup);
 }
        /**
         * Azure App Service basic sample for managing web apps.
         *  - Create 4 web apps under the same new app service plan:
         *    - Deploy to 1 using FTP
         *    - Deploy to 2 using local Git repository
         *    - Deploy to 3 using a publicly available Git repository
         *    - Deploy to 4 using a GitHub repository with continuous integration
         */

        public static void RunSample(IAzure azure)
        {
            string suffix   = ".azurewebsites.net";
            string app1Name = SdkContext.RandomResourceName("webapp1-", 20);
            string app2Name = SdkContext.RandomResourceName("webapp2-", 20);
            string app3Name = SdkContext.RandomResourceName("webapp3-", 20);
            string app4Name = SdkContext.RandomResourceName("webapp4-", 20);
            string app1Url  = app1Name + suffix;
            string app2Url  = app2Name + suffix;
            string app3Url  = app3Name + suffix;
            string app4Url  = app4Name + suffix;
            string rgName   = SdkContext.RandomResourceName("rg1NEMV_", 24);

            try {
                //============================================================
                // Create a web app with a new app service plan

                Utilities.Log("Creating web app " + app1Name + " in resource group " + rgName + "...");

                IWebApp app1 = azure.WebApps.Define(app1Name)
                               .WithRegion(Region.USWest)
                               .WithNewResourceGroup(rgName)
                               .WithNewLinuxPlan(PricingTier.StandardS1)
                               .WithPublicDockerHubImage("tomcat:8-jre8")
                               .WithStartUpCommand("/bin/bash -c \"sed -ie 's/appBase=\\\"webapps\\\"/appBase=\\\"\\\\/home\\\\/site\\\\/wwwroot\\\\/webapps\\\"/g' conf/server.xml && catalina.sh run\"")
                               .WithAppSetting("PORT", "8080")
                               .Create();

                Utilities.Log("Created web app " + app1.Name);
                Utilities.Print(app1);

                //============================================================
                // Deploy to app 1 through FTP

                Utilities.Log("Deploying helloworld.War to " + app1Name + " through FTP...");

                Utilities.UploadFileToWebApp(
                    app1.GetPublishingProfile(),
                    Path.Combine(Utilities.ProjectPath, "Asset", "helloworld.war"));

                Utilities.Log("Deployment helloworld.War to web app " + app1.Name + " completed");
                Utilities.Print(app1);

                // warm up
                Utilities.Log("Warming up " + app1Url + "/helloworld...");
                Utilities.CheckAddress("http://" + app1Url + "/helloworld");
                SdkContext.DelayProvider.Delay(5000);
                Utilities.Log("CURLing " + app1Url + "/helloworld...");
                Utilities.Log(Utilities.CheckAddress("http://" + app1Url + "/helloworld"));

                //============================================================
                // Create a second web app with local git source control

                Utilities.Log("Creating another web app " + app2Name + " in resource group " + rgName + "...");
                IAppServicePlan plan = azure.AppServices.AppServicePlans.GetById(app1.AppServicePlanId);
                IWebApp         app2 = azure.WebApps.Define(app2Name)
                                       .WithExistingLinuxPlan(plan)
                                       .WithExistingResourceGroup(rgName)
                                       .WithPublicDockerHubImage("tomcat:8-jre8")
                                       .WithStartUpCommand("/bin/bash -c \"sed -ie 's/appBase=\\\"webapps\\\"/appBase=\\\"\\\\/home\\\\/site\\\\/wwwroot\\\\/webapps\\\"/g' conf/server.xml && catalina.sh run\"")
                                       .WithAppSetting("PORT", "8080")
                                       .WithLocalGitSourceControl()
                                       .Create();

                Utilities.Log("Created web app " + app2.Name);
                Utilities.Print(app2);

                //============================================================
                // Deploy to app 2 through local Git

                Utilities.Log("Deploying a local Tomcat source to " + app2Name + " through Git...");

                var profile = app2.GetPublishingProfile();
                Utilities.DeployByGit(profile, "azure-samples-appservice-helloworld");

                Utilities.Log("Deployment to web app " + app2.Name + " completed");
                Utilities.Print(app2);

                // warm up
                Utilities.Log("Warming up " + app2Url + "/helloworld...");
                Utilities.CheckAddress("http://" + app2Url + "/helloworld");
                SdkContext.DelayProvider.Delay(5000);
                Utilities.Log("CURLing " + app2Url + "/helloworld...");
                Utilities.Log(Utilities.CheckAddress("http://" + app2Url + "/helloworld"));

                //============================================================
                // Create a 3rd web app with a public GitHub repo in Azure-Samples

                Utilities.Log("Creating another web app " + app3Name + "...");
                IWebApp app3 = azure.WebApps.Define(app3Name)
                               .WithExistingLinuxPlan(plan)
                               .WithNewResourceGroup(rgName)
                               .WithPublicDockerHubImage("tomcat:8-jre8")
                               .WithStartUpCommand("/bin/bash -c \"sed -ie 's/appBase=\\\"webapps\\\"/appBase=\\\"\\\\/home\\\\/site\\\\/wwwroot\\\\/webapps\\\"/g' conf/server.xml && catalina.sh run\"")
                               .WithAppSetting("PORT", "8080")
                               .DefineSourceControl()
                               .WithPublicGitRepository("https://github.com/azure-appservice-samples/java-get-started")
                               .WithBranch("master")
                               .Attach()
                               .Create();

                Utilities.Log("Created web app " + app3.Name);
                Utilities.Print(app3);

                // warm up
                Utilities.Log("Warming up " + app3Url + "...");
                Utilities.CheckAddress("http://" + app3Url);
                SdkContext.DelayProvider.Delay(5000);
                Utilities.Log("CURLing " + app3Url + "...");
                Utilities.Log(Utilities.CheckAddress("http://" + app3Url));

                //============================================================
                // Create a 4th web app with a personal GitHub repo and turn on continuous integration

                Utilities.Log("Creating another web app " + app4Name + "...");
                IWebApp app4 = azure.WebApps
                               .Define(app4Name)
                               .WithExistingLinuxPlan(plan)
                               .WithExistingResourceGroup(rgName)
                               .WithPublicDockerHubImage("tomcat:8-jre8")
                               .WithStartUpCommand("/bin/bash -c \"sed -ie 's/appBase=\\\"webapps\\\"/appBase=\\\"\\\\/home\\\\/site\\\\/wwwroot\\\\/webapps\\\"/g' conf/server.xml && catalina.sh run\"")
                               .WithAppSetting("PORT", "8080")
                               // Uncomment the following lines to turn on 4th scenario
                               //.DefineSourceControl()
                               //    .WithContinuouslyIntegratedGitHubRepository("username", "reponame")
                               //    .WithBranch("master")
                               //    .WithGitHubAccessToken("YOUR GITHUB PERSONAL TOKEN")
                               //    .Attach()
                               .Create();

                Utilities.Log("Created web app " + app4.Name);
                Utilities.Print(app4);

                // warm up
                Utilities.Log("Warming up " + app4Url + "...");
                Utilities.CheckAddress("http://" + app4Url);
                SdkContext.DelayProvider.Delay(5000);
                Utilities.Log("CURLing " + app4Url + "...");
                Utilities.Log(Utilities.CheckAddress("http://" + app4Url));
            }
            finally
            {
                try
                {
                    Utilities.Log("Deleting Resource Group: " + rgName);
                    azure.ResourceGroups.BeginDeleteByName(rgName);
                    Utilities.Log("Deleted Resource Group: " + rgName);
                }
                catch (NullReferenceException)
                {
                    Utilities.Log("Did not create any resources in Azure. No clean up is necessary");
                }
                catch (Exception g)
                {
                    Utilities.Log(g);
                }
            }
        }
        /**
         * Azure App Service basic sample for managing function apps.
         *  - Create 3 function apps under the same new app service plan and with the same storage account
         *    - Deploy 1 & 2 via Git a function that calculates the square of a number
         *    - Deploy 3 via Web Deploy
         *    - Enable app level authentication for the 1st function app
         *    - Verify the 1st function app can be accessed with the admin key
         *    - Enable function level authentication for the 2nd function app
         *    - Verify the 2nd function app can be accessed with the function key
         *    - Enable function level authentication for the 3rd function app
         *    - Verify the 3rd function app can be accessed with the function key
         */


        public static void RunSample(IAzure azure)
        {
            // New resources
            string suffix   = ".azurewebsites.net";
            string app1Name = SdkContext.RandomResourceName("webapp1-", 20);
            string app2Name = SdkContext.RandomResourceName("webapp2-", 20);
            string app3Name = SdkContext.RandomResourceName("webapp3-", 20);
            string app1Url  = app1Name + suffix;
            string app2Url  = app2Name + suffix;
            string app3Url  = app3Name + suffix;
            string rgName   = SdkContext.RandomResourceName("rg1NEMV_", 24);

            try {
                //============================================================
                // Create a function app with admin level auth

                Utilities.Log("Creating function app " + app1Name + " in resource group " + rgName + " with admin level auth...");

                IFunctionApp app1 = azure.AppServices.FunctionApps.Define(app1Name)
                                    .WithRegion(Region.USWest)
                                    .WithNewResourceGroup(rgName)
                                    .WithLocalGitSourceControl()
                                    .Create();

                Utilities.Log("Created function app " + app1.Name);
                Utilities.Print(app1);

                //============================================================
                // Create a second function app with function level auth

                Utilities.Log("Creating another function app " + app2Name + " in resource group " + rgName + " with function level auth...");
                IAppServicePlan plan = azure.AppServices.AppServicePlans.GetById(app1.AppServicePlanId);
                IFunctionApp    app2 = azure.AppServices.FunctionApps.Define(app2Name)
                                       .WithExistingAppServicePlan(plan)
                                       .WithExistingResourceGroup(rgName)
                                       .WithExistingStorageAccount(app1.StorageAccount)
                                       .WithLocalGitSourceControl()
                                       .Create();

                Utilities.Log("Created function app " + app2.Name);
                Utilities.Print(app2);

                //============================================================
                // Create a third function app with function level auth

                Utilities.Log("Creating another function app " + app3Name + " in resource group " + rgName + " with function level auth...");
                IFunctionApp app3 = azure.AppServices.FunctionApps.Define(app3Name)
                                    .WithExistingAppServicePlan(plan)
                                    .WithExistingResourceGroup(rgName)
                                    .WithExistingStorageAccount(app1.StorageAccount)
                                    .WithLocalGitSourceControl()
                                    .Create();

                Utilities.Log("Created function app " + app3.Name);
                Utilities.Print(app3);

                //============================================================
                // Deploy to app 1 through Git

                Utilities.Log("Deploying a local function app to " + app1Name + " through Git...");

                IPublishingProfile profile = app1.GetPublishingProfile();
                Utilities.DeployByGit(profile, "square-function-app-admin-auth");

                // warm up
                Utilities.Log("Warming up " + app1Url + "/api/square...");
                Utilities.PostAddress("http://" + app1Url + "/api/square", "625");
                SdkContext.DelayProvider.Delay(5000);
                Utilities.Log("CURLing " + app1Url + "/api/square...");
                Utilities.Log("Square of 625 is " + Utilities.PostAddress("http://" + app1Url + "/api/square?code=" + app1.GetMasterKey(), "625"));

                //============================================================
                // Deploy to app 2 through Git

                Utilities.Log("Deploying a local function app to " + app2Name + " through Git...");

                profile = app2.GetPublishingProfile();
                Utilities.DeployByGit(profile, "square-function-app-function-auth");

                Utilities.Log("Deployment to function app " + app2.Name + " completed");
                Utilities.Print(app2);


                string functionKey = app2.ListFunctionKeys("square").Values.First();

                // warm up
                Utilities.Log("Warming up " + app2Url + "/api/square...");
                Utilities.PostAddress("http://" + app2Url + "/api/square", "725");
                SdkContext.DelayProvider.Delay(5000);
                Utilities.Log("CURLing " + app2Url + "/api/square...");
                Utilities.Log("Square of 725 is " + Utilities.PostAddress("http://" + app2Url + "/api/square?code=" + functionKey, "725"));

                Utilities.Log("Adding a new key to function app " + app2.Name + "...");

                var newKey = app2.AddFunctionKey("square", "newkey", null);

                Utilities.Log("CURLing " + app2Url + "/api/square...");
                Utilities.Log("Square of 825 is " + Utilities.PostAddress("http://" + app2Url + "/api/square?code=" + newKey.Value, "825"));

                //============================================================
                // Deploy to app 3 through web deploy

                Utilities.Log("Deploying a local function app to " + app3Name + " throuh web deploy...");

                app3.Deploy()
                .WithPackageUri("https://github.com/Azure/azure-libraries-for-net/raw/master/Samples/Asset/square-function-app-function-auth.zip")
                .WithExistingDeploymentsDeleted(false)
                .Execute();

                Utilities.Log("Deployment to function app " + app3.Name + " completed");

                Utilities.Log("Adding a new key to function app " + app3.Name + "...");
                app3.AddFunctionKey("square", "newkey", "mysecretkey");

                // warm up
                Utilities.Log("Warming up " + app3Url + "/api/square...");
                Utilities.PostAddress("http://" + app3Url + "/api/square", "925");
                SdkContext.DelayProvider.Delay(5000);
                Utilities.Log("CURLing " + app3Url + "/api/square...");
                Utilities.Log("Square of 925 is " + Utilities.PostAddress("http://" + app3Url + "/api/square?code=mysecretkey", "925"));
            }
            finally
            {
                try
                {
                    Utilities.Log("Deleting Resource Group: " + rgName);
                    azure.ResourceGroups.DeleteByName(rgName);
                    Utilities.Log("Deleted Resource Group: " + rgName);
                }
                catch (NullReferenceException)
                {
                    Utilities.Log("Did not create any resources in Azure. No clean up is necessary");
                }
                catch (Exception g)
                {
                    Utilities.Log(g);
                }
            }
        }
Exemplo n.º 21
0
        private IWebApp CreateWebsite(string subscriptionId, string appName, string resourceGroupName, IAppServicePlan plan, bool allowAutomaticRename)
        {
            int attempt = 1;

            while (attempt <= 5)
            {
                try
                {
                    _logger.LogInformation($"Creating new website \"{appName}\". Attempt {attempt}");
                    return(ExecuteWithRetry(() => _authenticatedAzure.WithSubscription(subscriptionId).WebApps.Define(appName).WithExistingWindowsPlan(plan).WithExistingResourceGroup(resourceGroupName).Create()));
                }
                catch (DefaultErrorResponseException ex)
                {
                    if (ex.Message.Equals("Operation returned an invalid status code 'Conflict'", StringComparison.InvariantCultureIgnoreCase))
                    {
                        if (allowAutomaticRename)
                        {
                            _logger.LogWarning($"The application name \"{appName}\" is not available. Trying other name...");
                            appName = GetAlternativeAppName(appName);
                            attempt++;
                        }
                        else
                        {
                            return(null);
                        }
                    }
                    else
                    {
                        throw;
                    }
                }
            }

            if (attempt > 5)
            {
                throw new Exception("Failed getting available name after 5 attempts");
            }

            return(null);
        }
        public static void RunSample(IAzure azure)
        {
            string suffix   = ".azurewebsites.net";
            string app1Name = SdkContext.RandomResourceName("webapp1-", 20);
            string app2Name = SdkContext.RandomResourceName("webapp2-", 20);
            string app3Name = SdkContext.RandomResourceName("webapp3-", 20);
            string app4Name = SdkContext.RandomResourceName("webapp4-", 20);
            string app1Url  = app1Name + suffix;
            string app2Url  = app2Name + suffix;
            string app3Url  = app3Name + suffix;
            string app4Url  = app4Name + suffix;
            string rgName   = SdkContext.RandomResourceName("rg1NEMV_", 24);

            try
            {
                //============================================================
                // Create a web app with a new app service plan

                Utilities.Log("Creating web app " + app1Name + " in resource group " + rgName + "...");

                IWebApp app1 = azure.WebApps.Define(app1Name)
                               .WithRegion(Region.USWest)
                               .WithNewResourceGroup(rgName)
                               .WithNewWindowsPlan(PricingTier.StandardS1)
                               .WithJavaVersion(JavaVersion.V8Newest)
                               .WithWebContainer(WebContainer.Tomcat8_0Newest)
                               .Create();

                Utilities.Log("Created web app " + app1.Name);
                Utilities.Print(app1);

                //============================================================
                // Set up active directory authentication

                Utilities.Log("Please create an AD application with redirect URL " + app1Url);
                Utilities.Log("Application ID is:");
                string applicationId = Utilities.ReadLine();
                Utilities.Log("Tenant ID is:");
                string tenantId = Utilities.ReadLine();

                Utilities.Log("Updating web app " + app1Name + " to use active directory login...");

                app1.Update()
                .DefineAuthentication()
                .WithDefaultAuthenticationProvider(BuiltInAuthenticationProvider.AzureActiveDirectory)
                .WithActiveDirectory(applicationId, "https://sts.windows.net/" + tenantId)
                .Attach()
                .Apply();

                Utilities.Log("Added active directory login to " + app1.Name);
                Utilities.Print(app1);

                //============================================================
                // Create a second web app

                Utilities.Log("Creating another web app " + app2Name + " in resource group " + rgName + "...");
                IAppServicePlan plan = azure.AppServices.AppServicePlans.GetById(app1.AppServicePlanId);
                IWebApp         app2 = azure.WebApps.Define(app2Name)
                                       .WithExistingWindowsPlan(plan)
                                       .WithExistingResourceGroup(rgName)
                                       .WithJavaVersion(JavaVersion.V8Newest)
                                       .WithWebContainer(WebContainer.Tomcat8_0Newest)
                                       .Create();

                Utilities.Log("Created web app " + app2.Name);
                Utilities.Print(app2);

                //============================================================
                // Set up Facebook authentication

                Utilities.Log("Please create a Facebook developer application with whitelisted URL " + app2Url);
                Utilities.Log("App ID is:");
                string fbAppId = Utilities.ReadLine();
                Utilities.Log("App secret is:");
                string fbAppSecret = Utilities.ReadLine();

                Utilities.Log("Updating web app " + app2Name + " to use Facebook login...");

                app2.Update()
                .DefineAuthentication()
                .WithDefaultAuthenticationProvider(BuiltInAuthenticationProvider.Facebook)
                .WithFacebook(fbAppId, fbAppSecret)
                .Attach()
                .Apply();

                Utilities.Log("Added Facebook login to " + app2.Name);
                Utilities.Print(app2);

                //============================================================
                // Create a 3rd web app with a public GitHub repo in Azure-Samples

                Utilities.Log("Creating another web app " + app3Name + "...");
                IWebApp app3 = azure.WebApps.Define(app3Name)
                               .WithExistingWindowsPlan(plan)
                               .WithNewResourceGroup(rgName)
                               .DefineSourceControl()
                               .WithPublicGitRepository("https://github.com/Azure-Samples/app-service-web-dotnet-get-started")
                               .WithBranch("master")
                               .Attach()
                               .Create();

                Utilities.Log("Created web app " + app3.Name);
                Utilities.Print(app3);

                //============================================================
                // Set up Google authentication

                Utilities.Log("Please create a Google developer application with redirect URL " + app3Url);
                Utilities.Log("Client ID is:");
                string gClientId = Utilities.ReadLine();
                Utilities.Log("Client secret is:");
                string gClientSecret = Utilities.ReadLine();

                Utilities.Log("Updating web app " + app3Name + " to use Google login...");

                app3.Update()
                .DefineAuthentication()
                .WithDefaultAuthenticationProvider(BuiltInAuthenticationProvider.Google)
                .WithGoogle(gClientId, gClientSecret)
                .Attach()
                .Apply();

                Utilities.Log("Added Google login to " + app3.Name);
                Utilities.Print(app3);

                //============================================================
                // Create a 4th web app

                Utilities.Log("Creating another web app " + app4Name + "...");
                IWebApp app4 = azure.WebApps
                               .Define(app4Name)
                               .WithExistingWindowsPlan(plan)
                               .WithExistingResourceGroup(rgName)
                               .Create();

                Utilities.Log("Created web app " + app4.Name);
                Utilities.Print(app4);

                //============================================================
                // Set up Google authentication

                Utilities.Log("Please create a Microsoft developer application with redirect URL " + app4Url);
                Utilities.Log("Client ID is:");
                string clientId = Utilities.ReadLine();
                Utilities.Log("Client secret is:");
                string clientSecret = Utilities.ReadLine();

                Utilities.Log("Updating web app " + app3Name + " to use Microsoft login...");

                app4.Update()
                .DefineAuthentication()
                .WithDefaultAuthenticationProvider(BuiltInAuthenticationProvider.MicrosoftAccount)
                .WithMicrosoft(clientId, clientSecret)
                .Attach()
                .Apply();

                Utilities.Log("Added Microsoft login to " + app4.Name);
                Utilities.Print(app4);
            }
            finally
            {
                try
                {
                    Utilities.Log("Deleting Resource Group: " + rgName);
                    azure.ResourceGroups.DeleteByName(rgName);
                    Utilities.Log("Deleted Resource Group: " + rgName);
                }
                catch (NullReferenceException)
                {
                    Utilities.Log("Did not create any resources in Azure. No clean up is necessary");
                }
                catch (Exception g)
                {
                    Utilities.Log(g);
                }
            }
        }
Exemplo n.º 23
0
 /// <summary>
 /// Uses an existing app service plan for the web app.
 /// </summary>
 /// <param name="appServicePlan">The existing app service plan.</param>
 /// <return>The next stage of the definition.</return>
 WebApp.Definition.IExistingLinuxPlanWithGroup WebApp.Definition.IBlank.WithExistingLinuxPlan(IAppServicePlan appServicePlan)
 {
     return(this.WithExistingLinuxPlan(appServicePlan));
 }
        /**
         * Azure App Service sample for managing web apps.
         *  - app service plan, web app
         *    - Create 2 web apps under the same new app service plan
         *  - domain
         *    - Create a domain
         *  - certificate
         *    - Upload a self-signed wildcard certificate
         *    - update both web apps to use the domain and the created wildcard SSL certificate
         */
        public static void RunSample(IAzure azure)
        {
            string app1Name   = SdkContext.RandomResourceName("webapp1-", 20);
            string app2Name   = SdkContext.RandomResourceName("webapp2-", 20);
            string rgName     = SdkContext.RandomResourceName("rgNEMV_", 24);
            string domainName = SdkContext.RandomResourceName("jsdkdemo-", 20) + ".com";

            try {
                //============================================================
                // Create a web app with a new app service plan

                Utilities.Log("Creating web app " + app1Name + "...");

                IWebApp app1 = azure.WebApps.Define(app1Name)
                               .WithRegion(Region.USWest)
                               .WithNewResourceGroup(rgName)
                               .WithNewLinuxPlan(PricingTier.StandardS1)
                               .WithBuiltInImage(RuntimeStack.NodeJS_6_9)
                               .Create();

                Utilities.Log("Created web app " + app1.Name);
                Utilities.Print(app1);

                //============================================================
                // Create a second web app with the same app service plan

                Utilities.Log("Creating another web app " + app2Name + "...");
                IAppServicePlan plan = azure.AppServices.AppServicePlans.GetById(app1.AppServicePlanId);
                IWebApp         app2 = azure.WebApps.Define(app2Name)
                                       .WithExistingLinuxPlan(plan)
                                       .WithExistingResourceGroup(rgName)
                                       .WithBuiltInImage(RuntimeStack.NodeJS_6_9)
                                       .Create();

                Utilities.Log("Created web app " + app2.Name);
                Utilities.Print(app2);

                //============================================================
                // Purchase a domain (will be canceled for a full refund)

                Utilities.Log("Purchasing a domain " + domainName + "...");

                IAppServiceDomain domain = azure.AppServices.AppServiceDomains.Define(domainName)
                                           .WithExistingResourceGroup(rgName)
                                           .DefineRegistrantContact()
                                           .WithFirstName("Jon")
                                           .WithLastName("Doe")
                                           .WithEmail("*****@*****.**")
                                           .WithAddressLine1("123 4th Ave")
                                           .WithCity("Redmond")
                                           .WithStateOrProvince("WA")
                                           .WithCountry(CountryISOCode.UnitedStates)
                                           .WithPostalCode("98052")
                                           .WithPhoneCountryCode(CountryPhoneCode.UnitedStates)
                                           .WithPhoneNumber("4258828080")
                                           .Attach()
                                           .WithDomainPrivacyEnabled(true)
                                           .WithAutoRenewEnabled(false)
                                           .Create();
                Utilities.Log("Purchased domain " + domain.Name);
                Utilities.Print(domain);

                //============================================================
                // Bind domain to web app 1

                Utilities.Log("Binding http://" + app1Name + "." + domainName + " to web app " + app1Name + "...");

                app1 = app1.Update()
                       .DefineHostnameBinding()
                       .WithAzureManagedDomain(domain)
                       .WithSubDomain(app1Name)
                       .WithDnsRecordType(CustomHostNameDnsRecordType.CName)
                       .Attach()
                       .Apply();

                Utilities.Log("Finished binding http://" + app1Name + "." + domainName + " to web app " + app1Name);
                Utilities.Print(app1);

                //============================================================
                // Create a self-singed SSL certificate

                var pfxPath = "webapp_" + nameof(ManageLinuxWebAppWithDomainSsl).ToLower() + ".pfx";

                Utilities.Log("Creating a self-signed certificate " + pfxPath + "...");

                Utilities.CreateCertificate(domainName, pfxPath, CertificatePassword);

                Utilities.Log("Created self-signed certificate " + pfxPath);

                //============================================================
                // Bind domain to web app 2 and turn on wild card SSL for both

                Utilities.Log("Binding https://" + app1Name + "." + domainName + " to web app " + app1Name + "...");

                app1 = app1.Update()
                       .WithManagedHostnameBindings(domain, app1Name)
                       .DefineSslBinding()
                       .ForHostname(app1Name + "." + domainName)
                       .WithPfxCertificateToUpload(Path.Combine(Utilities.ProjectPath, "Asset", pfxPath), CertificatePassword)
                       .WithSniBasedSsl()
                       .Attach()
                       .Apply();

                Utilities.Log("Finished binding http://" + app1Name + "." + domainName + " to web app " + app1Name);
                Utilities.Print(app1);

                Utilities.Log("Binding https://" + app2Name + "." + domainName + " to web app " + app2Name + "...");

                app2 = app2.Update()
                       .WithManagedHostnameBindings(domain, app2Name)
                       .DefineSslBinding()
                       .ForHostname(app2Name + "." + domainName)
                       .WithPfxCertificateToUpload(Path.Combine(Utilities.ProjectPath, "Asset", pfxPath), CertificatePassword)
                       .WithSniBasedSsl()
                       .Attach()
                       .Apply();

                Utilities.Log("Finished binding http://" + app2Name + "." + domainName + " to web app " + app2Name);
                Utilities.Print(app2);
            }
            finally
            {
                try
                {
                    Utilities.Log("Deleting Resource Group: " + rgName);
                    azure.ResourceGroups.BeginDeleteByName(rgName);
                    Utilities.Log("Deleted Resource Group: " + rgName);
                }
                catch (NullReferenceException)
                {
                    Utilities.Log("Did not create any resources in Azure. No clean up is necessary");
                }
                catch (Exception g)
                {
                    Utilities.Log(g);
                }
            }
        }
Exemplo n.º 25
0
        /**
         * Azure App Service basic sample for managing function apps.
         *  - Create 4 function apps under the same new app service plan:
         *    - Deploy to 1 using FTP
         *    - Deploy to 2 using local Git repository
         *    - Deploy to 3 using a publicly available Git repository
         *    - Deploy to 4 using a GitHub repository with continuous integration
         */


        public static void RunSample(IAzure azure)
        {
            // New resources
            string suffix   = ".azurewebsites.net";
            string app1Name = SdkContext.RandomResourceName("webapp1-", 20);
            string app2Name = SdkContext.RandomResourceName("webapp2-", 20);
            string app1Url  = app1Name + suffix;
            string app2Url  = app2Name + suffix;
            string rgName   = SdkContext.RandomResourceName("rg1NEMV_", 24);

            try {
                //============================================================
                // Create a function app with admin level auth

                Utilities.Log("Creating function app " + app1Name + " in resource group " + rgName + " with admin level auth...");

                IFunctionApp app1 = azure.AppServices.FunctionApps.Define(app1Name)
                                    .WithRegion(Region.USWest)
                                    .WithNewResourceGroup(rgName)
                                    .WithLocalGitSourceControl()
                                    .Create();

                Utilities.Log("Created function app " + app1.Name);
                Utilities.Print(app1);

                //============================================================
                // Create a second function app with function level auth

                Utilities.Log("Creating another function app " + app2Name + " in resource group " + rgName + " with function level auth...");
                IAppServicePlan plan = azure.AppServices.AppServicePlans.GetById(app1.AppServicePlanId);
                IFunctionApp    app2 = azure.AppServices.FunctionApps.Define(app2Name)
                                       .WithExistingAppServicePlan(plan)
                                       .WithExistingResourceGroup(rgName)
                                       .WithExistingStorageAccount(app1.StorageAccount)
                                       .WithLocalGitSourceControl()
                                       .Create();

                Utilities.Log("Created function app " + app2.Name);
                Utilities.Print(app2);

                //============================================================
                // Deploy to app 1 through Git

                Utilities.Log("Deploying a local function app to " + app1Name + " through Git...");

                IPublishingProfile profile = app1.GetPublishingProfile();
                Utilities.DeployByGit(profile, "square-function-app-admin-auth");

                // warm up
                Utilities.Log("Warming up " + app1Url + "/api/square...");
                Utilities.PostAddress("http://" + app1Url + "/api/square", "625");
                SdkContext.DelayProvider.Delay(5000);
                Utilities.Log("CURLing " + app1Url + "/api/square...");
                Utilities.Log("Square of 625 is " + Utilities.PostAddress("http://" + app1Url + "/api/square?code=" + app1.GetMasterKey(), "625"));

                //============================================================
                // Deploy to app 2 through Git

                Utilities.Log("Deploying a local function app to " + app2Name + " through Git...");

                profile = app2.GetPublishingProfile();
                Utilities.DeployByGit(profile, "square-function-app-function-auth");

                Utilities.Log("Deployment to function app " + app2.Name + " completed");
                Utilities.Print(app2);


                string masterKey       = app2.GetMasterKey();
                var    functionsHeader = new Dictionary <string, string>();
                functionsHeader["x-functions-key"] = masterKey;
                string response    = Utilities.CheckAddress("http://" + app2Url + "/admin/functions/square/keys", functionsHeader);
                Regex  pattern     = new Regex(@"""name"":""default"",""value"":""([\w=/]+)""");
                Match  matcher     = pattern.Match(response);
                string functionKey = matcher.Captures[0].Value;

                // warm up
                Utilities.Log("Warming up " + app2Url + "/api/square...");
                Utilities.PostAddress("http://" + app2Url + "/api/square", "725");
                SdkContext.DelayProvider.Delay(5000);
                Utilities.Log("CURLing " + app2Url + "/api/square...");
                Utilities.Log("Square of 725 is " + Utilities.PostAddress("http://" + app2Url + "/api/square?code=" + functionKey, "725"));
            }
            finally
            {
                try
                {
                    Utilities.Log("Deleting Resource Group: " + rgName);
                    azure.ResourceGroups.DeleteByName(rgName);
                    Utilities.Log("Deleted Resource Group: " + rgName);
                }
                catch (NullReferenceException)
                {
                    Utilities.Log("Did not create any resources in Azure. No clean up is necessary");
                }
                catch (Exception g)
                {
                    Utilities.Log(g);
                }
            }
        }
Exemplo n.º 26
0
 /// <summary>
 /// Uses an existing app service plan for the web app.
 /// </summary>
 /// <param name="appServicePlan">The existing app service plan.</param>
 /// <return>The next stage of the web app update.</return>
 Microsoft.Azure.Management.AppService.Fluent.WebApp.Update.IUpdate WebApp.Update.IWithAppServicePlan.WithExistingAppServicePlan(IAppServicePlan appServicePlan)
 {
     return(this.WithExistingAppServicePlan(appServicePlan));
 }
 public override FunctionAppImpl WithExistingAppServicePlan(IAppServicePlan appServicePlan)
 {
     base.WithExistingAppServicePlan(appServicePlan);
     return(AutoSetAlwaysOn(appServicePlan.PricingTier));
 }
        public IWebApp CreateWebAppProcess(ICloudAppConfig appconfig, IResourceGroup resgrp, IAppServicePlan plan)
        {
            Logger.Info("WebApp Creating");
            var webapp = Program.Cloud.WebApps.Define(appconfig.FullName)
                         .WithExistingWindowsPlan(plan)
                         .WithExistingResourceGroup(resgrp.Name.ToLower())
                         .WithClientAffinityEnabled(false)
                         .WithoutPhp()
                         .WithPhpVersion(PhpVersion.Off)
                         .WithPythonVersion(PythonVersion.Off)
                         .WithPlatformArchitecture(PlatformArchitecture.X64)
                         .WithWebSocketsEnabled(false)
                         .WithWebAppAlwaysOn(false)
                         .Create();

            Logger.Info("WebApp Created");

            CreateDeploymentSlot(webapp, appconfig.DeploymentSlotName);

            Logger.Info($"OutBound IP Range: {string.Join(",", webapp.OutboundIPAddresses)}");

            return(webapp);
        }