/**
         * Azure App Service basic sample for managing web apps.
         *  - Create a Cosmos DB with credentials stored in a Key Vault
         *  - Create a web app which interacts with the Cosmos DB by first
         *      reading the secrets from the Key Vault.
         *
         *      The source code of the web app is located at Asset/documentdb-dotnet-todo-app
         */

        public static void RunSample(IAzure azure)
        {
            Region region     = Region.USWest;
            string appName    = SdkContext.RandomResourceName("webapp-", 20);
            string rgName     = SdkContext.RandomResourceName("rg1NEMV_", 24);
            string vaultName  = SdkContext.RandomResourceName("vault", 20);
            string cosmosName = SdkContext.RandomResourceName("cosmosdb", 20);
            string appUrl     = appName + ".azurewebsites.net";

            try
            {
                //============================================================
                // Create a CosmosDB

                Utilities.Log("Creating a CosmosDB...");
                ICosmosDBAccount cosmosDBAccount = azure.CosmosDBAccounts.Define(cosmosName)
                                                   .WithRegion(region)
                                                   .WithNewResourceGroup(rgName)
                                                   .WithKind(DatabaseAccountKind.GlobalDocumentDB)
                                                   .WithEventualConsistency()
                                                   .WithWriteReplication(Region.USEast)
                                                   .WithReadReplication(Region.USCentral)
                                                   .Create();

                Utilities.Log("Created CosmosDB");
                Utilities.Log(cosmosDBAccount);

                //============================================================
                // Create a key vault

                var servicePrincipalInfo = ParseAuthFile(Environment.GetEnvironmentVariable("AZURE_AUTH_LOCATION"));

                IVault vault = azure.Vaults
                               .Define(vaultName)
                               .WithRegion(region)
                               .WithNewResourceGroup(rgName)
                               .DefineAccessPolicy()
                               .ForServicePrincipal(servicePrincipalInfo.ClientId)
                               .AllowSecretAllPermissions()
                               .Attach()
                               .Create();

                SdkContext.DelayProvider.Delay(10000);

                //============================================================
                // Store Cosmos DB credentials in Key Vault

                IKeyVaultClient keyVaultClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(async(authority, resource, scope) =>
                {
                    var context = new AuthenticationContext(authority, TokenCache.DefaultShared);
                    var result  = await context.AcquireTokenAsync(resource, new ClientCredential(servicePrincipalInfo.ClientId, servicePrincipalInfo.ClientSecret));
                    return(result.AccessToken);
                }), ((KeyVaultManagementClient)azure.Vaults.Manager.Inner).HttpClient);
                keyVaultClient.SetSecretAsync(vault.VaultUri, "azure-documentdb-uri", cosmosDBAccount.DocumentEndpoint).GetAwaiter().GetResult();
                keyVaultClient.SetSecretAsync(vault.VaultUri, "azure-documentdb-key", cosmosDBAccount.ListKeys().PrimaryMasterKey).GetAwaiter().GetResult();
                keyVaultClient.SetSecretAsync(vault.VaultUri, "azure-documentdb-database", "tododb").GetAwaiter().GetResult();

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

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

                IWebApp app = azure.WebApps
                              .Define(appName)
                              .WithRegion(region)
                              .WithExistingResourceGroup(rgName)
                              .WithNewWindowsPlan(PricingTier.StandardS1)
                              .WithNetFrameworkVersion(NetFrameworkVersion.V4_6)
                              .WithAppSetting("AZURE_KEYVAULT_URI", vault.VaultUri)
                              .WithSystemAssignedManagedServiceIdentity()
                              .Create();

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

                //============================================================
                // Update vault to allow the web app to access

                vault.Update()
                .DefineAccessPolicy()
                .ForObjectId(app.SystemAssignedManagedServiceIdentityPrincipalId)
                .AllowSecretAllPermissions()
                .Attach()
                .Apply();

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

                Utilities.Log("Deploying a local asp.net application to " + appName + " through Git...");

                var profile = app.GetPublishingProfile();
                Utilities.DeployByGit(profile, "documentdb-dotnet-todo-app");

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

                // warm up
                Utilities.Log("Warming up " + appUrl + "...");
                Utilities.CheckAddress("http://" + appUrl);
                SdkContext.DelayProvider.Delay(5000);
                Utilities.Log("CURLing " + appUrl + "...");
                Utilities.Log(Utilities.CheckAddress("http://" + appUrl));
            }
            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);
                }
            }
        }
        /**
         * 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 web apps.
         *  - Create a storage account and upload a couple blobs
         *  - Create a web app that contains the connection string to the storage account
         *  - Deploy a Tomcat application that reads from the storage account
         *  - Clean up
         */
        public static void RunSample(IAzure azure)
        {
            string app1Name      = SdkContext.RandomResourceName("webapp1-", 20);
            string app1Url       = app1Name + SUFFIX;
            string storageName   = SdkContext.RandomResourceName("jsdkstore", 20);
            string containerName = SdkContext.RandomResourceName("jcontainer", 20);
            string rgName        = SdkContext.RandomResourceName("rg1NEMV_", 24);

            try {
                //============================================================
                // Create a storage account for the web app to use

                Utilities.Log("Creating storage account " + storageName + "...");

                IStorageAccount storageAccount = azure.StorageAccounts.Define(storageName)
                                                 .WithRegion(Region.USWest)
                                                 .WithNewResourceGroup(rgName)
                                                 .Create();

                string accountKey = storageAccount.GetKeys()[0].Value;

                string connectionString = string.Format("DefaultEndpointsProtocol=https;AccountName={0};AccountKey={1}",
                                                        storageAccount.Name, accountKey);

                Utilities.Log("Created storage account " + storageAccount.Name);

                //============================================================
                // Upload a few files to the storage account blobs

                Utilities.Log("Uploading 2 blobs to container " + containerName + "...");

                Utilities.UploadFilesToContainer(
                    connectionString,
                    containerName,
                    new[]
                {
                    Path.Combine(Utilities.ProjectPath, "Asset", "helloworld.war"),
                    Path.Combine(Utilities.ProjectPath, "Asset", "install_apache.Sh")
                });

                Utilities.Log("Uploaded 2 blobs to container " + containerName);

                //============================================================
                // 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)
                               .WithExistingResourceGroup(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\"")
                               .WithConnectionString("storage.connectionString", connectionString, ConnectionStringType.Custom)
                               .WithAppSetting("storage.containerName", containerName)
                               .WithAppSetting("PORT", "8080")
                               .Create();

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

                //============================================================
                // Deploy a web app that connects to the storage account
                // Source code: https://github.com/jianghaolu/azure-samples-blob-explorer

                Utilities.Log("Deploying azure-samples-blob-traverser.war to " + app1Name + " through FTP...");

                Utilities.UploadFileToWebApp(
                    app1.GetPublishingProfile(),
                    Path.Combine(Utilities.ProjectPath, "Asset", "azure-samples-blob-traverser.war"));

                Utilities.Log("Deployment azure-samples-blob-traverser.war to web app " + app1.Name + " completed");
                Utilities.Print(app1);

                // warm up
                Utilities.Log("Warming up " + app1Url + "/azure-samples-blob-traverser...");
                Utilities.CheckAddress("http://" + app1Url + "/azure-samples-blob-traverser");
                SdkContext.DelayProvider.Delay(5000);
                Utilities.Log("CURLing " + app1Url + "/azure-samples-blob-traverser...");
                Utilities.Log(Utilities.CheckAddress("http://" + app1Url + "/azure-samples-blob-traverser"));
            }
            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);
                }
            }
        }
