public PSAppServicePlan(AppServicePlan other) : base(
         location: other.Location,
         name: other.Name,
         id: other.Id,
         kind: other.Kind,
         type: other.Type,
         tags: other.Tags,
         workerTierName: other.WorkerTierName,
         status: other.Status,
         subscription: other.Subscription,
         adminSiteName: other.AdminSiteName,
         hostingEnvironmentProfile: other.HostingEnvironmentProfile,
         maximumNumberOfWorkers: other.MaximumNumberOfWorkers,
         geoRegion: other.GeoRegion,
         perSiteScaling: other.PerSiteScaling,
         numberOfSites: other.NumberOfSites,
         isSpot: other.IsSpot,
         spotExpirationTime: other.SpotExpirationTime,
         freeOfferExpirationTime: other.FreeOfferExpirationTime,
         resourceGroup: other.ResourceGroup,
         reserved: other.Reserved,
         isXenon: other.IsXenon,
         targetWorkerCount: other.TargetWorkerCount,
         targetWorkerSizeId: other.TargetWorkerSizeId,
         provisioningState: other.ProvisioningState,
         sku: other.Sku
         )
 {
 }
Пример #2
0
        public string CreateWebapp(String version, String acrPassword, String appName, String imageName, String planName)
        {
            //_log.Info("creating webapp");

            _webappClient.WebApps.Delete(_rgName, appName, false, false);
            AppServicePlan plan = _webappClient.AppServicePlans.Get(_rgName, planName);

            //_log.Info("creating site :" + appName);
            _webappClient.WebApps.CreateOrUpdate(_rgName, appName,
                                                 new Site
            {
                Location     = "westus2",
                ServerFarmId = plan.Id,
                SiteConfig   = new SiteConfig
                {
                    LinuxFxVersion = String.Format("DOCKER|{0}.azurecr.io/{1}", _acrName, imageName),
                    AppSettings    = new List <NameValuePair>
                    {
                        new NameValuePair("DOCKER_REGISTRY_SERVER_USERNAME", _acrName),
                        new NameValuePair("DOCKER_REGISTRY_SERVER_PASSWORD", acrPassword),
                        new NameValuePair("DOCKER_REGISTRY_SERVER_URL", string.Format("https://{0}.azurecr.io", _acrName)),
                        new NameValuePair("DOCKER_ENABLE_CI", "false"),
                        new NameValuePair("WEBSITES_ENABLE_APP_SERVICE_STORAGE", "false")
                    }
                }
            });

            User   user  = _webappClient.WebApps.ListPublishingCredentials(_rgName, appName);
            String cdUrl = String.Format("{0}/docker/hook", user.ScmUri);

            return(cdUrl);
        }
 public static AppServicePlan CreateOrUpdateServerFarm(this IAppServicePlansOperations serverFarm,
                                                       string resourceGroupName,
                                                       string name,
                                                       AppServicePlan appServicePlan)
 {
     return(serverFarm.CreateOrUpdate(resourceGroupName, name, appServicePlan));
 }
Пример #4
0
        public string CreateWebappGitDeploy(String version, String acrPassword, String appName,
                                            String imageName, String planName, String targetRepo, GitHubUtils gitHubUtils)
        {
            int tries = 0;

            while (true)
            {
                try
                {
                    //_log.Info("creating webapp");

                    _webappClient.WebApps.Delete(_rgName, appName, false, false);
                    AppServicePlan plan = _webappClient.AppServicePlans.Get(_rgName, planName);

                    //_log.Info("creating site :" + appName);
                    _webappClient.WebApps.CreateOrUpdate(_rgName, appName,
                                                         new Site
                    {
                        Location     = "westus2",
                        ServerFarmId = plan.Id,
                        SiteConfig   = new SiteConfig
                        {
                            LinuxFxVersion = String.Format("DOCKER|{0}.azurecr.io/{1}", _acrName, imageName),
                            AppSettings    = new List <NameValuePair>
                            {
                                //new NameValuePair("DOCKER_REGISTRY_SERVER_USERNAME", _acrName),
                                new NameValuePair("DOCKER_REGISTRY_SERVER_PASSWORD", acrPassword),
                                new NameValuePair("DOCKER_REGISTRY_SERVER_URL", string.Format("https://{0}.azurecr.io", _acrName)),
                                new NameValuePair("DOCKER_ENABLE_CI", "false"),
                                new NameValuePair("WEBSITES_ENABLE_APP_SERVICE_STORAGE", "false")
                            }
                        }
                    });

                    //get publishing profile
                    var publishingProfile = _webappClient.WebApps.ListPublishingCredentials(_rgName, appName);

                    //clone app repo
                    String timeStamp = DateTime.Now.ToString("yyyyMMddHHmmss");
                    String random    = new Random().Next(0, 9999).ToString();
                    String path      = String.Format("D:\\local\\Temp\\blimp{0}{1}", timeStamp, random);
                    gitHubUtils.Clone(targetRepo, path, "master");

                    //push repo
                    gitHubUtils.Push(path, "master", publishingProfile.ScmUri + "/" + appName + ".git");
                    gitHubUtils.Delete(path);
                    return("");
                }
                catch (Exception e)
                {
                    if (tries >= 3)
                    {
                        throw e;
                    }
                    System.Threading.Thread.Sleep(60 * 1000);
                    tries = tries + 1;
                }
            }
        }
Пример #5
0
        public override void ExecuteCmdlet()
        {
            base.ExecuteCmdlet();

            string deletedSiteId = string.IsNullOrEmpty(DeletedId) ? GetDeletedSiteResourceId() : DeletedId;

            ResolveTargetParameters();

            DeletedAppRestoreRequest restoreReq = new DeletedAppRestoreRequest()
            {
                DeletedSiteId        = deletedSiteId,
                RecoverConfiguration = !this.RestoreContentOnly,
                UseDRSecondary       = UseDisasterRecovery
            };

            Action restoreAction = () => WebsitesClient.RestoreDeletedWebApp(TargetResourceGroupName, TargetName, TargetSlot, restoreReq);

            if (WebsitesClient.WebAppExists(TargetResourceGroupName, TargetName, TargetSlot))
            {
                ConfirmAction(this.Force.IsPresent, "Target web app contents will be overwritten with the contents of the deleted app.",
                              "The deleted app has been restored.", TargetName, restoreAction);
            }
            else
            {
                if (string.IsNullOrEmpty(TargetAppServicePlanName))
                {
                    throw new Exception("Target app " + TargetName + " does not exist. Specify TargetAppServicePlanName for it to be created automatically.");
                }
                AppServicePlan plan = WebsitesClient.GetAppServicePlan(TargetResourceGroupName, TargetAppServicePlanName);
                if (plan == null)
                {
                    throw new Exception("Target App Service Plan " + TargetAppServicePlanName + " not found in target Resource Group " + TargetResourceGroupName);
                }
                try
                {
                    Action createRestoreAction = () =>
                    {
                        WebsitesClient.CreateWebApp(TargetResourceGroupName, TargetName, TargetSlot, plan.Location, TargetAppServicePlanName,
                                                    null, string.Empty, string.Empty);
                        restoreAction();
                    };
                    string confirmMsg = string.Format("This web app will be created. App Name: {0}, Resource Group: {1}", TargetName, TargetResourceGroupName);
                    if (!string.IsNullOrEmpty(TargetSlot))
                    {
                        confirmMsg += ", Slot: " + TargetSlot;
                    }
                    ConfirmAction(this.Force.IsPresent, confirmMsg, "The deleted app has been restored.", TargetName, createRestoreAction);
                }
                catch (Exception e)
                {
                    WebsitesClient.RemoveWebApp(TargetResourceGroupName, TargetName, TargetSlot, true, true, false);
                    throw e;
                }
            }

            PSSite restoredApp = new PSSite(WebsitesClient.GetWebApp(TargetResourceGroupName, TargetName, TargetSlot));

            WriteObject(restoredApp);
        }
        public async Task Get()
        {
            var planName = Recording.GenerateAssetName("testDisk-");
            var plan1    = await CreateAppServicePlanAsync(planName);

            AppServicePlan plan2 = await plan1.GetAsync();

            ResourceDataHelper.AssertPlan(plan1.Data, plan2.Data);
        }
        public override void ExecuteCmdlet()
        {
            if (HyperV.IsPresent &&
                (Tier != "PremiumContainer" && Tier != "PremiumV3"))
            {
                throw new Exception("HyperV switch is only allowed for PremiumContainer or PremiumV3 tiers");
            }
            if (!HyperV.IsPresent && Tier == "PremiumContainer")
            {
                throw new Exception("PremiumContainer tier is only allowed if HyperV switch is present");
            }

            if (string.IsNullOrWhiteSpace(Tier))
            {
                Tier = "Free";
            }

            if (string.IsNullOrWhiteSpace(WorkerSize))
            {
                WorkerSize = "Small";
            }

            var aseResourceGroupName = AseResourceGroupName;

            if (!string.IsNullOrEmpty(AseName) &&
                string.IsNullOrEmpty(aseResourceGroupName))
            {
                aseResourceGroupName = ResourceGroupName;
            }

            var capacity = NumberofWorkers < 1 ? 1 : NumberofWorkers;
            var skuName  = CmdletHelpers.GetSkuName(Tier, WorkerSize);

            var sku = new SkuDescription
            {
                Tier     = Tier,
                Name     = skuName,
                Capacity = capacity
            };

            var appServicePlan = new AppServicePlan
            {
                Location       = Location,
                Sku            = sku,
                PerSiteScaling = PerSiteScaling,
                IsXenon        = HyperV.IsPresent,
                Tags           = (IDictionary <string, string>)CmdletHelpers.ConvertToStringDictionary(Tag),
                Reserved       = Linux.IsPresent
            };

            AppServicePlan   retPlan = WebsitesClient.CreateOrUpdateAppServicePlan(ResourceGroupName, Name, appServicePlan, AseName, aseResourceGroupName);
            PSAppServicePlan psPlan  = new PSAppServicePlan(retPlan);

            WriteObject(psPlan, true);
        }
