static Task <int> Main() => Deployment.RunAsync(async() => { // Fetch the Docker Hub auth info from config. var config = new Pulumi.Config(); var username = config.Require("dockerUsername"); var password = config.RequireSecret("dockerPassword"); // Populate the registry info (creds and endpoint). var imageName = $"{username}/myapp"; var registryInfo = new ImageRegistry { Server = "docker.io", Username = username, Password = password, }; // Build and publish the app image. var image = new Image("my-image", new ImageArgs { ImageName = username + "/myapp", Build = new DockerBuild { Context = "app" }, Registry = registryInfo, }); // Export the resulting image name. return(new Dictionary <string, object> { { "imageName", image.ImageName }, }); });
public AzureStack() { var config = new Pulumi.Config(); var deployTo = config.Require("DeployTo"); // Create an Azure Resource Group var resourceGroupName = $"rg-ne-rpc-demo-{deployTo}"; var resourceGroup = new ResourceGroup( resourceGroupName, new ResourceGroupArgs { Name = resourceGroupName }); // Create an Azure Storage Account var storageAccount = new Account($"nerpcdemo{deployTo}", new AccountArgs { ResourceGroupName = resourceGroup.Name, AccountReplicationType = "LRS", AccountTier = "Standard" }); // Export the connection string for the storage account this.StorageAccountName = storageAccount.Name; }
public MyStack() { var config = new Pulumi.Config(); var siteDir = config.Get("siteDir"); var bucket = new Aws.S3.Bucket("my-bucket", new BucketArgs { Website = new BucketWebsiteArgs { IndexDocument = "index.html", } }); this.BucketName = bucket.BucketName; this.WebsiteEndpoint = bucket.WebsiteEndpoint; foreach (var file in Directory.EnumerateFiles(siteDir)) { var name = Path.GetFileName(file); var bucketObject = new Aws.S3.BucketObject(name, new BucketObjectArgs { Bucket = bucket.BucketName, Source = new FileAsset(Path.Combine(siteDir, Path.GetFileName(file))), Acl = "public-read", ContentType = "text/html", }); } }
public MyStack() { var config = new Pulumi.Config(); var siteDir = config.Get("siteDir"); var bucket = new Aws.S3.Bucket("my-bucket", new BucketArgs { Website = new BucketWebsiteArgs { IndexDocument = "index.html", } }); this.BucketName = bucket.BucketName; this.WebsiteEndpoint = bucket.WebsiteEndpoint; var bucketFile = Path.Combine(siteDir, "index.html"); var bucketObject = new Aws.S3.BucketObject("index.html", new BucketObjectArgs { Bucket = bucket.BucketName, Source = new FileAsset(bucketFile), Acl = "public-read", ContentType = "text/html", }); }
static (Output <string> username, Output <string> password) GetConfig() { var config = new Pulumi.Config(); var username = config.RequireSecret("sqlUsername"); var password = config.RequireSecret("sqlPassword"); return(username, password); }
public gcpIamCustomRole() { gcpConfig = new Config("gcp"); this.roleId = gcpConfig.Require("RoleId"); this.roleTitle = gcpConfig.Require("RoleTitle"); this.rolePermissions = gcpConfig.GetObject <string[]>("RolePermissions"); this.roleDescription = $"{gcpConfig.Require("RoleDescription")}"; ProvisionRole(); }
public ActiveDirectoryResource(Output <string> currentUserObjectId) { var config = new Config("azureactivedirectory"); ClientId = config.Require("clientid"); ClientSecret = config.GetSecret("clientsecret"); Domain = config.Require("domain"); TenantId = config.Require("tenantId"); _currentUserObjectId = currentUserObjectId; }
public CreateRoleStack() { var config = new Pulumi.Config(); var unprivilegedUsername = config.Require("unprivilegedUsername"); var unprivilegedUser = new Iam.User("unprivilegedUser", new Iam.UserArgs { Name = unprivilegedUsername, }); var unprivilegedUserCreds = new Iam.AccessKey("unprivileged-user-key", new Iam.AccessKeyArgs { User = unprivilegedUser.Name, }, // additional_secret_outputs specify properties that must be encrypted as secrets // https://www.pulumi.com/docs/intro/concepts/programming-model/#additionalsecretoutputs new CustomResourceOptions { AdditionalSecretOutputs = { "secret" } }); var tempPolicy = unprivilegedUser.Arn.Apply((string arn) => { AssumeRolePolicyArgs policyArgs = new AssumeRolePolicyArgs(arn); return(JsonSerializer.Serialize <AssumeRolePolicyArgs>(policyArgs)); }); var allowS3ManagementRole = new Iam.Role("allow-s3-management", new Iam.RoleArgs { Description = "Allow management of S3 buckets", AssumeRolePolicy = tempPolicy }); var rolePolicy = new Iam.RolePolicy("allow-s3-management-policy", new Iam.RolePolicyArgs { Role = allowS3ManagementRole.Name, Policy = @"{ ""Version"": ""2012-10-17"", ""Statement"": [{ ""Effect"": ""Allow"", ""Action"": ""s3:*"", ""Resource"": ""*"", ""Sid"": ""allowS3Access"" }] }" }, new CustomResourceOptions { Parent = allowS3ManagementRole } ); this.roleArn = allowS3ManagementRole.Arn; this.accessKeyId = unprivilegedUserCreds.Id; this.secretAccessKey = unprivilegedUserCreds.Secret; }
public AppStack() { var config = new Pulumi.Config(); var redisPort = 6379; // getting refererence from AKS Stack var cluster = new StackReference($"gutek/aks-infra/{Deployment.Instance.StackName}"); var kubeConfig = cluster.RequireOutput("KubeConfig").Apply(v => v.ToString()); var provider = new Provider("k8s", new ProviderArgs { KubeConfig = kubeConfig ! });
public MyStack() { var config = new Pulumi.Config(); var location = config.Get("location") ?? "WestUS"; var resourceGroup = new ResourceGroup("resourceGroup", new ResourceGroupArgs { ResourceGroupName = "aci-rg", Location = location }); var imageName = "mcr.microsoft.com/azuredocs/aci-helloworld"; var containerGroup = new ContainerGroup("containerGroup", new ContainerGroupArgs { ResourceGroupName = resourceGroup.Name, Location = resourceGroup.Location, ContainerGroupName = "helloworld", OsType = "Linux", Containers = { new ContainerArgs { Name = "acilinuxpublicipcontainergroup", Image = imageName, Ports ={ new ContainerPortArgs { Port = 80 } }, Resources = new ResourceRequirementsArgs { Requests = new ResourceRequestsArgs { Cpu = 1.0, MemoryInGB = 1.5, } } } }, IpAddress = new IpAddressArgs { Ports = { new PortArgs { Port = 80, Protocol = "Tcp", } }, Type = "Public" }, RestartPolicy = "always" }); this.ContainerIPv4Address = containerGroup.IpAddress.Apply(ip => ip !.Ip); }
public MyStack() { var config = new Pulumi.Config(); var zoneId = config.Require("zone_id"); var foobar = new Cloudflare.Record("foobar", new Cloudflare.RecordArgs { Name = "my-record-csharp", ZoneId = zoneId, Value = "162.168.0.14", Type = "A", Ttl = 3600, }); }
public KanbernetesStack() { var config = new Config(); var azureResources = CreateBaseAzureInfrastructure(config); var clusterOptions = new ClusterOptions { Domain = config.Require("domain"), Namespace = config.Require("kubernetes-namespace"), CertificateIssuerAcmeEmail = config.Require("certmanager-acme-email") }; ConfigureKubernetesCluster(azureResources, clusterOptions); }
// Initialize all of the config variables. static Config() { var config = new Pulumi.Config(); AvailabilityZones = config.GetObject <string[]>("availabilityZones"); NumberOfAvailabilityZones = config.GetInt32("numberOfAvailabilityZones") ?? 2; CreatePrivateSubnets = config.GetBoolean("createPrivateSubnets") ?? true; CreateProtectedSubnets = config.GetBoolean("createProtectedSubnets") ?? false; VpcCidr = config.Get("vpcCidr") ?? "10.0.0.0/16"; VpcTenancy = config.Get("vpcTenancy") ?? "default"; PublicSubnetCidrs = config.GetObject <string[]>("publicSubnetCidrs"); PublicSubnetTags = config.GetObject <ImmutableDictionary <string, object>[]>("publicSubnetTags"); PrivateSubnetCidrs = config.GetObject <string[]>("privateSubnetCidrs"); PrivateSubnetTags = config.GetObject <ImmutableDictionary <string, object>[]>("privateSubnetTags"); ProtectedSubnetCidrs = config.GetObject <string[]>("protectedSubnetCidrs"); ProtectedSubnetTags = config.GetObject <ImmutableDictionary <string, object>[]>("protectedSubnetTags"); }
public AssumeRoleStack() { var awsConfig = new Pulumi.Config("aws"); var config = new Pulumi.Config(); var roleToAssumeARN = config.Require("roleToAssumeARN"); var provider = new Aws.Provider("privileged", new Aws.ProviderArgs { AssumeRole = new Aws.Inputs.ProviderAssumeRoleArgs { RoleArn = roleToAssumeARN, SessionName = "PulumiSession", ExternalId = "PulumiApplication" }, Region = awsConfig.Require("region"), }); var bucket = new Aws.S3.Bucket("myBucket", null, new CustomResourceOptions { Provider = provider }); }
public PetDoctorStack() { var config = new Config(); var azureResources = CreateBaseAzureInfrastructure(config); var clusterOptions = new PetDoctorClusterOptions { Domain = config.Require("domain"), Namespace = config.Require("kubernetes-namespace"), CertificateIssuerAcmeEmail = config.Require("certmanager-acme-email"), AppointmentApi = new ReplicaSetConfiguration { AadPodIdentityBindingName = "appointments-api-pod-identity-binding", AadPodIdentityName = "appointments-api-pod-identity", AadPodIdentitySelector = "appointments-api", DeploymentName = "appointments-api", IngressName = "appointments-api-ingress", ServiceName = "appointments-api-svc", Image = azureResources.Registry.LoginServer.Apply(loginServer => $"{loginServer}/pet-doctor/appointments/api:{config.Require("versions-appointments-api")}"), Port = 80, ReplicaCount = 2, Cpu = new ResourceLimit { Request = "25m", Limit = "50m" }, Memory = new ResourceLimit { Request = "250Mi", Limit = "400Mi" }, SecretName = "appointments-api-secrets" } }; ConfigureKubernetesCluster(azureResources, clusterOptions); var appointmentApiAzureResources = CreateAppointmentApiAzureResources(azureResources, config, clusterOptions.AppointmentApi.Image); SetupAppointmentApiInKubernetes(azureResources, appointmentApiAzureResources, clusterOptions); }
public MyStack() { var config = new Pulumi.Config(); Pulumi.Log.Info($"mySecretKey: {config.RequireSecret("mySecretKey")}"); // Create an Azure Resource Group var resourceGroup = new ResourceGroup("resourceGroup"); // Create an Azure Storage Account var storageAccount = new Account("storage", new AccountArgs { ResourceGroupName = resourceGroup.Name, AccountReplicationType = "LRS", AccountTier = "Standard" }); // Export the connection string for the storage account this.ConnectionString = storageAccount.PrimaryConnectionString; }
static Task <int> Main() { return(Deployment.RunAsync(() => { var config = new Pulumi.Config(); var companyCode = config.Require("company_code"); var location = config.Require("location"); var environment = config.Require("environment"); ResourceFactory factory = new ResourceFactory(companyCode, location, environment); // Create an Azure Resource Group var resourceGroup = factory.GetResourceGroup("00"); // Create an Azure Storage Account var storageAccount = factory.GetStorageAccount("00", resourceGroup.Name); // Export the connection string for the storage account return new Dictionary <string, object?> { { "connectionString", storageAccount.PrimaryConnectionString }, }; })); }
public KeyVaultStack() { // Get current Subscription var currentSubscription = Output.Create(GetSubscription.InvokeAsync()); var tenantId = currentSubscription.Apply(currentSubscription => currentSubscription.TenantId); // Get current Client Config var currentClient = Output.Create(GetClientConfig.InvokeAsync()); var objectId = currentClient.Apply(currentClient => currentClient.ObjectId); var config = new Pulumi.Config(); var resourceGroupName = config.Require("resource_group_name"); var keyVaultName = config.Require("key_vault_name"); // Create an Azure Resource Group var resourceGroup = new ResourceGroup(resourceGroupName); // Create an Azure Key Vault var keyVault = new KeyVault(keyVaultName, new KeyVaultArgs { ResourceGroupName = resourceGroup.Name, SkuName = "standard", TenantId = tenantId, AccessPolicies = { new KeyVaultAccessPolicyArgs { TenantId = tenantId, ObjectId = objectId, SecretPermissions ={ "list", "get" } } } }); this.VaultUri = keyVault.VaultUri; }
public AksStack() { var config = new Pulumi.Config(); var kubernetesVersion = config.Get("kubernetesVersion") ?? "1.19.3"; var resourceGroup = new ResourceGroup("aks-rg"); var password = new RandomPassword("password", new RandomPasswordArgs { Length = 20, Special = true, }).Result; var sshPublicKey = new PrivateKey("ssh-key", new PrivateKeyArgs { Algorithm = "RSA", RsaBits = 4096, }).PublicKeyOpenssh; // Create the AD service principal for the K8s cluster. var adApp = new Application("aks"); var adSp = new ServicePrincipal("aksSp", new ServicePrincipalArgs { ApplicationId = adApp.ApplicationId }); var adSpPassword = new ServicePrincipalPassword("aksSpPassword", new ServicePrincipalPasswordArgs { ServicePrincipalId = adSp.Id, Value = password, EndDate = "2099-01-01T00:00:00Z", }); // Grant networking permissions to the SP (needed e.g. to provision Load Balancers) var assignment = new Assignment("role-assignment", new AssignmentArgs { PrincipalId = adSp.Id, Scope = resourceGroup.Id, RoleDefinitionName = "Network Contributor" }); // Create a Virtual Network for the cluster var vnet = new VirtualNetwork("vnet", new VirtualNetworkArgs { ResourceGroupName = resourceGroup.Name, AddressSpaces = { "10.2.0.0/16" }, }); // Create a Subnet for the cluster var subnet = new Subnet("subnet", new SubnetArgs { ResourceGroupName = resourceGroup.Name, VirtualNetworkName = vnet.Name, AddressPrefixes = { "10.2.1.0/24" }, }); // Now allocate an AKS cluster. var cluster = new KubernetesCluster("aksCluster", new KubernetesClusterArgs { ResourceGroupName = resourceGroup.Name, DefaultNodePool = new KubernetesClusterDefaultNodePoolArgs { Name = "aksagentpool", NodeCount = 3, VmSize = "Standard_B2s", OsDiskSizeGb = 30, VnetSubnetId = subnet.Id, }, DnsPrefix = "aksdemo", LinuxProfile = new KubernetesClusterLinuxProfileArgs { AdminUsername = "******", SshKey = new KubernetesClusterLinuxProfileSshKeyArgs { KeyData = sshPublicKey, }, }, ServicePrincipal = new KubernetesClusterServicePrincipalArgs { ClientId = adApp.ApplicationId, ClientSecret = adSpPassword.Value, }, KubernetesVersion = kubernetesVersion, RoleBasedAccessControl = new KubernetesClusterRoleBasedAccessControlArgs { Enabled = true }, NetworkProfile = new KubernetesClusterNetworkProfileArgs { NetworkPlugin = "azure", DnsServiceIp = "10.2.2.254", ServiceCidr = "10.2.2.0/24", DockerBridgeCidr = "172.17.0.1/16", }, }); this.KubeConfig = cluster.KubeConfigRaw; }
public static Output <string> Run() { // Read a list of target locations from the config file: // Expecting a comma-separated list, e.g., "westus,eastus,westeurope" var locations = new Pulumi.Config().Require("locations").Split(","); var resourceGroup = new ResourceGroup("cosmosaci-rg", new ResourceGroupArgs { Location = locations[0] }); var app = new CosmosApp("aci", new CosmosAppArgs { ResourceGroup = resourceGroup, Locations = locations, DatabaseName = "pricedb", ContainerName = "prices", Factory = global => { var registry = new Registry("global", new RegistryArgs { ResourceGroupName = resourceGroup.Name, AdminEnabled = true, Sku = "Premium", }, global.Options); var dockerImage = new Image("node-app", new ImageArgs { ImageName = Output.Format($"{registry.LoginServer}/mynodeapp:v1.0.0"), Build = "./container", Registry = new ImageRegistry { Server = registry.LoginServer, Username = registry.AdminUsername, Password = registry.AdminPassword, }, }, new ComponentResourceOptions { Parent = registry }); return(region => { var connectionString = global.CosmosAccount.ConnectionStrings.Apply(cs => cs[0]); var group = new Group($"aci-{region.Location}", new GroupArgs { ResourceGroupName = resourceGroup.Name, Location = region.Location, ImageRegistryCredentials = { new GroupImageRegistryCredentialArgs { Server = registry.LoginServer, Username = registry.AdminUsername, Password = registry.AdminPassword, } }, OsType = "Linux", Containers = { new GroupContainerArgs { Cpu = 0.5, Image = dockerImage.ImageName, Memory = 1.5, Name = "hello-world", Ports = { new GroupContainerPortArgs { Port = 80, Protocol = "TCP", } }, EnvironmentVariables = { { "ENDPOINT", global.CosmosAccount.Endpoint }, { "MASTER_KEY", global.CosmosAccount.PrimaryMasterKey }, { "DATABASE", global.Database.Name }, { "COLLECTION", global.Container.Name }, { "LOCATION", region.Location }, }, }, }, IpAddressType = "public", DnsNameLabel = $"acishop-{region.Location}", }, global.Options); return new ExternalEndpoint(group.Fqdn); }); } }); return(Output.Format($"{app.Endpoint}/cosmos")); }
public BotStack() { var config = new Pulumi.Config(); var botName = config.Require("botName"); var resourceGroup = new ResourceGroup("botservice-rg"); var storageAccount = new Storage.Account("sa", new Storage.AccountArgs { ResourceGroupName = resourceGroup.Name, AccountReplicationType = "LRS", AccountTier = "Standard" }); var appServicePlan = new Plan("asp", new PlanArgs { ResourceGroupName = resourceGroup.Name, Kind = "App", Sku = new PlanSkuArgs { Tier = "Basic", Size = "B1" } }); var container = new Storage.Container("zips", new Storage.ContainerArgs { StorageAccountName = storageAccount.Name, ContainerAccessType = "private", }); var blob = new Storage.Blob("zip", new Storage.BlobArgs { StorageAccountName = storageAccount.Name, StorageContainerName = container.Name, Type = "Block", Source = new FileArchive("bot/publish") }); var codeBlobUrl = Storage.SharedAccessSignature.SignedBlobReadUrl(blob, storageAccount); var appInsights = new Insights("ai", new InsightsArgs { ApplicationType = "web", ResourceGroupName = resourceGroup.Name }); var appInsightApiKey = new ApiKey("ai", new ApiKeyArgs { ApplicationInsightsId = appInsights.Id, ReadPermissions = "api", }); var luis = new Cognitive.Account("cs", new Cognitive.AccountArgs { Kind = "CognitiveServices", // includes LUIS ResourceGroupName = resourceGroup.Name, SkuName = "S0" }); var msa = new Application("msapp", new ApplicationArgs { Oauth2AllowImplicitFlow = false, AvailableToOtherTenants = true, PublicClient = true }); var pwd = new RandomPassword("password", new RandomPasswordArgs { Length = 16, MinNumeric = 1, MinSpecial = 1, MinUpper = 1, MinLower = 1 }); var msaSecret = new ApplicationPassword("msasecret", new ApplicationPasswordArgs { ApplicationObjectId = msa.ObjectId, EndDateRelative = "8640h", Value = pwd.Result }); var app = new AppService("app", new AppServiceArgs { ResourceGroupName = resourceGroup.Name, AppServicePlanId = appServicePlan.Id, AppSettings = { { "WEBSITE_RUN_FROM_PACKAGE", codeBlobUrl }, { "MicrosoftAppId", msa.ApplicationId }, { "MicrosoftAppPassword", msaSecret.Value }, { "LuisApiKey", luis.PrimaryAccessKey }, }, HttpsOnly = true }); var bot = new WebApp(botName, new WebAppArgs { DisplayName = botName, MicrosoftAppId = msa.ApplicationId, ResourceGroupName = resourceGroup.Name, Sku = "F0", Location = "global", Endpoint = Output.Format($"https://{app.DefaultSiteHostname}/api/messages"), DeveloperAppInsightsApiKey = appInsightApiKey.Key, DeveloperAppInsightsApplicationId = appInsights.AppId, DeveloperAppInsightsKey = appInsights.InstrumentationKey }); this.BotEndpoint = bot.Endpoint; this.MicrosoftAppId = msa.ApplicationId; this.MicrosoftAppPassword = msaSecret.Value; }
public DeploymentStack() { // Define variables var config = new Pulumi.Config(); var rgName = string.Format("{0}-{1}-{2}-{3}", config.Require("prefix"), config.Require("resourceFunction"), config.Require("environment"), config.Require("azureRegion")); var storageAccountName = string.Format("{0}{1}sa{2}{3}", config.Require("prefix"), config.Require("resourceFunction"), config.Require("environment"), config.Require("azureRegion")); var apimName = string.Format("{0}-{1}-{2}-{3}", config.Require("prefix"), config.Require("resourceFunction"), config.Require("environment"), config.Require("azureRegion")); var kvName = string.Format("{0}-{1}-kv-{2}-{3}", config.Require("prefix"), config.Require("resourceFunction"), config.Require("environment"), config.Require("azureRegion")); var appInsightsName = string.Format("{0}-{1}-appinsights-{2}-{3}", config.Require("prefix"), config.Require("resourceFunction"), config.Require("environment"), config.Require("azureRegion")); var tags = new InputMap <string>() { { "belongsto", "Core Resources" }, { "environment", "Development" }, { "costcenter", "Backend" }, { "owner", "IT" } }; // Get current identity details var clientConfig = Output.Create(Pulumi.Azure.Core.Invokes.GetClientConfig()); var tenantId = clientConfig.Apply(c => c.TenantId); var currentPrincipal = clientConfig.Apply(c => c.ObjectId); // Create the Azure Resource Group var rg = new ResourceGroup("rg", new ResourceGroupArgs() { Name = rgName, Location = config.Require("azureLocation"), Tags = tags }); // Create the storage account to contain policy, OpenApi and other deployment related files var sa = new Account("sa", new AccountArgs { ResourceGroupName = rg.Name, Name = storageAccountName, AccountKind = "StorageV2", AccountReplicationType = "LRS", AccountTier = "Standard", EnableHttpsTrafficOnly = true, Tags = tags }, new CustomResourceOptions() { DependsOn = { rg } }); var saContainerApim = new Container("apim-files", new ContainerArgs() { StorageAccountName = sa.Name, ContainerAccessType = "private" }, new CustomResourceOptions() { DependsOn = { rg } }); var saContainerApi = new Container("api-files", new ContainerArgs() { StorageAccountName = sa.Name, ContainerAccessType = "private" }, new CustomResourceOptions() { DependsOn = { rg } }); // Create key vault to contain the certificate secret var kv = new KV.KeyVault("kv", new KV.KeyVaultArgs() { Name = kvName, ResourceGroupName = rg.Name, EnabledForDiskEncryption = false, SkuName = "standard", TenantId = tenantId, AccessPolicies = { new KeyVaultAccessPoliciesArgs { TenantId = tenantId, ObjectId = currentPrincipal, SecretPermissions = { "get" }, CertificatePermissions ={ "delete", "create", "get", "import", "list", "update" }, } }, Tags = tags }); // Upload the certificate to Key Vault --> Currently disabled because no valid pfx which breaks the deployment // var pfxBytes = System.IO.File.ReadAllBytes("certificates/"+ config.Require("customDomainsCertificateName")); // var cert = new KV.Certificate("apim-tls-certificate", new KV.CertificateArgs() // { // Name = "apim-tls-certificate", // KeyVaultId = kv.Id, // KeyVaultCertificate = new CertificateCertificateArgs() // { // Contents = System.Convert.ToBase64String(pfxBytes), // Password = config.Require("customDomainsCertificatePasword") // }, // CertificatePolicy = new CertificateCertificatePolicyArgs() // { // IssuerParameters = new CertificateCertificatePolicyIssuerParametersArgs() // { // Name = config.Require("customDomainsCertificateIssuer") // }, // KeyProperties = new CertificateCertificatePolicyKeyPropertiesArgs() // { // Exportable = true, // KeySize = 2048, // KeyType = "RSA", // ReuseKey = false // }, // SecretProperties = new CertificateCertificatePolicySecretPropertiesArgs() // { // ContentType = "application/x-pkcs12" // } // } // }, // new CustomResourceOptions() // { // DependsOn = { rg, kv } // }); // APIM resource var apim = new Service("apim", new ServiceArgs() { Name = apimName, ResourceGroupName = rg.Name, SkuName = "Developer_1", PublisherEmail = config.Require("publisherEmail"), PublisherName = config.Require("publisherName"), Tags = tags, Identity = new ServiceIdentityArgs() { Type = "SystemAssigned" } }, new CustomResourceOptions() { CustomTimeouts = new CustomTimeouts { Create = TimeSpan.FromMinutes(60) }, DependsOn = { rg, sa, kv } }); // Change Key Vault policy to be able to have APIM access the certificate // var kvApimPolicy = new KV.AccessPolicy("apim-policy", new KV.AccessPolicyArgs() // { // TenantId = tenantId, // ObjectId = apim.Identity.PrincipalId, // SecretPermissions = {"get"}, // CertificatePermissions = {"get", "list"}, // KeyVaultId = kv.Id // }); // Set custom domain // Call Powershell to assign custom domain to APIM instance // Create product on APIM var apimProduct = new Product("apimProduct", new ProductArgs() { ResourceGroupName = rg.Name, ApiManagementName = apim.Name, DisplayName = config.Require("productName"), ProductId = config.Require("productId"), ApprovalRequired = bool.Parse(config.Require("productApprovalRequired")), Published = bool.Parse(config.Require("productPublished")), SubscriptionRequired = bool.Parse(config.Require("productSubscriptionRequired")), SubscriptionsLimit = int.Parse(config.Require("productSubscriptionLimit")) }, new CustomResourceOptions() { DependsOn = { apim } }); var apimProductPolicy = new ProductPolicy("apimProductPolicy", new ProductPolicyArgs() { ResourceGroupName = rg.Name, ApiManagementName = apim.Name, ProductId = config.Require("productId"), XmlContent = @"<policies> <inbound> <base /> </inbound> <backend> <base /> </backend> <outbound> <set-header name='Server' exists-action='delete' /> <set-header name='X-Powered-By' exists-action='delete' /> <set-header name='X-AspNet-Version' exists-action='delete' /> <base /> </outbound> <on-error> <base /> </on-error> </policies>" }, new CustomResourceOptions() { DependsOn = { apim, apimProduct } }); // Create user var apimUser = new User("user", new UserArgs() { ResourceGroupName = rg.Name, ApiManagementName = apim.Name, UserId = string.Format("{0}-user", config.Require("productId")), Email = string.Format("{0}-{1}@didago.nl", config.Require("productId"), config.Require("environment")), FirstName = "user", LastName = config.Require("productName"), State = "active" }, new CustomResourceOptions() { DependsOn = { apim } }); // Create subscription var apimSubscription = new Subscription("subscription", new SubscriptionArgs() { ResourceGroupName = rg.Name, ApiManagementName = apim.Name, DisplayName = "Some subscription", ProductId = apimProduct.Id, UserId = apimUser.Id, PrimaryKey = config.Require("productSubscriptionKey") }, new CustomResourceOptions() { DependsOn = { apim, apimProduct, apimUser } }); // Create Application Insights var appInsights = new Insights("appinsights", new InsightsArgs() { Name = appInsightsName, ResourceGroupName = rg.Name, ApplicationType = "web", Tags = tags }); // Create APIM diagnostics logger var apimLogger = new Logger("apimLogger", new LoggerArgs() { Name = $"{apimName}-logger", ResourceGroupName = rg.Name, ApiManagementName = apim.Name, ApplicationInsights = new LoggerApplicationInsightsArgs() { InstrumentationKey = appInsights.InstrumentationKey } }, new CustomResourceOptions() { DependsOn = { appInsights, apim } }); // Add health probe to APIM, create operation, policy and assign to product var apiHealthProbe = new Api("healthProbe", new ApiArgs() { ResourceGroupName = rg.Name, ApiManagementName = apim.Name, DisplayName = "Health probe", Path = "health-probe", Protocols = "https", Revision = "1" }, new CustomResourceOptions() { DependsOn = { apim } }); var apimHealthProbeOperation = new ApiOperation("pingOperation", new ApiOperationArgs() { ResourceGroupName = rg.Name, ApiManagementName = apim.Name, ApiName = apiHealthProbe.Name, DisplayName = "Ping", Method = "GET", UrlTemplate = "/", OperationId = "get-ping" }, new CustomResourceOptions() { DependsOn = { apiHealthProbe } }); var apiHealthProbePolicy = new ApiPolicy("healthProbePolicy", new ApiPolicyArgs() { ResourceGroupName = rg.Name, ApiManagementName = apim.Name, ApiName = apiHealthProbe.Name, XmlContent = @"<policies> <inbound> <return-response> <set-status code='200' /> </return-response> <base /> </inbound> </policies>" }, new CustomResourceOptions() { DependsOn = { apimHealthProbeOperation } }); var apiHealtProbeProduct = new ProductApi("healthProbeProduct", new ProductApiArgs() { ResourceGroupName = rg.Name, ApiManagementName = apim.Name, ApiName = apiHealthProbe.Name, ProductId = apimProduct.ProductId }, new CustomResourceOptions() { DependsOn = { apim, apimProduct, apiHealthProbePolicy } }); }
public MyStack() { var config = new Pulumi.Config(); // Per-cluster config var aksClusterConfigs = new[] { new { Name = "east", Location = "eastus", NodeCount = 2, NodeSize = ContainerServiceVMSizeTypes.Standard_D2_v2, }, new { Name = "west", Location = "westus", NodeCount = 5, NodeSize = ContainerServiceVMSizeTypes.Standard_D2_v2, }, }; // Create an Azure Resource Group var resourceGroup = new ResourceGroup("aks", new ResourceGroupArgs { Location = config.Get("location") ?? "eastus", }); // Create the AD service principal for the K8s cluster. var adApp = new Application("aks", new ApplicationArgs { DisplayName = "my-aks-multicluster", }); var adSp = new ServicePrincipal("aksSp", new ServicePrincipalArgs { ApplicationId = adApp.ApplicationId }); var adSpPassword = new ServicePrincipalPassword("aksSpPassword", new ServicePrincipalPasswordArgs { ServicePrincipalId = adSp.Id, Value = config.Require("password"), EndDate = "2099-01-01T00:00:00Z", }); // Create the individual clusters var aksClusterNames = new List <Output <string> >(); foreach (var perClusterConfig in aksClusterConfigs) { var cluster = new ManagedCluster($"aksCluster-{perClusterConfig.Name}", new ManagedClusterArgs { // Global config arguments ResourceGroupName = resourceGroup.Name, LinuxProfile = new ContainerServiceLinuxProfileArgs { AdminUsername = "******", Ssh = new ContainerServiceSshConfigurationArgs { PublicKeys = { new ContainerServiceSshPublicKeyArgs { KeyData = config.Require("sshPublicKey"), } } } }, ServicePrincipalProfile = new ManagedClusterServicePrincipalProfileArgs { ClientId = adApp.ApplicationId, Secret = adSpPassword.Value }, // Per-cluster config arguments Location = perClusterConfig.Location, AgentPoolProfiles = { new ManagedClusterAgentPoolProfileArgs { Mode = AgentPoolMode.System, Name = "agentpool", Count = perClusterConfig.NodeCount, VmSize = perClusterConfig.NodeSize, } }, DnsPrefix = $"{Pulumi.Deployment.Instance.StackName}-kube", KubernetesVersion = "1.18.14", }); aksClusterNames.Add(cluster.Name); } ; this.aksClusterNames = Output.All(aksClusterNames); }
static Task <int> Main() { return(Deployment.RunAsync(() => { var config = new Config(); var nodeCount = config.GetInt32("nodeCount") ?? 2; var appReplicaCount = config.GetInt32("appReplicaCount") ?? 5; var domainName = config.Get("domainName"); var cluster = new KubernetesCluster("do-cluser", new KubernetesClusterArgs { Region = "sfo2", Version = "latest", NodePool = new KubernetesClusterNodePoolArgs { Name = "default", Size = "s-2vcpu-2gb", NodeCount = nodeCount } }); var k8sProvider = new Provider("do-k8s", new ProviderArgs { KubeConfig = cluster.KubeConfigs.Apply(array => array[0].RawConfig) }); var app = new Pulumi.Kubernetes.Apps.V1.Deployment("do-app-dep", new DeploymentArgs { Spec = new DeploymentSpecArgs { Selector = new LabelSelectorArgs { MatchLabels = { { "app", "app-nginx" } } }, Replicas = appReplicaCount, Template = new PodTemplateSpecArgs { Metadata = new ObjectMetaArgs { Labels = { { "app", "app-nginx" } } }, Spec = new PodSpecArgs { Containers = new ContainerArgs { Name = "nginx", Image = "nginx" } } } } }, new CustomResourceOptions { Provider = k8sProvider }); var appService = new Service("do-app-svc", new ServiceArgs { Spec = new ServiceSpecArgs { Type = "LoadBalancer", Selector = app.Spec.Apply(spec => spec.Template.Metadata.Labels), Ports = new ServicePortArgs { Port = 80 } } }, new CustomResourceOptions { Provider = k8sProvider }); var ingressIp = appService.Status.Apply(status => status.LoadBalancer.Ingress[0].Ip); if (!string.IsNullOrWhiteSpace(domainName)) { var domain = new Domain("do-domain", new DomainArgs { Name = domainName, IpAddress = ingressIp }); var cnameRecord = new DnsRecord("do-domain-cname", new DnsRecordArgs { Domain = domain.Name, Type = "CNAME", Name = "www", Value = "@" }); } return new Dictionary <string, object?> { { "ingressIp", ingressIp } }; })); }
public AzureStack() { var config = new Pulumi.Config(); var deployTo = config.Require("DeployTo"); // Create an Azure Resource Group var resourceGroupName = $"rg-ne-rpc-demo-{deployTo}"; var resourceGroup = new ResourceGroup(resourceGroupName, new ResourceGroupArgs { Name = resourceGroupName }); // Create an Azure Storage Account var storageAccount = new Account($"nerpcdemo{deployTo}", new AccountArgs { ResourceGroupName = resourceGroup.Name, AccountReplicationType = "LRS", AccountTier = "Standard" }); // Container for deployment artefacts var zipContainer = new Container("zips", new ContainerArgs { StorageAccountName = storageAccount.Name, ContainerAccessType = "private" }); var dataContainer = new Container("data", new ContainerArgs { StorageAccountName = storageAccount.Name, ContainerAccessType = "private", Name = "data" }); var appServicePlan = new Plan($"plan-{deployTo}", new PlanArgs { ResourceGroupName = resourceGroup.Name, Kind = "FunctionApp", Sku = new PlanSkuArgs { Tier = "Dynamic", Size = "Y1", } }); var blob = new Blob("azure-func", new BlobArgs { StorageAccountName = storageAccount.Name, StorageContainerName = zipContainer.Name, Type = "Block", Source = new FileArchive("../azure-func/publish") }); var codeBlobUrl = SharedAccessSignature.SignedBlobReadUrl(blob, storageAccount); var app = new FunctionApp("app", new FunctionAppArgs { ResourceGroupName = resourceGroup.Name, AppServicePlanId = appServicePlan.Id, AppSettings = { { "runtime", "dotnet" }, { "WEBSITE_RUN_FROM_PACKAGE", codeBlobUrl }, { "QuoteServerHost", "https://vn651r8t22.execute-api.eu-west-2.amazonaws.com/Prod" }, { "DataConnectionString", storageAccount.PrimaryBlobConnectionString }, { "DataContainer", dataContainer.Name } }, StorageAccountName = storageAccount.Name, StorageAccountAccessKey = storageAccount.PrimaryAccessKey, Version = "~3" }); this.StorageAccountName = storageAccount.Name; this.Endpoint = Output.Format($"https://{app.DefaultHostname}/api/lookup"); this.DataContainer = dataContainer.Name; }
public MyStack() { var config = new Pulumi.Config(); var location = config.Get("location") ?? "WestUS"; // Create an Azure Resource Group var resourceGroup = new ResourceGroup("resourceGroup", new ResourceGroupArgs { ResourceGroupName = "azure-nextgen-cs-aks", Location = location }); // Create an AD service principal var adApp = new Application("aks"); var adSp = new ServicePrincipal("aksSp", new ServicePrincipalArgs { ApplicationId = adApp.ApplicationId }); // Generate random password var password = new RandomPassword("password", new RandomPasswordArgs { Length = 20, Special = true }); // Create the Service Principal Password var adSpPassword = new ServicePrincipalPassword("aksSpPassword", new ServicePrincipalPasswordArgs { ServicePrincipalId = adSp.Id, Value = password.Result, EndDate = "2099-01-01T00:00:00Z" }); // Generate an SSH key var sshKey = new PrivateKey("ssh-key", new PrivateKeyArgs { Algorithm = "RSA", RsaBits = 4096 }); var managedClusterName = config.Get("managedClusterName") ?? "azure-nextgen-aks"; var cluster = new ManagedCluster("managedClusterResource", new ManagedClusterArgs { ResourceGroupName = resourceGroup.Name, AddonProfiles = { { "KubeDashboard", new ManagedClusterAddonProfileArgs { Enabled = true } } }, AgentPoolProfiles = { new ManagedClusterAgentPoolProfileArgs { Count = 3, MaxPods = 110, Mode = "System", Name = "agentpool", OsDiskSizeGB = 30, OsType = "Linux", Type = "VirtualMachineScaleSets", VmSize = "Standard_DS2_v2", } }, DnsPrefix = "azurenextgenprovider", EnableRBAC = true, KubernetesVersion = "1.16.10", LinuxProfile = new ContainerServiceLinuxProfileArgs { AdminUsername = "******", Ssh = new ContainerServiceSshConfigurationArgs { PublicKeys = { new ContainerServiceSshPublicKeyArgs { KeyData = sshKey.PublicKeyOpenssh, } } } }, Location = resourceGroup.Location, NodeResourceGroup = $"MC_azure-nextgen-cs_{managedClusterName}", ResourceName = managedClusterName, ServicePrincipalProfile = new ManagedClusterServicePrincipalProfileArgs { ClientId = adApp.ApplicationId, Secret = adSpPassword.Value } }); // Export the KubeConfig this.KubeConfig = Output.Tuple(resourceGroup.Name, cluster.Name).Apply(names => GetKubeConfig(names.Item1, names.Item2)); }
public ApimStack() { var config = new Pulumi.Config(); var tenantId = config.Require("tenantId"); var authorizationEndpoint = $"https://login.microsoftonline.com/{tenantId}/oauth2/v2.0/authorize"; var tokenEndpoint = $"https://login.microsoftonline.com/{tenantId}/oauth2/v2.0/token"; var defaultScope = config.Require("scope"); var clientId = config.Require("clientId"); var clientSecret = config.Require("clientSecret"); // Create an Azure Resource Group var resourceGroup = new ResourceGroup("rg-chris-apim"); //Service Plan var appServicePlan = new Plan("plan-api", new PlanArgs { ResourceGroupName = resourceGroup.Name, Kind = "App", Sku = new PlanSkuArgs { Tier = "Basic", Size = "B1" } }); var app = new AppService("app-api", new AppServiceArgs { ResourceGroupName = resourceGroup.Name, AppServicePlanId = appServicePlan.Id }); var apim = new Service("apim-api", new ServiceArgs { ResourceGroupName = resourceGroup.Name, PublisherName = "chrisjensenuk", PublisherEmail = "*****@*****.**", SkuName = "Developer_1" }); var apimAuth = new AuthorizationServer("apim-oauth", new AuthorizationServerArgs { ApiManagementName = apim.Name, ResourceGroupName = resourceGroup.Name, DisplayName = "apim-oauth", ClientRegistrationEndpoint = "http://localhost", GrantTypes = { "authorizationCode" }, AuthorizationEndpoint = authorizationEndpoint, AuthorizationMethods = { "GET", "POST" }, TokenEndpoint = tokenEndpoint, ClientAuthenticationMethods = "Body", BearerTokenSendingMethods = "authorizationHeader", DefaultScope = defaultScope, ClientId = clientId, ClientSecret = clientSecret }); var api = new Api("example-api", new ApiArgs { ResourceGroupName = resourceGroup.Name, ApiManagementName = apim.Name, Revision = "1", DisplayName = "Example API", Path = "example", Protocols = { "https" }, Oauth2Authorization = new ApiOauth2AuthorizationArgs { AuthorizationServerName = apimAuth.Name }, Import = new ApiImportArgs { ContentFormat = "openapi+json", ContentValue = Constants.SwaggerJson }, ServiceUrl = app.Name.Apply(n => $"http://{n}.azurewebsites.net") }); var policy = new ApiPolicy("example-api-policy", new ApiPolicyArgs { ResourceGroupName = resourceGroup.Name, ApiManagementName = apim.Name, ApiName = api.Name, XmlContent = Constants.ApiPolicyXml }); }
public MyStack() { var config = new Pulumi.Config(); var location = config.Get("location") ?? "WestUS"; var resourceGroup = new ResourceGroup("synapse-rg"); var storageAccount = new StorageAccount("synapsesa", new StorageAccountArgs { ResourceGroupName = resourceGroup.Name, AccessTier = AccessTier.Hot, EnableHttpsTrafficOnly = true, IsHnsEnabled = true, Kind = "StorageV2", Sku = new SkuArgs { Name = "Standard_RAGRS" }, }); var dataLakeStorageAccountUrl = Output.Format($"https://{storageAccount.Name}.dfs.core.windows.net"); var users = new BlobContainer("users", new BlobContainerArgs { ResourceGroupName = resourceGroup.Name, AccountName = storageAccount.Name, PublicAccess = PublicAccess.None }); var workspacePwd = new RandomPassword("workspace-pwd", new RandomPasswordArgs { Length = 12, }); var workspace = new Workspace("workspace", new WorkspaceArgs { ResourceGroupName = resourceGroup.Name, DefaultDataLakeStorage = new DataLakeStorageAccountDetailsArgs { AccountUrl = dataLakeStorageAccountUrl, Filesystem = "users" }, Identity = new ManagedIdentityArgs { Type = ResourceIdentityType.SystemAssigned }, SqlAdministratorLogin = "******", SqlAdministratorLoginPassword = workspacePwd.Result }); var allowAll = new IpFirewallRule("allowAll", new IpFirewallRuleArgs { ResourceGroupName = resourceGroup.Name, WorkspaceName = workspace.Name, EndIpAddress = "255.255.255.255", StartIpAddress = "0.0.0.0" }); var subscriptionId = resourceGroup.Id.Apply(id => id.Split('/')[2]); var roleDefinitionId = $"/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/roleDefinitions/ba92f5b4-2d11-453d-a403-e96b0029c9fe"; var storageAccess = new RoleAssignment("storageAccess", new RoleAssignmentArgs { RoleAssignmentName = new RandomUuid("roleName").Result, Scope = storageAccount.Id, PrincipalId = workspace.Identity.Apply(identity => identity.PrincipalId).Apply(v => v ?? "<preview>"), PrincipalType = "ServicePrincipal", RoleDefinitionId = roleDefinitionId }); var clientConfig = Output.Create(GetClientConfig.InvokeAsync()); var userAccess = new RoleAssignment("userAccess", new RoleAssignmentArgs { RoleAssignmentName = new RandomUuid("userRoleName").Result, Scope = storageAccount.Id, PrincipalId = clientConfig.Apply(v => v.ObjectId), PrincipalType = "User", RoleDefinitionId = roleDefinitionId }); var sqlPool = new SqlPool("SQLPOOL1", new SqlPoolArgs { ResourceGroupName = resourceGroup.Name, WorkspaceName = workspace.Name, Collation = "SQL_Latin1_General_CP1_CI_AS", CreateMode = "Default", Sku = new Pulumi.AzureNative.Synapse.Inputs.SkuArgs { Name = "DW100c" }, }); var sparkPool = new BigDataPool("Spark1", new BigDataPoolArgs { ResourceGroupName = resourceGroup.Name, WorkspaceName = workspace.Name, AutoPause = new AutoPausePropertiesArgs { DelayInMinutes = 15, Enabled = true, }, AutoScale = new AutoScalePropertiesArgs { Enabled = true, MaxNodeCount = 3, MinNodeCount = 3, }, NodeCount = 3, NodeSize = "Small", NodeSizeFamily = "MemoryOptimized", SparkVersion = "2.4" }); }
private Pipeline CreatePipeline(Bucket bucket, Role pipelineRole, Project buildProject, Role cloudFormationRole) { Pipeline pipeline = new Pipeline("WakerUpper", new PipelineArgs { ArtifactStore = new PipelineArtifactStoreArgs { Type = "S3", Location = bucket.BucketName, }, RoleArn = pipelineRole.Arn, Stages = { new PipelineStageArgs { Name = "Source", Actions = { new PipelineStageActionArgs { Name = "Source", Category = "Source", Owner = "ThirdParty", Provider = "GitHub", Version = "1", Configuration = { { "Owner", Config.Require("githubOwner") }, { "Repo", Config.Require("githubRepo") }, { "Branch", Config.Require("githubBranch") }, { "OAuthToken", GitHubConfig.RequireSecret("token") }, { "PollForSourceChanges", "false" }, }, OutputArtifacts ={ "SourceArtifact" }, }, }, }, new PipelineStageArgs { Name = "Build", Actions = { new PipelineStageActionArgs { Name = "Api-Build", Category = "Build", Owner = "AWS", Provider = "CodeBuild", Version = "1", InputArtifacts ={ "SourceArtifact" }, Configuration = { { "ProjectName", buildProject.Name }, { "EnvironmentVariables", "[ { \"name\": \"ProjectPath\", \"value\": \"WakerUpper.Api\" } ]" }, }, OutputArtifacts ={ "ApiBuildArtifact" }, RunOrder = 1, }, new PipelineStageActionArgs { Name = "WebApp-Build", Category = "Build", Owner = "AWS", Provider = "CodeBuild", Version = "1", InputArtifacts ={ "SourceArtifact" }, Configuration = { { "ProjectName", buildProject.Name }, { "EnvironmentVariables", "[ { \"name\": \"ProjectPath\", \"value\": \"WakerUpper.WebApp\" } ]" }, }, OutputArtifacts ={ "WebAppBuildArtifact" }, RunOrder = 1, }, }, }, new PipelineStageArgs { Name = "Deploy", Actions = { new PipelineStageActionArgs { Name = "Api-CreateChangeSet", Category = "Deploy", Owner = "AWS", Provider = "CloudFormation", Version = "1", InputArtifacts ={ "ApiBuildArtifact" },
static Task <int> Main(string[] args) { return(Pulumi.Deployment.RunAsync(() => { var config = new Pulumi.Config(); var pw = config.RequireSecret("message"); var rawPw = config.Require("message"); var cmData = new CoreV1.ConfigMap("cmdata", new ConfigMapArgs { Data = new InputMap <string> { { "password", pw }, } }); var cmBinaryData = new CoreV1.ConfigMap("cmbinarydata", new ConfigMapArgs { BinaryData = new InputMap <string> { { "password", pw.Apply(v => Base64Encode(v)) }, } }); var sStringData = new CoreV1.Secret("sstringdata", new SecretArgs { StringData = new InputMap <string> { { "password", rawPw } } }); var sData = new CoreV1.Secret("sdata", new SecretArgs { Data = new InputMap <string> { { "password", Base64Encode(rawPw) } } }); var name = $"test-{RandomString()}"; var secretYAML = $@" apiVersion: v1 kind: Secret metadata: name: {name} stringData: password: {rawPw} "; var cg = new Yaml.ConfigGroup("example", new Yaml.ConfigGroupArgs { Yaml = secretYAML }); var cgSecret = cg.GetResource <CoreV1.Secret>(name); return new Dictionary <string, object> { { "cmData", cmData.Data }, { "cmBinaryData", cmData.BinaryData }, { "sStringData", sStringData.StringData }, { "sData", sStringData.Data }, { "cgData", cgSecret.Apply(v => v.Data) }, }; })); }