Пример #4
0
            public async Task CreateWebApp()
            {
                var     appProfile = GetAppProfile();
                IWebApp webApp     = null;


                await Spinner.StartAsync("", async spinner =>
                {
                    spinner.Text = $"Starting deployment for {appProfile.profile.PublishName}";

                    if (appProfile.isNew)
                    {
                        spinner.Text = $"Creating web app {appProfile.profile.PublishName}";

                        // create the webapp
                        try
                        {
                            if (appProfile.profile.PricingTier == PricingTier.SharedD1)
                            {
                                webApp = await GetSdkClient()
                                         .WebApps.Define(appProfile.profile.PublishName)
                                         .WithRegion(appProfile.profile.Region)
                                         .WithNewResourceGroup(appProfile.profile.ResourceGroup)
                                         .WithNewSharedAppServicePlan()
                                         .CreateAsync();
                            }
                            else
                            {
                                webApp = await GetSdkClient()
                                         .WebApps.Define(appProfile.profile.PublishName)
                                         .WithRegion(appProfile.profile.Region)
                                         .WithNewResourceGroup(appProfile.profile.ResourceGroup)
                                         .WithNewWindowsPlan(appProfile.profile.PricingTier)
                                         .CreateAsync();
                            }
                        }
                        catch (LogingException loginEx)
                        {
                            spinner.Fail(loginEx.Message);
                            return;
                        }
                        catch (Exception ex)
                        {
                            spinner.Fail($"Error creating web app {appProfile.profile.PublishName} - " + ex.Message);
                            return;
                        }
                    }
                    else
                    {
                        spinner.Text = $"{appProfile.profile.PublishName} already published, updating files.";

                        webApp = GetSdkClient()
                                 .WebApps.GetByResourceGroup(appProfile.profile.ResourceGroup, appProfile.profile.PublishName);
                    }

                    // get the zipdeploy url
                    var webUri = new Uri(string.Format("https://{0}.scm.azurewebsites.net/api/zipdeploy", appProfile.profile.PublishName));


                    spinner.Text = "Retrieving publishing profile.";
                    // get the publishing profile and create the auth token
                    var publishProfile = webApp.GetPublishingProfile();
                    var ftpUser        = publishProfile.FtpUsername.Split('\\')[1];
                    var val            = Convert.ToBase64String(Encoding.Default.GetBytes($"{ftpUser}:{publishProfile.FtpPassword}"));
                    string authToken   = $"Basic {val}";

                    try
                    {
                        spinner.Text = "Running dotnet publish.";
                        // run dotnet publish on application
                        try
                        {
                            var results = ShellHelper.Cmd($"dotnet publish {AppPath} -c Release -o {AppPath}/publish");
                            if (results.Contains(": error"))
                            {
                                throw new DotNetPublishException("Error building application", new Exception(results));
                            }
                        }
                        catch (DotNetPublishException dnex)
                        {
                            spinner.Fail(dnex.Message);
                            return;
                        }

                        spinner.Text = "Preparing files for upload.";
                        //zip publish folder
                        var zipFile = ZipContents(appProfile.profile);

                        spinner.Text  = "Uploading application.";
                        var published = await UploadFiles(webUri, zipFile, authToken);
                        if (published)
                        {
                            spinner.Text = $"App {appProfile.profile.PublishName} published.";

                            appProfile.profile.LastPublish = DateTime.Now;
                            SaveAppProfile(appProfile.profile);
                        }
                        else
                        {
                            throw new Exception("Could not deploy files, please try again.");
                        }
                    }
                    catch (Exception ex)
                    {
                        spinner.Fail($"Error creating web app {appProfile.profile.PublishName} - " + ex.Message);
                        throw ex; // throwing so caller can handle
                    }
                    spinner.Succeed($"Browse to https://{appProfile.profile.PublishName}.azurewebsites.net");
                });
            }