Пример #8
0
        public async Task Get()
        {
            var container = await GetAppServicePlanCollectionAsync();

            var planName = Recording.GenerateAssetName("testAppServicePlan-");
            var input    = ResourceDataHelper.GetBasicAppServicePlanData(DefaultLocation);
            var lro      = await container.CreateOrUpdateAsync(planName, input);

            AppServicePlan plan1 = lro.Value;
            AppServicePlan plan2 = await container.GetAsync(planName);

            ResourceDataHelper.AssertPlan(plan1.Data, plan2.Data);
        }
Пример #9
0
        private static void DeleteApps(String planName)
        {
            AppServicePlan appServicePlan = webClient.AppServicePlans.Get(resourceGroupName, planName);
            List <Site>    apps           = webClient.WebApps.ListByResourceGroup(resourceGroupName)             //Get all of the apps in the resource group
                                            .Where(x => x.ServerFarmId.ToLower() == appServicePlan.Id.ToLower()) //Get all of the apps in the given app service plan
                                            .Where(x => !SaveApp(x.Name))
                                            .ToList();

            foreach (Site site in apps)
            {
                pipelineUtils.DeleteWebapp(site.Name, planName);
            }
        }
Пример #10
0
        public string CreateWebapp(String version, String acrPassword, String appName, String imageName, String planName)
        {
            int tries = 0;

            while (true)
            {
                try
                {
                    //_log.Info("creating webapp");
                    try
                    {
                        _webappClient.WebApps.Delete(_rgName, appName, false, false);
                    }
                    catch
                    {
                        // noop
                    }
                    AppServicePlan plan = _webappClient.AppServicePlans.Get(_rgName, planName);

                    //_log.Info("creating site :" + appName);
                    _webappClient.WebApps.CreateOrUpdate(_rgName, appName,
                                                         new Site
                    {
                        Location     = "centralus",
                        ServerFarmId = plan.Id,
                        SiteConfig   = new SiteConfig
                        {
                            LinuxFxVersion = String.Format("DOCKER|{0}.azurecr.io/{1}", _acrName, imageName),
                            AppSettings    = new List <NameValuePair>
                            {
                                new NameValuePair("DOCKER_REGISTRY_SERVER_USERNAME", _acrName),
                                new NameValuePair("DOCKER_REGISTRY_SERVER_PASSWORD", acrPassword),
                                new NameValuePair("DOCKER_REGISTRY_SERVER_URL", string.Format("https://{0}.azurecr.io", _acrName)),
                                new NameValuePair("DOCKER_ENABLE_CI", "false"),
                                new NameValuePair("WEBSITES_ENABLE_APP_SERVICE_STORAGE", "false")
                            }
                        }
                    });
                    return("");
                }
                catch (Exception e)
                {
                    if (tries >= 3)
                    {
                        throw e;
                    }
                    System.Threading.Thread.Sleep(60 * 1000);
                    tries = tries + 1;
                }
            }
        }
Пример #11
0
        public async Task CheckIfExistsAsync()
        {
            var container = await GetAppServicePlanCollectionAsync();

            var planName = Recording.GenerateAssetName("testAppService-");
            var input    = ResourceDataHelper.GetBasicAppServicePlanData(DefaultLocation);
            var lro      = await container.CreateOrUpdateAsync(planName, input);

            AppServicePlan plan = lro.Value;

            Assert.IsTrue(await container.CheckIfExistsAsync(planName));
            Assert.IsFalse(await container.CheckIfExistsAsync(planName + "1"));

            Assert.ThrowsAsync <ArgumentNullException>(async() => _ = await container.CheckIfExistsAsync(null));
        }
Пример #12
0
        public static async Task CreateAppServicePlan(
            [ActivityTrigger] CreationParameters creationParams,
            ILogger log)
        {
            log.LogWarning("Creating App Service Plan in Resource Group: {resourceGroupName}", creationParams.ResourceGroupName);

            var websiteClientProvider = Container.GetService <IAzureClientProvider <IWebSiteManagementClient> >();
            var websiteClient         = await websiteClientProvider.Get(creationParams.TenantID, creationParams.SubscriptionID);

            string aspName = creationParams.CustomerShortName + "-asp";

            //"sku": {
            //	"name": "S1",
            //	"tier": "Standard",
            //	"size": "S1",
            //	"family": "S",
            //	"capacity": 1
            //}

            var appServicePlan = new AppServicePlan(maximumNumberOfWorkers: 20, location: creationParams.AzureResourceLocation)
            {
                Sku = new SkuDescription()
                {
                    Name     = "S1",
                    Tier     = Microsoft.Azure.Management.WebSites.Models.SkuName.Standard,
                    Size     = "S1",
                    Family   = "S",
                    Capacity = 1
                },
                AppServicePlanName = aspName,
                PerSiteScaling     = false,
                Tags = GenerateTags(creationParams)
            };

            try
            {
                var asp = await websiteClient.AppServicePlans.CreateOrUpdateAsync(creationParams.ResourceGroupName, aspName, appServicePlan);

                log.LogWarning($"Created App Service Plan {asp.AppServicePlanName} in Resource Group: {asp.ResourceGroup}");
            }
            catch (Exception e)
            {
                log.LogError(e, "Unable to create app service plan {name}", aspName);
                throw;
            }
        }
Пример #13
0
            private SiteConfig GetNewConfig(AppServicePlan appServiceplan)
            {
                bool       newConfigAdded = false;
                SiteConfig siteConfig     = new SiteConfig();

                siteConfig.AppSettings = new List <NameValuePair>();

                string containerImageName = _cmdlet.ContainerImageName;

                if (containerImageName != null)
                {
                    containerImageName = CmdletHelpers.DockerImagePrefix + containerImageName;
                    if (appServiceplan == null || appServiceplan.IsXenon.GetValueOrDefault())
                    {
                        siteConfig.WindowsFxVersion = containerImageName;
                        newConfigAdded = true;
                    }
                }
                if (_cmdlet.ContainerRegistryUrl != null)
                {
                    siteConfig.AppSettings.Add(new NameValuePair(CmdletHelpers.DockerRegistryServerUrl, _cmdlet.ContainerRegistryUrl));
                    newConfigAdded = true;
                }
                if (_cmdlet.ContainerRegistryUser != null)
                {
                    siteConfig.AppSettings.Add(new NameValuePair(CmdletHelpers.DockerRegistryServerUserName, _cmdlet.ContainerRegistryUser));
                    newConfigAdded = true;
                }
                if (_cmdlet.ContainerRegistryPassword != null)
                {
                    siteConfig.AppSettings.Add(new NameValuePair(CmdletHelpers.DockerRegistryServerPassword, _cmdlet.ContainerRegistryPassword.ConvertToString()));
                    newConfigAdded = true;
                }
                if (_cmdlet.EnableContainerContinuousDeployment.IsPresent)
                {
                    siteConfig.AppSettings.Add(new NameValuePair(CmdletHelpers.DockerEnableCI, "true"));
                    newConfigAdded = true;
                }
                return(newConfigAdded ? siteConfig : null);
            }
Пример #14
0
        public AppServicePlan CreateAppServicePlan(string resourceGroupName, string appServicePlanName, string location, string adminSiteName, SkuDescription sku, string aseName = null, string aseResourceGroupName = null, bool?perSiteScaling = false)
        {
            var appServicePlan = new AppServicePlan
            {
                Location           = location,
                AppServicePlanName = appServicePlanName,
                Sku            = sku,
                AdminSiteName  = adminSiteName,
                PerSiteScaling = perSiteScaling
            };

            if (!string.IsNullOrEmpty(aseName) &&
                !string.IsNullOrEmpty(aseResourceGroupName))
            {
                appServicePlan.HostingEnvironmentProfile = new HostingEnvironmentProfile(
                    id: CmdletHelpers.GetApplicationServiceEnvironmentResourceId(WrappedWebsitesClient.SubscriptionId, aseResourceGroupName, aseName),
                    name: aseName,
                    type: CmdletHelpers.ApplicationServiceEnvironmentResourcesName);
            }

            return(WrappedWebsitesClient.AppServicePlans().CreateOrUpdate(resourceGroupName, appServicePlanName, appServicePlan));
        }
Пример #15
0
        public async Task Setup()
        {
            var resourceManagementEndpointBaseUri =
                Environment.GetEnvironmentVariable(AccountVariables.ResourceManagementEndPoint) ??
                DefaultVariables.ResourceManagementEndpoint;
            var activeDirectoryEndpointBaseUri =
                Environment.GetEnvironmentVariable(AccountVariables.ActiveDirectoryEndPoint) ??
                DefaultVariables.ActiveDirectoryEndpoint;

            resourceGroupName = Guid.NewGuid().ToString();

            clientId       = ExternalVariables.Get(ExternalVariable.AzureSubscriptionClientId);
            clientSecret   = ExternalVariables.Get(ExternalVariable.AzureSubscriptionPassword);
            tenantId       = ExternalVariables.Get(ExternalVariable.AzureSubscriptionTenantId);
            subscriptionId = ExternalVariables.Get(ExternalVariable.AzureSubscriptionId);
            var resourceGroupLocation = Environment.GetEnvironmentVariable("AZURE_NEW_RESOURCE_REGION") ?? "eastus";

            authToken = await Auth.GetAuthTokenAsync(activeDirectoryEndpointBaseUri, resourceManagementEndpointBaseUri,
                                                     tenantId, clientId, clientSecret);

            var resourcesClient = new ResourcesManagementClient(subscriptionId,
                                                                new ClientSecretCredential(tenantId, clientId, clientSecret));

            resourceGroupClient = resourcesClient.ResourceGroups;

            resourceGroup = new ResourceGroup(resourceGroupLocation);
            resourceGroup = await resourceGroupClient.CreateOrUpdateAsync(resourceGroupName, resourceGroup);

            webMgmtClient = new WebSiteManagementClient(new TokenCredentials(authToken))
            {
                SubscriptionId = subscriptionId,
                HttpClient     = { BaseAddress = new Uri(DefaultVariables.ResourceManagementEndpoint), Timeout = TimeSpan.FromMinutes(5) },
            };

            svcPlan = await webMgmtClient.AppServicePlans.CreateOrUpdateAsync(resourceGroup.Name,
                                                                              resourceGroup.Name,
                                                                              new AppServicePlan(resourceGroup.Location) { Sku = new SkuDescription("S1", "Standard") }
                                                                              );
        }
Пример #16
0
            public async Task <ResourceConfig <Site> > CreateConfigAsync()
            {
                _cmdlet.ResourceGroupName = _cmdlet.ResourceGroupName ?? _cmdlet.Name;
                _cmdlet.AppServicePlan    = _cmdlet.AppServicePlan ?? _cmdlet.Name;

                var planResourceGroup = _cmdlet.ResourceGroupName;
                var planName          = _cmdlet.AppServicePlan;

                var rgStrategy = ResourceGroupStrategy.CreateResourceGroupConfig(_cmdlet.ResourceGroupName);
                var planRG     = rgStrategy;

                if (_cmdlet.MyInvocation.BoundParameters.ContainsKey(nameof(AppServicePlan)))
                {
                    if (!_cmdlet.TryGetServerFarmFromResourceId(_cmdlet.AppServicePlan, out planResourceGroup, out planName))
                    {
                        planResourceGroup = _cmdlet.ResourceGroupName;
                        planName          = _cmdlet.AppServicePlan;
                    }

                    planRG = ResourceGroupStrategy.CreateResourceGroupConfig(planResourceGroup);
                }
                else
                {
                    var farm = await _cmdlet.GetDefaultServerFarm(Location);

                    if (farm != null)
                    {
                        planResourceGroup = farm.ResourceGroup;
                        planName          = farm.Name;
                        planRG            = ResourceGroupStrategy.CreateResourceGroupConfig(planResourceGroup);
                    }
                }
                AppServicePlan appServiceplan = _websitesClient.GetAppServicePlan(planResourceGroup, planName);

                // If ContainerImageName is specified and appservice plan doesn’t exist (appServiceplan == null) we will try to create plan with windows container
                var farmStrategy = planRG.CreateServerFarmConfig(planResourceGroup, planName, appServiceplan == null && _cmdlet.ContainerImageName != null);

                return(rgStrategy.CreateSiteConfig(farmStrategy, _cmdlet.Name, this.GetNewConfig(appServiceplan)));
            }
Пример #17
0
        private async Task <AppServicePlan> GetDefaultServerFarm(string location)
        {
            var websiteLocation = string.IsNullOrWhiteSpace(location) ? new LocationConstraint() : new LocationConstraint(location);
            var farmResources   = await ResourcesClient.ResourceManagementClient.Resources.ListAsync(new ODataQuery <GenericResourceFilter>(r => r.ResourceType == "Microsoft.Web/serverFarms"));

            AppServicePlan defaultFarm = null;

            foreach (var resource in farmResources)
            {
                // Try to find a policy with Sku=Free and available site capacity
                var id   = new ResourceIdentifier(resource.Id);
                var farm = await WebsitesClient.WrappedWebsitesClient.AppServicePlans.GetAsync(id.ResourceGroupName, id.ResourceName);

                if (websiteLocation.Match(farm.Location) &&
                    string.Equals("free", farm.Sku?.Tier?.ToLower(), StringComparison.OrdinalIgnoreCase) &&
                    farm.NumberOfSites < MaxFreeSites)
                {
                    defaultFarm = farm;
                    break;
                }
            }

            return(defaultFarm);
        }
Пример #18
0
        public GithubActionsWithAnAzureFunction()
        {
            var config      = new Config();
            var azureRegion = config.Require("azureRegion");

            var workloadResources = "ghares";
            var workloadFunction  = "ghafunc";

            var resourceGroupForResources = ResourceGroupFactory.Create(GetName("rg", workloadResources, azureRegion));
            var resourceGroupForFunction  = ResourceGroupFactory.Create(GetName("rg", workloadFunction, azureRegion));

            // Storage account is required by Function App.
            // Also, we will upload the function code to the same storage account.
            var storageAccount = StorageAccountFactory.Create(resourceGroupForResources, $"st{workloadResources}{Deployment.Instance.StackName}{azureRegion}001");

            // Export the primary key of the Storage Account
            this.PrimaryStorageKey = Output.Tuple(resourceGroupForResources.Name, storageAccount.Name).Apply(names =>
                                                                                                             Output.CreateSecret(GetStorageAccountPrimaryKey(names.Item1, names.Item2)));

            var functionSku = config.Require("functionSku").Split('/');

            // Define a Consumption Plan for the Function App.
            // You can change the SKU to Premium or App Service Plan if needed.
            var appServicePlanName = GetName("plan", workloadFunction, azureRegion);
            var appServicePlan     = new AppServicePlan(appServicePlanName, new AppServicePlanArgs
            {
                Name = appServicePlanName,

                ResourceGroupName = resourceGroupForResources.Name,

                // Run on Linux
                Kind = "Linux",

                // Consumption plan SKU
                Sku = new SkuDescriptionArgs
                {
                    Tier = functionSku[0],
                    Name = functionSku[1]
                },

                // For Linux, you need to change the plan to have Reserved = true property.
                Reserved = true
            }, new CustomResourceOptions {
                DeleteBeforeReplace = true
            });

            var container = new BlobContainer("zips-container", new BlobContainerArgs
            {
                AccountName       = storageAccount.Name,
                PublicAccess      = PublicAccess.None,
                ResourceGroupName = resourceGroupForResources.Name,
            }, new CustomResourceOptions {
                DeleteBeforeReplace = true
            });

            var functionAppPublishFolder = Path.Combine("C:\\dev\\swiftbit\\GithubActionsWithAzureFunction\\src", "GithubActions.AzureFunction", "bin", "Release", "netcoreapp3.1", "publish");
            var blob = new Blob("zip", new BlobArgs
            {
                AccountName       = storageAccount.Name,
                ContainerName     = container.Name,
                ResourceGroupName = resourceGroupForResources.Name,
                Type   = BlobType.Block,
                Source = new FileArchive(functionAppPublishFolder)
            }, new CustomResourceOptions {
                DeleteBeforeReplace = true
            });

            var codeBlobUrl = SignedBlobReadUrl(blob, container, storageAccount, resourceGroupForResources);

            // Application insights
            var appInsightsName = GetName("appi", workloadFunction, azureRegion);
            var appInsights     = new Component(appInsightsName, new ComponentArgs
            {
                ResourceName = appInsightsName,

                ApplicationType   = ApplicationType.Web,
                Kind              = "web",
                ResourceGroupName = resourceGroupForResources.Name,
            }, new CustomResourceOptions {
                DeleteBeforeReplace = true
            });

            var funcName = GetName("func", workloadFunction, azureRegion);
            var app      = new WebApp(funcName, new WebAppArgs
            {
                Name = funcName,

                Kind = "FunctionApp",
                ResourceGroupName = resourceGroupForFunction.Name,
                ServerFarmId      = appServicePlan.Id,
                SiteConfig        = new SiteConfigArgs
                {
                    AppSettings = new[]
                    {
                        new NameValuePairArgs {
                            Name  = "AzureWebJobsStorage",
                            Value = GetConnectionString(resourceGroupForResources.Name, storageAccount.Name),
                        },
                        new NameValuePairArgs {
                            Name  = "runtime",
                            Value = "dotnet",
                        },
                        new NameValuePairArgs {
                            Name  = "FUNCTIONS_WORKER_RUNTIME",
                            Value = "dotnet",
                        },
                        new NameValuePairArgs {
                            Name  = "WEBSITE_RUN_FROM_PACKAGE",
                            Value = codeBlobUrl,
                        },
                        new NameValuePairArgs {
                            Name  = "APPLICATIONINSIGHTS_CONNECTION_STRING",
                            Value = Output.Format($"InstrumentationKey={appInsights.InstrumentationKey}"),
                        },
                        new NameValuePairArgs {
                            Name  = "Greeting",
                            Value = "Hi",
                        },
                    },
                },
            });

            this.Endpoint = Output.Format($"https://{app.DefaultHostName}/api/HelloFunction?name=Pulumi");
        }
Пример #19
0
        public AppServicePlan CreateOrUpdateAppServicePlan(string resourceGroupName, string appServicePlanName, AppServicePlan appServicePlan, string aseRecourceId)
        {
            if (!string.IsNullOrEmpty(aseRecourceId))
            {
                string aseResourceGroupName, aseName;
                if (!CmdletHelpers.TryParseAppServiceEnvironmentMetadataFromResourceId(aseRecourceId, out aseResourceGroupName, out aseName))
                {
                    throw new ArgumentException(string.Format("AseResourceId format is invalid"));
                }
                appServicePlan.HostingEnvironmentProfile = new HostingEnvironmentProfile(
                    id: aseRecourceId,
                    name: aseName,
                    type: CmdletHelpers.AppServiceEnvironmentResourcesName);
            }

            return(WrappedWebsitesClient.AppServicePlans().CreateOrUpdate(resourceGroupName, appServicePlanName, appServicePlan));
        }
Пример #20
0
        public AzureApplications(Construct scope, string id) : base(scope, id)
        {
            // Update organization name
            const string orgName = "jet";

            // define resources here
            var azureProvider = new AzurermProvider(this, "AzureRm", new AzurermProviderConfig
            {
                Features = new[] { new AzurermProviderFeatures() }
            });

            var resourceGroup = new ResourceGroup(this, "basket", new ResourceGroupConfig
            {
                Name     = "basket",
                Location = "canadaeast",
                Provider = azureProvider
            });

            var appServicePlan = new AppServicePlan(this, "appServicePlan", new AppServicePlanConfig
            {
                Name              = $"{orgName}-appServicePlan",
                Kind              = "Linux",
                Reserved          = true,
                ResourceGroupName = resourceGroup.Name,
                Location          = resourceGroup.Location,
                Sku = new IAppServicePlanSku[] { new AppServicePlanSku {
                                                     Size = "P1V2", Tier = "Premium"
                                                 } },
                DependsOn = new ITerraformDependable[] { resourceGroup }
            });

            var appService = new AppService(this, "appService", new AppServiceConfig
            {
                Name                  = $"{orgName}-appService",
                AppServicePlanId      = appServicePlan.Id,
                Location              = resourceGroup.Location,
                ResourceGroupName     = resourceGroup.Name,
                ClientAffinityEnabled = false,
                HttpsOnly             = true,
                DependsOn             = new ITerraformDependable[] { appServicePlan },
                AppSettings           = new Dictionary <string, string>
                {
                    { "Environment", "Production" },
                }
            });

            var appServiceSlot = new AppServiceSlot(this, "appServiceSlot", new AppServiceSlotConfig
            {
                Name              = $"{orgName}-appServiceSlot",
                AppServicePlanId  = appServicePlan.Id,
                Location          = resourceGroup.Location,
                ResourceGroupName = resourceGroup.Name,
                AppServiceName    = appService.Name,
                HttpsOnly         = true,
                DependsOn         = new ITerraformDependable[] { appService },
                AppSettings       = new Dictionary <string, string>
                {
                    { "Environment", "Production" }
                }
            });

            var storageAccount = new StorageAccount(this, "ssd", new StorageAccountConfig
            {
                Name                   = $"{orgName}ssd",
                Location               = resourceGroup.Location,
                ResourceGroupName      = resourceGroup.Name,
                AccountKind            = "StorageV2",
                AccountReplicationType = "LRS",
                AccountTier            = "Premium"
            });

            var functionApp = new FunctionApp(this, "functionApp", new FunctionAppConfig
            {
                Name                    = $"{orgName}-functionApp",
                AppServicePlanId        = appServicePlan.Id,
                Location                = resourceGroup.Location,
                ResourceGroupName       = resourceGroup.Name,
                Version                 = "3",
                StorageAccountName      = storageAccount.Name,
                StorageAccountAccessKey = storageAccount.PrimaryAccessKey,
                OsType                  = "linux",
                SiteConfig              = new IFunctionAppSiteConfig[]
                {
                    new FunctionAppSiteConfig
                    {
                        AlwaysOn = true
                    }
                },
                AppSettings = new Dictionary <string, string>()
                {
                    { "WEBSITE_RUN_FROM_PACKAGE", "" },
                    { "FUNCTIONS_WORKER_RUNTIME", "dotnet" }
                },
                DependsOn = new ITerraformDependable[] { appServicePlan, storageAccount }
            });

            // Grab tenant Id from azure and update tenantId for keyVault
            // $ az account list
            // Uncomment below lines

            // var keyVault = new KeyVault(this, "keyvault", new KeyVaultConfig
            // {
            //     Name = $"{orgName}-keyvault-1",
            //     Location = resourceGroup.Location,
            //     ResourceGroupName = resourceGroup.Name,
            //     SkuName = "standard",
            //     TenantId = "<replace_tenant_id>"
            // });

            var cosmosdbAccount = new CosmosdbAccount(this, "cosmosdb", new CosmosdbAccountConfig
            {
                Name              = $"{orgName}-cosmosdb",
                Location          = resourceGroup.Location,
                ResourceGroupName = resourceGroup.Name,
                OfferType         = "Standard",
                Kind              = "GlobalDocumentDB",
                GeoLocation       = new ICosmosdbAccountGeoLocation[]
                {
                    new CosmosdbAccountGeoLocation
                    {
                        Location         = resourceGroup.Location,
                        FailoverPriority = 0,
                        ZoneRedundant    = false
                    }
                },
                ConsistencyPolicy = new ICosmosdbAccountConsistencyPolicy[]
                {
                    new CosmosdbAccountConsistencyPolicy
                    {
                        ConsistencyLevel = "Session"
                    }
                }
            });

            var appServiceOutput = new TerraformOutput(this, "appweburl", new TerraformOutputConfig
            {
                Value = $"https://{appService.Name}.azurewebsites.net"
            });
            var functionAppOutput = new TerraformOutput(this, "fnWebUrl", new TerraformOutputConfig
            {
                Value = $"https://{functionApp.Name}.azurewebsites.net"
            });
            var cosmosDbOutput = new TerraformOutput(this, "cosmosDbURL", new TerraformOutputConfig
            {
                Value = cosmosdbAccount.Endpoint
            });
        }
Пример #21
0
        static async Task CreateSite(string rgName, string appServicePlanName, string siteName, string location)
        {
            // Create/Update the resource group
            var rgCreateResult = await _resourceGroupClient.ResourceGroups.CreateOrUpdateAsync(rgName, new ResourceGroup { Location = location });

            // Create/Update the App Service Plan
            var serverFarmWithRichSku = new AppServicePlan
            {
                Location = location,
                Sku      = new SkuDescription
                {
                    Name = "F1",
                    Tier = "Free"
                }
            };

            serverFarmWithRichSku = await _websiteClient.AppServicePlans.CreateOrUpdateAsync(rgName, appServicePlanName, serverFarmWithRichSku);

            // Create/Update the Website
            var site = new Site
            {
                Location     = location,
                ServerFarmId = appServicePlanName
            };

            site = await _websiteClient.WebApps.CreateOrUpdateAsync(rgName, siteName, site);

            Console.WriteLine($"Site outbound IP addresses: {site.OutboundIpAddresses}");

            // Create/Update the Website configuration
            var siteConfig = new SiteConfig
            {
                Location   = location,
                PhpVersion = "5.6"
            };

            siteConfig = await _websiteClient.WebApps.CreateOrUpdateConfigurationAsync(rgName, siteName, siteConfig);

            // Create/Update some App Settings
            var appSettings = new StringDictionary
            {
                Location   = location,
                Properties = new Dictionary <string, string>
                {
                    { "MyFirstKey", "My first value" },
                    { "MySecondKey", "My second value" }
                }
            };
            await _websiteClient.WebApps.UpdateApplicationSettingsAsync(rgName, siteName, appSettings);

            // Create/Update some Connection Strings
            var connStrings = new ConnectionStringDictionary
            {
                Location   = location,
                Properties = new Dictionary <string, ConnStringValueTypePair>
                {
                    { "MyFirstConnString", new ConnStringValueTypePair {
                          Value = "My SQL conn string", Type = ConnectionStringType.SQLAzure
                      } },
                    { "MySecondConnString", new ConnStringValueTypePair {
                          Value = "My custom conn string", Type = ConnectionStringType.Custom
                      } }
                }
            };
            await _websiteClient.WebApps.UpdateConnectionStringsAsync(rgName, siteName, connStrings);

            // List the site quotas
            Console.WriteLine("Site quotas:");
            var quotas = await _websiteClient.WebApps.ListUsagesAsync(rgName, siteName);

            foreach (var quota in quotas)
            {
                Console.WriteLine($"    {quota.Name.Value}: {quota.CurrentValue} {quota.Unit}");
            }

            // Get the publishing profile xml file
            using (var stream = await _websiteClient.WebApps.ListPublishingProfileXmlWithSecretsAsync(rgName, siteName, new CsmPublishingProfileOptions()))
            {
                string profileXml = await(new StreamReader(stream)).ReadToEndAsync();
                Console.WriteLine(profileXml);
            }

            // Restart the site
            await _websiteClient.WebApps.RestartAsync(rgName, siteName, softRestart : true);
        }
Пример #22
0
        public FunctionStack()
        {
            const string projectName = "pulumiazurenative";
            var          stackName   = Deployment.Instance.StackName;

            #region Resource Group

            var resourceGroupName = $"{projectName}-{stackName}-rg";
            var resourceGroup     = new ResourceGroup(resourceGroupName, new ResourceGroupArgs
            {
                ResourceGroupName = resourceGroupName
            });

            #endregion

            #region Storage Account

            var storageAccountName = $"{projectName}{stackName}st";
            var storageAccount     = new StorageAccount(storageAccountName, new StorageAccountArgs
            {
                ResourceGroupName = resourceGroup.Name,
                AccountName       = storageAccountName,
                Sku = new SkuArgs
                {
                    Name = SkuName.Standard_LRS
                },
                Kind = Kind.StorageV2
            });

            #endregion

            #region Plan

            var planName = $"{projectName}-{stackName}-plan";
            var plan     = new AppServicePlan(planName, new AppServicePlanArgs
            {
                ResourceGroupName = resourceGroup.Name,
                Name = planName,
                Kind = "Linux",
                // Consumption plan SKU
                Sku = new SkuDescriptionArgs
                {
                    Tier = "Dynamic",
                    Name = "Y1"
                },
                // For Linux, you need to change the plan to have Reserved = true property.
                Reserved = true
            });

            #endregion

            #region Func Blob

            var container = new BlobContainer("zips", new BlobContainerArgs
            {
                AccountName       = storageAccount.Name,
                ResourceGroupName = resourceGroup.Name,
                PublicAccess      = PublicAccess.None
            });

            var blob = new Blob("funczip", new BlobArgs
            {
                AccountName       = storageAccount.Name,
                ResourceGroupName = resourceGroup.Name,
                ContainerName     = container.Name,
                Type   = BlobType.Block,
                Source = new FileArchive("../PulumiAzureNative.Func/bin/Debug/netcoreapp3.1/publish")
            });

            var codeBlobUrl = SignedBlobReadUrl(blob, container, storageAccount, resourceGroup);

            #endregion

            #region Func

            var funcName = $"{projectName}-{stackName}-func";
            var func     = new WebApp(funcName, new WebAppArgs
            {
                Name = funcName,
                Kind = "FunctionApp",
                ResourceGroupName = resourceGroup.Name,
                ServerFarmId      = plan.Id,
                SiteConfig        = new SiteConfigArgs
                {
                    AppSettings = new[]
                    {
                        new NameValuePairArgs {
                            Name  = "AzureWebJobsStorage",
                            Value = GetStorageConnectionString(resourceGroup.Name, storageAccount.Name)
                        },
                        new NameValuePairArgs {
                            Name  = "runtime",
                            Value = "dotnet"
                        },
                        new NameValuePairArgs {
                            Name  = "WEBSITE_RUN_FROM_PACKAGE",
                            Value = codeBlobUrl
                        }
                    }
                }
            });

            #endregion

            #region Func Abstraction

            /*
             * var funcName1 = $"{projectName}-{stackName}-func1";
             * var func1 = new PackageFunctionApp(funcName1, new PackageFunctionAppArgs
             * {
             *  ProjectName = projectName,
             *  ResourceGroup = resourceGroup,
             *  StorageAccount = storageAccount,
             *  Plan = plan,
             *  Archive = new FileArchive("../PulumiAzureNative.Func/bin/Debug/netcoreapp3.1/publish")
             * });
             */
            #endregion

            TestEndpoint = Output.Format($"https://{func.DefaultHostName}/api/Hello?name=PulumiDemo");
            //TestEndpoint1 = Output.Format($"https://{func1.FunctionApp.Apply(f => f.DefaultHostName)}/api/Hello?name=PulumiDemo");
        }
Пример #23
0
    public MyStack()
    {
        var resourceGroup = new ResourceGroup("appservice-docker-rg");

        var plan = new AppServicePlan("linux-apps", new AppServicePlanArgs
        {
            ResourceGroupName = resourceGroup.Name,
            Kind     = "Linux",
            Reserved = true,
            Sku      = new SkuDescriptionArgs
            {
                Name = "B1",
                Tier = "Basic"
            }
        });

        //
        // Scenario 1: deploying an image from Docker Hub.
        // The example uses a HelloWorld application written in Go.
        // Image: https://hub.docker.com/r/microsoft/azure-appservices-go-quickstart/
        //
        var imageInDockerHub = "microsoft/azure-appservices-go-quickstart";

        var helloApp = new WebApp("hello-app", new WebAppArgs
        {
            ResourceGroupName = resourceGroup.Name,
            ServerFarmId      = plan.Id,
            SiteConfig        = new SiteConfigArgs
            {
                AppSettings = new[]
                {
                    new NameValuePairArgs
                    {
                        Name  = "WEBSITES_ENABLE_APP_SERVICE_STORAGE",
                        Value = "false"
                    }
                },
                AlwaysOn       = true,
                LinuxFxVersion = $"DOCKER|{imageInDockerHub}"
            },
            HttpsOnly = true
        });

        this.HelloEndpoint = Output.Format($"https://{helloApp.DefaultHostName}/hello");

        //
        // Scenario 2: deploying a custom image from Azure Container Registry.
        //
        var customImage = "node-app";

        var registry = new Registry("myregistry", new RegistryArgs
        {
            ResourceGroupName = resourceGroup.Name,
            Sku = new SkuArgs {
                Name = "Basic"
            },
            AdminUserEnabled = true
        });

        var credentials = Output.Tuple(resourceGroup.Name, registry.Name).Apply(values =>
                                                                                ListRegistryCredentials.InvokeAsync(new ListRegistryCredentialsArgs
        {
            ResourceGroupName = values.Item1,
            RegistryName      = values.Item2
        }));
        var adminUsername = credentials.Apply(c => c.Username ?? "");
        var adminPassword = credentials.Apply(c => Output.CreateSecret(c.Passwords.First().Value ?? ""));

        var myImage = new Image(customImage, new ImageArgs
        {
            ImageName = Output.Format($"{registry.LoginServer}/{customImage}:v1.0.0"),
            Build     = new DockerBuild {
                Context = $"./{customImage}"
            },
            Registry = new ImageRegistry
            {
                Server   = registry.LoginServer,
                Username = adminUsername,
                Password = adminPassword
            },
        });

        var getStartedApp = new WebApp("get-started", new WebAppArgs
        {
            ResourceGroupName = resourceGroup.Name,
            ServerFarmId      = plan.Id,
            SiteConfig        = new SiteConfigArgs
            {
                AppSettings = new[]
                {
                    new NameValuePairArgs
                    {
                        Name  = "WEBSITES_ENABLE_APP_SERVICE_STORAGE",
                        Value = "false"
                    },
                    new NameValuePairArgs
                    {
                        Name  = "DOCKER_REGISTRY_SERVER_URL",
                        Value = Output.Format($"https://{registry.LoginServer}")
                    },
                    new NameValuePairArgs
                    {
                        Name  = "DOCKER_REGISTRY_SERVER_USERNAME",
                        Value = adminUsername
                    },
                    new NameValuePairArgs
                    {
                        Name  = "DOCKER_REGISTRY_SERVER_PASSWORD",
                        Value = adminPassword
                    },
                    new NameValuePairArgs
                    {
                        Name  = "WEBSITES_PORT",
                        Value = "80" // Our custom image exposes port 80. Adjust for your app as needed.
                    }
                },
                AlwaysOn       = true,
                LinuxFxVersion = Output.Format($"DOCKER|{myImage.ImageName}")
            },
            HttpsOnly = true
        });

        this.GetStartedEndpoint = Output.Format($"https://{getStartedApp.DefaultHostName}");
    }
Пример #24
0
    public AppServiceStack()
    {
        var resourceGroup = new ResourceGroup("appservice-rg", new ResourceGroupArgs
        {
            ResourceGroupName = "appservice-rg",
            Location          = "westus2",
        });

        var storageAccount = new StorageAccount("sa", new StorageAccountArgs
        {
            AccountName       = "appservicesa",
            ResourceGroupName = resourceGroup.Name,
            Kind = "StorageV2",
            Sku  = new SkuArgs
            {
                Name = SkuName.Standard_LRS,
            },
        });

        var appServicePlan = new AppServicePlan("asp", new AppServicePlanArgs
        {
            Name              = "asp",
            Location          = resourceGroup.Location,
            ResourceGroupName = resourceGroup.Name,
            Kind              = "App",
            Sku = new SkuDescriptionArgs
            {
                Tier = "Basic",
                Name = "B1",
            },
        });

        var container = new BlobContainer("zips", new BlobContainerArgs
        {
            AccountName       = storageAccount.Name,
            ContainerName     = "zips",
            PublicAccess      = PublicAccess.None,
            ResourceGroupName = resourceGroup.Name,
        });

        var blob = new Blob("zip", new BlobArgs
        {
            BlobName          = "appservice-blob",
            ResourceGroupName = resourceGroup.Name,
            AccountName       = storageAccount.Name,
            ContainerName     = container.Name,
            Type   = BlobType.Block,
            Source = new FileArchive("wwwroot"),
        });

        var codeBlobUrl = signedBlobReadUrl(blob, container, storageAccount, resourceGroup);

        this.SignedURL = codeBlobUrl;

        var appInsights = new Component("appInsights", new ComponentArgs
        {
            Location          = resourceGroup.Location,
            ApplicationType   = "web",
            Kind              = "web",
            ResourceGroupName = resourceGroup.Name,
            ResourceName      = "appInsights",
        });

        var config    = new Config();
        var username  = config.Get("sqlAdmin") ?? "pulumi";
        var password  = config.RequireSecret("sqlPassword");
        var sqlServer = new Server("sqlserver", new ServerArgs
        {
            ServerName                 = "insightssqlsrv1",
            Location                   = resourceGroup.Location,
            ResourceGroupName          = resourceGroup.Name,
            AdministratorLogin         = username,
            AdministratorLoginPassword = password,
            Version = "12.0",
        });

        var database = new Database("db", new DatabaseArgs
        {
            DatabaseName                  = "db",
            Location                      = resourceGroup.Location,
            ResourceGroupName             = resourceGroup.Name,
            ServerName                    = sqlServer.Name,
            RequestedServiceObjectiveName = ServiceObjectiveName.S0,
        });

        var app = new WebApp("app", new WebAppArgs
        {
            ResourceGroupName = resourceGroup.Name,
            Location          = resourceGroup.Location,
            Name         = "appserver-app",
            ServerFarmId = appServicePlan.Id,
            SiteConfig   = new SiteConfigArgs
            {
                AppSettings =
                {
                    new NameValuePairArgs {
                        Name  = "WEBSITE_RUN_FROM_PACKAGE",
                        Value = codeBlobUrl,
                    },
                    new NameValuePairArgs {
                        Name  = "APPINSIGHTS_INSTRUMENTATIONKEY",
                        Value = appInsights.InstrumentationKey
                    },
                    new NameValuePairArgs {
                        Name  = "APPLICATIONINSIGHTS_CONNECTION_STRING",
                        Value = appInsights.InstrumentationKey.Apply(key => $"InstrumentationKey={key}"),
                    },
                    new NameValuePairArgs {
                        Name  = "ApplicationInsightsAgent_EXTENSION_VERSION",
                        Value = "~2",
                    },
                },
Пример #25
0
    public MyStack()
    {
        Config config = new Config();

        // Create an Azure Resource Group
        var resourceGroup = new ResourceGroup("resourceGroup", new ResourceGroupArgs
        {
            ResourceGroupName = "pulumidemo",
            Location          = "AustraliaSouthEast"
        });

        // Create a Cosmos DB Database
        string cosmosAccountName = "mypulumidemo-dev";
        var    cosmosAccount     = new DatabaseAccount(cosmosAccountName, new DatabaseAccountArgs()
        {
            AccountName       = cosmosAccountName,
            ResourceGroupName = resourceGroup.Name,
            Location          = resourceGroup.Location,
            ConsistencyPolicy = new ConsistencyPolicyArgs()
            {
                DefaultConsistencyLevel = "Session"
            },
            DatabaseAccountOfferType      = "Standard",
            EnableFreeTier                = false,
            EnableMultipleWriteLocations  = false,
            IsVirtualNetworkFilterEnabled = false,
            Locations =
            {
                new LocationArgs
                {
                    FailoverPriority = 0,
                    IsZoneRedundant  = false,
                    LocationName     = resourceGroup.Location,
                }
            }
        });

        // Export the CosmosDb Connection String
        this.CosmosDatabaseConnectionString = Output
                                              .Tuple(resourceGroup.Name, cosmosAccount.Name)
                                              .Apply(names => Output.CreateSecret(GetCosmosDatabaseConnectionString(names.Item1, names.Item2)));

        // set with > pulumi config set myCosmosDb.autoScaleThroughput 4000
        int autoScaleThroughput = config.RequireInt32("myCosmosDb.autoScaleThroughput");

        string cosmosDatabaseName = "myCosmosDatabase";
        var    cosmosSqlDatabase  = new SqlResourceSqlDatabase(cosmosDatabaseName, new SqlResourceSqlDatabaseArgs()
        {
            DatabaseName      = cosmosDatabaseName,
            AccountName       = cosmosAccount.Name,
            ResourceGroupName = resourceGroup.Name,
            Location          = resourceGroup.Location,
            Resource          = new SqlDatabaseResourceArgs()
            {
                Id = cosmosDatabaseName
            },
            Options = new CreateUpdateOptionsArgs()
            {
                AutoscaleSettings = new AutoscaleSettingsArgs()
                {
                    MaxThroughput = autoScaleThroughput
                }
            }
        });

        string rulesContainerName = "rules";
        var    rulesContainer     = new SqlResourceSqlContainer(rulesContainerName, new SqlResourceSqlContainerArgs
        {
            AccountName       = cosmosAccount.Name,
            ContainerName     = rulesContainerName,
            DatabaseName      = cosmosSqlDatabase.Name,
            ResourceGroupName = resourceGroup.Name,
            Location          = resourceGroup.Location,
            Options           = new CreateUpdateOptionsArgs()
            {
            },
            Resource = new SqlContainerResourceArgs
            {
                Id             = rulesContainerName,
                IndexingPolicy = new IndexingPolicyArgs
                {
                    Automatic    = true,
                    IndexingMode = "Consistent",
                },
                PartitionKey = new ContainerPartitionKeyArgs
                {
                    Kind  = "Hash",
                    Paths =
                    {
                        "/id",
                    },
                }
            }
        });

        // Create an AppService Plan (Web Server)
        string appServicePlanName = "myRulesServer";
        var    appServicePlan     = new AppServicePlan(appServicePlanName, new AppServicePlanArgs
        {
            Name              = appServicePlanName,
            Location          = resourceGroup.Location,
            ResourceGroupName = resourceGroup.Name,
            Kind              = "app",
            Sku = new SkuDescriptionArgs
            {
                Capacity = 1,
                Family   = "P",
                Name     = "P1",
                Size     = "P1",
                Tier     = "Premium",
            }
        });

        // Create a WebApp
        string appServiceName = "myRulesApp";
        var    appService     = new WebApp(appServiceName, new WebAppArgs
        {
            Name              = appServiceName,
            Location          = resourceGroup.Location,
            ResourceGroupName = resourceGroup.Name,
            ServerFarmId      = appServicePlan.Id,
            SiteConfig        = new SiteConfigArgs()
            {
                AlwaysOn    = true,
                AppSettings = new InputList <NameValuePairArgs>()
                {
                },
                ConnectionStrings = new InputList <ConnStringInfoArgs>()
                {
                    new ConnStringInfoArgs()
                    {
                        Name             = "RulesDatabase",
                        Type             = "Custom",
                        ConnectionString = Output
                                           .Tuple(resourceGroup.Name, cosmosAccount.Name)
                                           .Apply(names => Output.Create(GetCosmosDatabaseConnectionString(names.Item1, names.Item2)))
                    }
                }
            }
        });
    }
    public FunctionApp(string name, FunctionAppArgs args, ComponentResourceOptions?options = null)
        : base("infra:functionapp", name, options)
    {
        var opts = new CustomResourceOptions {
            Parent = this
        };

        var appStorage = new StorageAccount(name.Replace("-", ""), new StorageAccountArgs
        {
            ResourceGroupName = args.ResourceGroupName,
            Sku = new SkuArgs
            {
                Name = SkuName.Standard_LRS,
            },
            Kind = Pulumi.AzureNative.Storage.Kind.StorageV2,
        });

        var appServicePlan = new AppServicePlan(name, new AppServicePlanArgs
        {
            ResourceGroupName = args.ResourceGroupName,
            Location          = args.Location,
            Kind = "FunctionApp",
            Sku  = new SkuDescriptionArgs
            {
                Tier = "Dynamic",
                Name = "Y1"
            }
        }, opts);

        var container = new BlobContainer("code-container", new BlobContainerArgs
        {
            AccountName       = appStorage.Name,
            PublicAccess      = PublicAccess.None,
            ResourceGroupName = args.ResourceGroupName,
        });

        var blob = new Blob($"zip-{DateTime.UtcNow:ddMMyyyyhhmmss}", new BlobArgs
        {
            AccountName       = appStorage.Name,
            ContainerName     = container.Name,
            ResourceGroupName = args.ResourceGroupName,
            Type   = BlobType.Block,
            Source = new FileArchive("../publish")
        });

        var appInsights = new Component("appInsights", new ComponentArgs
        {
            ApplicationType   = ApplicationType.Web,
            Kind              = "web",
            ResourceGroupName = args.ResourceGroupName,
        });

        var codeBlobUrl = SignedBlobReadUrl(blob, container, appStorage, args.ResourceGroupName);

        var accountKeys = Output.Tuple(args.ResourceGroupName, appStorage.Name)
                          .Apply(p => ListStorageAccountKeys.InvokeAsync(new ListStorageAccountKeysArgs
        {
            ResourceGroupName = p.Item1,
            AccountName       = p.Item2
        }));

        var storageConnectionString =
            Output.Format(
                $"DefaultEndpointsProtocol=https;AccountName={appStorage.Name};AccountKey={accountKeys.Apply(a => a.Keys[0].Value)}");

        var app = new WebApp(name, new WebAppArgs
        {
            Kind = "FunctionApp",
            ResourceGroupName = args.ResourceGroupName,
            ServerFarmId      = appServicePlan.Id,
            SiteConfig        = new SiteConfigArgs
            {
                AppSettings = new[]
                {
                    new NameValuePairArgs
                    {
                        Name  = "APPLICATIONINSIGHTS_CONNECTION_STRING",
                        Value = Output.Format($"InstrumentationKey={appInsights.InstrumentationKey}"),
                    },
                    new NameValuePairArgs
                    {
                        Name  = "FUNCTIONS_EXTENSION_VERSION",
                        Value = "~3"
                    },
                    new NameValuePairArgs
                    {
                        Name  = "FUNCTIONS_WORKER_RUNTIME",
                        Value = "dotnet-isolated"
                    },
                    new NameValuePairArgs {
                        Name  = "WEBSITE_RUN_FROM_PACKAGE",
                        Value = codeBlobUrl,
                    },
                    new NameValuePairArgs
                    {
                        Name  = "AzureWebJobsStorage",
                        Value = GetConnectionString(args.ResourceGroupName, appStorage.Name)
                    }
                }
            }
        });

        var slotConfigNames = new WebAppSlotConfigurationNames(name, new WebAppSlotConfigurationNamesArgs {
            Name = app.Name,
            ResourceGroupName = args.ResourceGroupName,
            AppSettingNames   = { "FUNCTIONS_WORKER_RUNTIME", "FUNCTIONS_EXTENSION_VERSION" }
        });

        var stagingSlot = new WebAppSlot($"{name}-slot", new WebAppSlotArgs()
        {
            Name = app.Name,
            Slot = "staging",
            ResourceGroupName = args.ResourceGroupName,
            SiteConfig        = new SiteConfigArgs
            {
                AppSettings = new[]
                {
                    new NameValuePairArgs
                    {
                        Name  = "WEBSITE_ADD_SITENAME_BINDINGS_IN_APPHOST_CONFIG",
                        Value = "1"
                    },
                    new NameValuePairArgs
                    {
                        Name  = "WEBSITE_SWAP_WARMUP_PING_PATH",
                        Value = "/helloworld"
                    }
                }
            },
        });

        this.AppName         = app.Name;
        this.AppId           = app.Id;
        this.DefaultHostname = app.DefaultHostName;
    }
Пример #27
0
    public FunctionsStack()
    {
        var resourceGroup = new ResourceGroup("functions-rg");

        var storageAccount = new StorageAccount("sa", new StorageAccountArgs
        {
            ResourceGroupName = resourceGroup.Name,
            Sku = new SkuArgs
            {
                Name = SkuName.Standard_LRS,
            },
            Kind = Pulumi.AzureNative.Storage.Kind.StorageV2,
        });

        var appServicePlan = new AppServicePlan("functions-linux-asp", new AppServicePlanArgs
        {
            ResourceGroupName = resourceGroup.Name,

            // Run on Linux
            Kind = "Linux",

            // Consumption plan SKU
            Sku = new SkuDescriptionArgs
            {
                Tier = "Dynamic",
                Name = "Y1"
            },

            // For Linux, you need to change the plan to have Reserved = true property.
            Reserved = true
        });

        var container = new BlobContainer("zips-container", new BlobContainerArgs
        {
            AccountName       = storageAccount.Name,
            PublicAccess      = PublicAccess.None,
            ResourceGroupName = resourceGroup.Name,
        });

        var blob = new Blob("zip", new BlobArgs
        {
            AccountName       = storageAccount.Name,
            ContainerName     = container.Name,
            ResourceGroupName = resourceGroup.Name,
            Type   = BlobType.Block,
            Source = new FileArchive("./functions")
        });

        var codeBlobUrl = SignedBlobReadUrl(blob, container, storageAccount, resourceGroup);

        // Application insights
        var appInsights = new Component("appInsights", new ComponentArgs
        {
            ApplicationType   = ApplicationType.Web,
            Kind              = "web",
            ResourceGroupName = resourceGroup.Name,
        });


        var app = new WebApp("app", new WebAppArgs
        {
            Kind = "FunctionApp",
            ResourceGroupName = resourceGroup.Name,
            ServerFarmId      = appServicePlan.Id,
            SiteConfig        = new SiteConfigArgs
            {
                AppSettings = new[]
                {
                    new NameValuePairArgs {
                        Name  = "runtime",
                        Value = "python",
                    },
                    new NameValuePairArgs {
                        Name  = "FUNCTIONS_WORKER_RUNTIME",
                        Value = "python",
                    },
                    new NameValuePairArgs {
                        Name  = "WEBSITE_RUN_FROM_PACKAGE",
                        Value = codeBlobUrl,
                    },
                    new NameValuePairArgs {
                        Name  = "APPLICATIONINSIGHTS_CONNECTION_STRING",
                        Value = Output.Format($"InstrumentationKey={appInsights.InstrumentationKey}"),
                    },
                },
            },
        });

        this.Endpoint = Output.Format($"https://{app.DefaultHostName}/api/Hello?name=Pulumi");
    }
Пример #28
0
        public AppServicePlan CreateOrUpdateAppServicePlan(string resourceGroupName, string appServicePlanName, AppServicePlan appServicePlan, string aseName = null, string aseResourceGroupName = null)
        {
            if (!string.IsNullOrEmpty(aseName) &&
                !string.IsNullOrEmpty(aseResourceGroupName))
            {
                appServicePlan.HostingEnvironmentProfile = new HostingEnvironmentProfile(
                    id: CmdletHelpers.GetApplicationServiceEnvironmentResourceId(WrappedWebsitesClient.SubscriptionId, aseResourceGroupName, aseName),
                    name: aseName,
                    type: CmdletHelpers.ApplicationServiceEnvironmentResourcesName);
            }

            return(WrappedWebsitesClient.AppServicePlans().CreateOrUpdate(resourceGroupName, appServicePlanName, appServicePlan));
        }
Пример #29
0
    public AzureStack()
    {
        var stack = Pulumi.Deployment.Instance.StackName.ToLower(); // Test or Prod

        var resourceGroup = new ResourceGroup($"fplbot-{stack}");

        var storageAccount = new StorageAccount($"stfplbot{stack}", new StorageAccountArgs
        {
            ResourceGroupName = resourceGroup.Name,
            Sku = new Pulumi.AzureNative.Storage.Inputs.SkuArgs
            {
                Name = Pulumi.AzureNative.Storage.SkuName.Standard_LRS
            },
            Kind = Pulumi.AzureNative.Storage.Kind.StorageV2,
        });

        var appServicePlan = new AppServicePlan($"pl-{stack}-windows-asp", new AppServicePlanArgs
        {
            ResourceGroupName = resourceGroup.Name,
            Kind = "Windows",
            Sku  = new SkuDescriptionArgs
            {
                Tier = "Dynamic",
                Name = "Y1"
            }
        });

        var appInsights = new Component($"ai-{stack}-fplbot", new ComponentArgs
        {
            ApplicationType   = ApplicationType.Web,
            Kind              = "web",
            ResourceGroupName = resourceGroup.Name,
        });

        var storageAccountConnectionStr = GetConnectionString(resourceGroup.Name, storageAccount.Name);

        var config = new Config();

        var app = new WebApp($"fn-{stack}-fplbot", new WebAppArgs
        {
            Kind = "functionapp",
            ResourceGroupName = resourceGroup.Name,
            ServerFarmId      = appServicePlan.Id,
            SiteConfig        = new SiteConfigArgs
            {
                AppSettings = new[]
                {
                    new NameValuePairArgs
                    {
                        Name  = "FUNCTIONS_WORKER_RUNTIME",
                        Value = "dotnet",
                    },
                    new NameValuePairArgs
                    {
                        Name  = "FUNCTIONS_EXTENSION_VERSION",
                        Value = "~3",
                    },
                    new NameValuePairArgs
                    {
                        Name  = "WEBSITE_RUN_FROM_PACKAGE",
                        Value = "1",
                    },
                    new NameValuePairArgs
                    {
                        Name  = "APPLICATIONINSIGHTS_CONNECTION_STRING",
                        Value = Output.Format($"InstrumentationKey={appInsights.InstrumentationKey}"),
                    },
                    new NameValuePairArgs
                    {
                        Name  = "AzureWebJobsStorage",
                        Value = storageAccountConnectionStr
                    },
                    new NameValuePairArgs
                    {
                        Name  = "WEBSITE_CONTENTAZUREFILECONNECTIONSTRING",
                        Value = storageAccountConnectionStr
                    },
                    new NameValuePairArgs
                    {
                        Name  = "WEBSITE_CONTENTSHARE",
                        Value = $"fn-{stack}-fplbot"
                    },
                    new NameValuePairArgs
                    {
                        Name  = "DOTNET_ENVIRONMENT",
                        Value = stack == "Prod" ? "Production" : "Test"
                    },
                    new NameValuePairArgs
                    {
                        Name  = "NSB_LICENSE",
                        Value = config.RequireSecret("NSB_LICENSE")
                    },
                    new NameValuePairArgs
                    {
                        Name  = "QueueName",
                        Value = stack == "Prod" ? "fplbot.functions.production" : "fplbot.functions.test"
                    },
                    new NameValuePairArgs
                    {
                        Name  = "ASB_CONNECTIONSTRING",
                        Value = config.RequireSecret("ASB_CONNECTIONSTRING")
                    },
                    new NameValuePairArgs
                    {
                        Name  = "SlackWebHookUrl",
                        Value = config.RequireSecret("SlackWebHookUrl")
                    },
                    new NameValuePairArgs
                    {
                        Name  = "AZURE_STORAGE_CONNECTIONSTRING",
                        Value = storageAccountConnectionStr
                    }
                }
            },
        });

        Endpoint          = Output.Format($"https://{app.DefaultHostName}/api/");
        ResourceGroupName = Output.Format($"{resourceGroup.Name}");
        FunctionName      = Output.Format($"{app.Name}");
    }
Пример #30
0
    public AppStack()
    {
        var config = new Config();

        var resourceGroup = new ResourceGroup("rotatesecretoneset-rg");

        var sqlAdminLogin    = config.Get("sqlAdminLogin") ?? "sqlAdmin";
        var sqlAdminPassword = new RandomUuid("sqlPassword").Result;
        var sqlServer        = new Server("sqlServer", new ServerArgs
        {
            AdministratorLogin         = sqlAdminLogin,
            AdministratorLoginPassword = sqlAdminPassword,
            ResourceGroupName          = resourceGroup.Name,
            Version = "12.0",
        });

        new FirewallRule("AllowAllWindowsAzureIps",
                         new FirewallRuleArgs
        {
            ServerName        = sqlServer.Name,
            ResourceGroupName = resourceGroup.Name,
            StartIpAddress    = "0.0.0.0",
            EndIpAddress      = "0.0.0.0",
        });

        var clientConfig = Output.Create(GetClientConfig.InvokeAsync());
        var tenantId     = clientConfig.Apply(c => c.TenantId);

        var storageAccount = new StorageAccount("storageaccount", new StorageAccountArgs
        {
            Kind = "Storage",
            ResourceGroupName = resourceGroup.Name,
            Sku = new Storage.Inputs.SkuArgs
            {
                Name = "Standard_LRS"
            },
        });

        var appInsights = new Component("appInsights", new ComponentArgs
        {
            RequestSource     = "IbizaWebAppExtensionCreate",
            ResourceGroupName = resourceGroup.Name,
            ApplicationType   = "web",
            Kind = "web",
            Tags =
            {
                //{ "[concat('hidden-link:', resourceId('Microsoft.Web/sites', parameters('functionAppName')))]", "Resource" },
            },
        });

        var secretName = config.Get("secretName") ?? "sqlPassword";
        var appService = new AppServicePlan("functionApp-appService", new AppServicePlanArgs
        {
            ResourceGroupName = resourceGroup.Name,
            Sku = new SkuDescriptionArgs
            {
                Name = "Y1",
                Tier = "Dynamic",
            },
        });

        var storageKey = Output.Tuple(resourceGroup.Name, storageAccount.Name).Apply(v =>
        {
            var task = ListStorageAccountKeys.InvokeAsync(new ListStorageAccountKeysArgs {
                AccountName = v.Item2, ResourceGroupName = v.Item1
            });
            return(Output.Create(task).Apply(t => t.Keys[0].Value));
        });

        var functionApp = new WebApp("functionApp", new WebAppArgs
        {
            Kind = "functionapp",
            ResourceGroupName = resourceGroup.Name,
            ServerFarmId      = appService.Id,
            Identity          = new ManagedServiceIdentityArgs {
                Type = ManagedServiceIdentityType.SystemAssigned
            },
            SiteConfig = new SiteConfigArgs
            {
                AppSettings =
                {
                    new NameValuePairArgs
                    {
                        Name  = "AzureWebJobsStorage",
                        Value = Output.Format($"DefaultEndpointsProtocol=https;AccountName={storageAccount.Name};AccountKey={storageKey}"),
                    },
                    new NameValuePairArgs
                    {
                        Name  = "FUNCTIONS_EXTENSION_VERSION",
                        Value = "~3",
                    },
                    new NameValuePairArgs
                    {
                        Name  = "FUNCTIONS_WORKER_RUNTIME",
                        Value = "dotnet",
                    },
                    new NameValuePairArgs
                    {
                        Name  = "WEBSITE_CONTENTAZUREFILECONNECTIONSTRING",
                        Value = Output.Format($"DefaultEndpointsProtocol=https;AccountName={storageAccount.Name};EndpointSuffix=core.windows.net;AccountKey={storageKey}"),
                    },
                    new NameValuePairArgs
                    {
                        Name  = "WEBSITE_NODE_DEFAULT_VERSION",
                        Value = "~10",
                    },
                    new NameValuePairArgs
                    {
                        Name  = "APPINSIGHTS_INSTRUMENTATIONKEY",
                        Value = appInsights.InstrumentationKey,
                    },
                },
            },
        });

        var functionAppSourceControl = new WebAppSourceControl("functionApp-sourceControl",
                                                               new WebAppSourceControlArgs
        {
            Name = functionApp.Name,
            IsManualIntegration = true,
            Branch            = "main",
            RepoUrl           = config.Get("functionAppRepoURL") ?? "https://github.com/Azure-Samples/KeyVault-Rotation-SQLPassword-Csharp.git",
            ResourceGroupName = resourceGroup.Name,
        });

        var webAppAppService = new AppServicePlan("webApp-appService", new AppServicePlanArgs
        {
            ResourceGroupName = resourceGroup.Name,
            Sku = new SkuDescriptionArgs
            {
                Name = "F1",
            },
        });

        var webApp = new WebApp("webApp", new WebAppArgs
        {
            Kind = "app",
            ResourceGroupName = resourceGroup.Name,
            ServerFarmId      = webAppAppService.Id,
            Identity          = new ManagedServiceIdentityArgs {
                Type = ManagedServiceIdentityType.SystemAssigned
            },
        });

        var keyVault = new Vault("keyVault", new VaultArgs
        {
            Properties = new VaultPropertiesArgs
            {
                AccessPolicies =
                {
                    new AccessPolicyEntryArgs
                    {
                        TenantId    = tenantId,
                        ObjectId    = functionApp.Identity.Apply(i => i !.PrincipalId),
                        Permissions = new PermissionsArgs
                        {
                            Secrets ={ "get",               "list", "set" },
                        },
                    },