Azure C# AKS + Cosmos DB example
MODIFY
README.md
README.md
@@ -200,6 +200,7 @@ Cluster.
[Azure Container Instance](azure-cs-aci) | Run Azure Container Instances on Linux.
[Azure Kubernetes Service](azure-cs-aks) | Create an Azure Kubernetes Service (AKS) Cluster.
[AKS web app with .NET 5](azure-cs-net5-aks-webapp) | Create an Azure Kubernetes Service (AKS) cluster and deploy a web app to it using .NET 5 and C# 9.
+[AKS + Cosmos DB](azure-cs-aks-cosmos-helm) | A Helm chart deployed to AKS that stores TODOs in an Azure Cosmos DB MongoDB API.
[Azure App Service](azure-cs-appservice) | Build a web application hosted in App Service and provision Azure SQL Database and Azure Application Insights.
[Azure App Service with Docker](azure-cs-appservice-docker) | Build a web application hosted in App Service from Docker images.
[Azure Cosmos DB and LogicApp](azure-cs-cosmosdb-logicapp) | Define Cosmos DB, API connections, and link them to a logic app.

ADD
azure-cs-aks-cosmos-helm/.gitignore
+## Ignore Visual Studio temporary files, build results, and
+## files generated by popular Visual Studio add-ons.
+##
+## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
+
+# User-specific files
+*.rsuser
+*.suo
+*.user
+*.userosscache
+*.sln.docstates
+
+# User-specific files (MonoDevelop/Xamarin Studio)
+*.userprefs
+
+# Mono auto generated files
+mono_crash.*
+
+# Build results
+[Dd]ebug/
+[Dd]ebugPublic/
+[Rr]elease/
+[Rr]eleases/
+x64/
+x86/
+[Aa][Rr][Mm]/
+[Aa][Rr][Mm]64/
+bld/
+[Bb]in/
+[Oo]bj/
+[Ll]og/
+[Ll]ogs/
+
+# Visual Studio 2015/2017 cache/options directory
+.vs/
+# Uncomment if you have tasks that create the project's static files in wwwroot
+#wwwroot/
+
+# Visual Studio 2017 auto generated files
+Generated\ Files/
+
+# MSTest test Results
+[Tt]est[Rr]esult*/
+[Bb]uild[Ll]og.*
+
+# NUnit
+*.VisualState.xml
+TestResult.xml
+nunit-*.xml
+
+# Build Results of an ATL Project
+[Dd]ebugPS/
+[Rr]eleasePS/
+dlldata.c
+
+# Benchmark Results
+BenchmarkDotNet.Artifacts/
+
+# .NET Core
+project.lock.json
+project.fragment.lock.json
+artifacts/
+
+# StyleCop
+StyleCopReport.xml
+
+# Files built by Visual Studio
+*_i.c
+*_p.c
+*_h.h
+*.ilk
+*.meta
+*.obj
+*.iobj
+*.pch
+*.pdb
+*.ipdb
+*.pgc
+*.pgd
+*.rsp
+*.sbr
+*.tlb
+*.tli
+*.tlh
+*.tmp
+*.tmp_proj
+*_wpftmp.csproj
+*.log
+*.vspscc
+*.vssscc
+.builds
+*.pidb
+*.svclog
+*.scc
+
+# Chutzpah Test files
+_Chutzpah*
+
+# Visual C++ cache files
+ipch/
+*.aps
+*.ncb
+*.opendb
+*.opensdf
+*.sdf
+*.cachefile
+*.VC.db
+*.VC.VC.opendb
+
+# Visual Studio profiler
+*.psess
+*.vsp
+*.vspx
+*.sap
+
+# Visual Studio Trace Files
+*.e2e
+
+# TFS 2012 Local Workspace
+$tf/
+
+# Guidance Automation Toolkit
+*.gpState
+
+# ReSharper is a .NET coding add-in
+_ReSharper*/
+*.[Rr]e[Ss]harper
+*.DotSettings.user
+
+# JustCode is a .NET coding add-in
+.JustCode
+
+# TeamCity is a build add-in
+_TeamCity*
+
+# DotCover is a Code Coverage Tool
+*.dotCover
+
+# AxoCover is a Code Coverage Tool
+.axoCover/*
+!.axoCover/settings.json
+
+# Visual Studio code coverage results
+*.coverage
+*.coveragexml
+
+# NCrunch
+_NCrunch_*
+.*crunch*.local.xml
+nCrunchTemp_*
+
+# MightyMoose
+*.mm.*
+AutoTest.Net/
+
+# Web workbench (sass)
+.sass-cache/
+
+# Installshield output folder
+[Ee]xpress/
+
+# DocProject is a documentation generator add-in
+DocProject/buildhelp/
+DocProject/Help/*.HxT
+DocProject/Help/*.HxC
+DocProject/Help/*.hhc
+DocProject/Help/*.hhk
+DocProject/Help/*.hhp
+DocProject/Help/Html2
+DocProject/Help/html
+
+# Click-Once directory
+publish/
+
+# Publish Web Output
+*.[Pp]ublish.xml
+*.azurePubxml
+# Note: Comment the next line if you want to checkin your web deploy settings,
+# but database connection strings (with potential passwords) will be unencrypted
+*.pubxml
+*.publishproj
+
+# Microsoft Azure Web App publish settings. Comment the next line if you want to
+# checkin your Azure Web App publish settings, but sensitive information contained
+# in these scripts will be unencrypted
+PublishScripts/
+
+# NuGet Packages
+*.nupkg
+# NuGet Symbol Packages
+*.snupkg
+# The packages folder can be ignored because of Package Restore
+**/[Pp]ackages/*
+# except build/, which is used as an MSBuild target.
+!**/[Pp]ackages/build/
+# Uncomment if necessary however generally it will be regenerated when needed
+#!**/[Pp]ackages/repositories.config
+# NuGet v3's project.json files produces more ignorable files
+*.nuget.props
+*.nuget.targets
+
+# Microsoft Azure Build Output
+csx/
+*.build.csdef
+
+# Microsoft Azure Emulator
+ecf/
+rcf/
+
+# Windows Store app package directories and files
+AppPackages/
+BundleArtifacts/
+Package.StoreAssociation.xml
+_pkginfo.txt
+*.appx
+*.appxbundle
+*.appxupload
+
+# Visual Studio cache files
+# files ending in .cache can be ignored
+*.[Cc]ache
+# but keep track of directories ending in .cache
+!?*.[Cc]ache/
+
+# Others
+ClientBin/
+~$*
+*~
+*.dbmdl
+*.dbproj.schemaview
+*.jfm
+*.pfx
+*.publishsettings
+orleans.codegen.cs
+
+# Including strong name files can present a security risk
+# (https://github.com/github/gitignore/pull/2483#issue-259490424)
+#*.snk
+
+# Since there are multiple workflows, uncomment next line to ignore bower_components
+# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
+#bower_components/
+
+# RIA/Silverlight projects
+Generated_Code/
+
+# Backup & report files from converting an old project file
+# to a newer Visual Studio version. Backup files are not needed,
+# because we have git ;-)
+_UpgradeReport_Files/
+Backup*/
+UpgradeLog*.XML
+UpgradeLog*.htm
+ServiceFabricBackup/
+*.rptproj.bak
+
+# SQL Server files
+*.mdf
+*.ldf
+*.ndf
+
+# Business Intelligence projects
+*.rdl.data
+*.bim.layout
+*.bim_*.settings
+*.rptproj.rsuser
+*- [Bb]ackup.rdl
+*- [Bb]ackup ([0-9]).rdl
+*- [Bb]ackup ([0-9][0-9]).rdl
+
+# Microsoft Fakes
+FakesAssemblies/
+
+# GhostDoc plugin setting file
+*.GhostDoc.xml
+
+# Node.js Tools for Visual Studio
+.ntvs_analysis.dat
+node_modules/
+
+# Visual Studio 6 build log
+*.plg
+
+# Visual Studio 6 workspace options file
+*.opt
+
+# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
+*.vbw
+
+# Visual Studio LightSwitch build output
+**/*.HTMLClient/GeneratedArtifacts
+**/*.DesktopClient/GeneratedArtifacts
+**/*.DesktopClient/ModelManifest.xml
+**/*.Server/GeneratedArtifacts
+**/*.Server/ModelManifest.xml
+_Pvt_Extensions
+
+# Paket dependency manager
+.paket/paket.exe
+paket-files/
+
+# FAKE - F# Make
+.fake/
+
+# CodeRush personal settings
+.cr/personal
+
+# Python Tools for Visual Studio (PTVS)
+__pycache__/
+*.pyc
+
+# Cake - Uncomment if you are using it
+# tools/**
+# !tools/packages.config
+
+# Tabs Studio
+*.tss
+
+# Telerik's JustMock configuration file
+*.jmconfig
+
+# BizTalk build output
+*.btp.cs
+*.btm.cs
+*.odx.cs
+*.xsd.cs
+
+# OpenCover UI analysis results
+OpenCover/
+
+# Azure Stream Analytics local run output
+ASALocalRun/
+
+# MSBuild Binary and Structured Log
+*.binlog
+
+# NVidia Nsight GPU debugger configuration file
+*.nvuser
+
+# MFractors (Xamarin productivity tool) working folder
+.mfractor/
+
+# Local History for Visual Studio
+.localhistory/
+
+# BeatPulse healthcheck temp database
+healthchecksdb
+
+# Backup folder for Package Reference Convert tool in Visual Studio 2017
+MigrationBackup/
+
+# Ionide (cross platform F# VS Code tools) working folder
+.ionide/

ADD
azure-cs-aks-cosmos-helm/AksCluster.cs
+// Copyright 2016-2021, Pulumi Corporation. All rights reserved.
+
+using System;
+using System.Text;
+
+using Pulumi;
+using Pulumi.AzureAD;
+using Pulumi.AzureNative.ContainerService;
+using Pulumi.AzureNative.ContainerService.Inputs;
+using Pulumi.AzureNative.Resources;
+using Pulumi.Random;
+using Pulumi.Tls;
+using K8s = Pulumi.Kubernetes;
+
+public class AksCluster : ComponentResource
+{
+ public Output<string> ClusterName { get; set; }
+ public Output<string> KubeConfig { get; set; }
+ public K8s.Provider Provider { get; set; }
+
+ public AksCluster(string name, AksClusterArgs args)
+ : base("example:component:AksCluster", name)
+ {
+ var adApp = new Application("app", new ApplicationArgs
+ {
+ DisplayName = "aks-cosmos"
+ }, new CustomResourceOptions { Parent = this });
+
+ var adSp = new ServicePrincipal("service-principal", new ServicePrincipalArgs
+ {
+ ApplicationId = adApp.ApplicationId
+ }, new CustomResourceOptions { Parent = this });
+
+ var pw = new RandomPassword("pw", new RandomPasswordArgs
+ {
+ Length = 20,
+ Special = true
+ }, new CustomResourceOptions { Parent = this });
+
+ var adSpPassword = new ServicePrincipalPassword("sp-password", new ServicePrincipalPasswordArgs
+ {
+ ServicePrincipalId = adSp.Id,
+ Value = pw.Result,
+ EndDate = "2099-01-01T00:00:00Z"
+ }, new CustomResourceOptions { Parent = this });
+
+ var keyPair = new PrivateKey("ssh-key", new PrivateKeyArgs
+ {
+ Algorithm = "RSA",
+ RsaBits = 4096
+ }, new CustomResourceOptions { Parent = this });
+
+ var k8sCluster = new ManagedCluster(name, new ManagedClusterArgs
+ {
+ ResourceGroupName = args.ResourceGroupName,
+ AddonProfiles =
+ {
+ ["KubeDashboard"] = new ManagedClusterAddonProfileArgs { Enabled = true }
+ },
+ AgentPoolProfiles =
+ {
+ new ManagedClusterAgentPoolProfileArgs
+ {
+ Count = args.NodeCount,
+ VmSize = args.NodeSize,
+ MaxPods = 110,
+ Mode = "System",
+ Name = "agentpool",
+ OsDiskSizeGB = 30,
+ OsType = "Linux",
+ Type = "VirtualMachineScaleSets"
+ }
+ },
+ DnsPrefix = args.ResourceGroupName,
+ EnableRBAC = true,
+ KubernetesVersion = args.KubernetesVersion,
+ LinuxProfile = new ContainerServiceLinuxProfileArgs
+ {
+ AdminUsername = "testuser",
+ Ssh = new ContainerServiceSshConfigurationArgs
+ {
+ PublicKeys = new ContainerServiceSshPublicKeyArgs
+ {
+ KeyData = keyPair.PublicKeyOpenssh
+ }
+ }
+ },
+ NodeResourceGroup = $"{name}-node-rg",
+ ServicePrincipalProfile = new ManagedClusterServicePrincipalProfileArgs
+ {
+ ClientId = adApp.ApplicationId,
+ Secret = adSpPassword.Value
+ }
+ }, new CustomResourceOptions { Parent = this });
+
+ this.ClusterName = k8sCluster.Name;
+
+ this.KubeConfig = Output.Tuple(k8sCluster.Name, args.ResourceGroupName.ToOutput())
+ .Apply(pair =>
+ {
+ var k8sClusterName = pair.Item1;
+ var resourceGroupName = pair.Item2;
+
+ return ListManagedClusterUserCredentials.InvokeAsync(new ListManagedClusterUserCredentialsArgs
+ {
+ ResourceGroupName = resourceGroupName,
+ ResourceName = k8sClusterName
+ });
+ })
+ .Apply(x => x.Kubeconfigs[0].Value)
+ .Apply(Convert.FromBase64String)
+ .Apply(Encoding.UTF8.GetString);
+
+ this.Provider = new K8s.Provider("k8s-provider", new K8s.ProviderArgs
+ {
+ KubeConfig = this.KubeConfig
+ }, new CustomResourceOptions { Parent = this });
+ }
+}
+
+public class AksClusterArgs
+{
+ public Input<string> ResourceGroupName { get; set; }
+ public string KubernetesVersion { get; set; }
+ public int NodeCount { get; set; }
+ public string NodeSize { get; set; }
+}

ADD
azure-cs-aks-cosmos-helm/CosmosDBMongoDB.cs
+// Copyright 2016-2021, Pulumi Corporation. All rights reserved.
+
+using System;
+using System.Collections.Generic;
+using System.Collections.Immutable;
+using Pulumi;
+using Pulumi.AzureNative.DocumentDB;
+using Pulumi.AzureNative.DocumentDB.Inputs;
+
+public class CosmosDBMongoDB : ComponentResource
+{
+ public Output<string> AccountName { get; set; }
+
+ public Output<string> DatabaseName { get; set; }
+
+ public CosmosDBMongoDB(string name, CosmosDBMongoDBArgs args)
+ : base("example:component:CosmosDBMongoDB", name)
+ {
+ var config = new Config("azure-native");
+ var location = config.Require("location");
+
+ var databaseAccount = new DatabaseAccount("cosmos-mongodb", new DatabaseAccountArgs
+ {
+ ResourceGroupName = args.ResourceGroupName,
+ DatabaseAccountOfferType = DatabaseAccountOfferType.Standard,
+ Kind = DatabaseAccountKind.MongoDB,
+ ConsistencyPolicy = new ConsistencyPolicyArgs
+ {
+ DefaultConsistencyLevel = DefaultConsistencyLevel.BoundedStaleness,
+ MaxIntervalInSeconds = 10,
+ MaxStalenessPrefix = 200,
+ },
+ Locations =
+ {
+ new LocationArgs
+ {
+ FailoverPriority = 0,
+ LocationName = location
+ }
+ }
+ }, new CustomResourceOptions { Parent = this });
+ this.AccountName = databaseAccount.Name;
+
+ var database = new MongoDBResourceMongoDBDatabase(args.DatabaseName, new MongoDBResourceMongoDBDatabaseArgs
+ {
+ ResourceGroupName = args.ResourceGroupName,
+ AccountName = databaseAccount.Name,
+ Resource = new MongoDBDatabaseResourceArgs { Id = args.DatabaseName }
+ }, new CustomResourceOptions { Parent = this });
+ this.DatabaseName = database.Name;
+ }
+
+ public static Output<ImmutableDictionary<string, string>> KubernetesSecretData(Output<string> resourceGroupName, Output<string> accountName, Output<string> databaseName)
+ {
+ return Output.Tuple(resourceGroupName, accountName, databaseName).Apply(async values =>
+ {
+ var conn = await ListDatabaseAccountConnectionStrings.InvokeAsync(
+ new ListDatabaseAccountConnectionStringsArgs
+ {
+ ResourceGroupName = values.Item1,
+ AccountName = values.Item2
+ });
+ return parseConnString(conn.ConnectionStrings[0].ConnectionString, values.Item3);
+ }
+ );
+ }
+
+ private static ImmutableDictionary<string, string> parseConnString(string conn, string database)
+ {
+ // Per the official docs[1], the format of this connection string is:
+ //
+ // mongodb://username:password@host:port/[database]?ssl=true
+ //
+ // For instance:
+ //
+ // mongodb://cosmos-mongodb965c15ec:9mrcqzY98o53WiehJ9FZncTS4auyU2BUG6E2Aq9kn8PUi6XsISj6fVhJJXGzfTpZcFGsgIzKw1unveMMQW8Mtw==@cosmos-mongodb965c15ec.mongo.cosmos.azure.com:10255/?ssl=true&replicaSet=globaldb&retrywrites=false&maxIdleTimeMS=120000&appName=@cosmos-mongodb965c15ec@
+ //
+ // Where these could have the following values:
+ //
+ // {
+ // username: "cosmosdb93a4133a",
+ // password: "23maXrWsrzZ1LmPe4w6XNGRJJTHsqGZPDTjyVQNbPaw119KCoCNpStH0DQms5MKdyAecisBM9uWbpV7lUnyNeQ==",
+ // host: "cosmosdb93a4133a.documents.azure.com",
+ // port: "10255",
+ // database: "mydatabase"
+ // }
+ //
+ // There are a few subtleties involved in getting the Bitnami node Chart to actually be able to
+ // use this:
+ //
+ // 1. The `database` field is optional, we default to `test`, as the API expects.
+ // 2. The node Chart expects the components of this connection string to be parsed and
+ // presented in files in a `Secret`. The CosmosDb API doesn't natively expose this, so we
+ // must parse it ourselves.
+ // 3. The node Chart uses mongoose to speak the MongoDB wire protocol to CosmosDB. Mongoose
+ // fails to parse base64-encoded passwords because it doesn't like the `=` character. This
+ // means we have to (1) URI-encode the password component ourselves, and (2) base64-encode
+ // that URI-encoded password, because this is the format Kubernetes expects.
+ //
+ // [1]: https://docs.microsoft.com/en-us/azure/cosmos-db/connect-mongodb-account
+
+ var noProtocol = conn.Replace("mongodb://", "");
+ var parts = noProtocol.Split(":", 3);
+ var userName = parts[0];
+ var subParts = parts[1].Split("@", 2);
+ var (password, host) = (subParts[0], subParts[1]);
+ var port = parts[2].Split("/", 2)[0];
+ return new Dictionary<string, string>
+ {
+ {"host", toBase64(host)},
+ {"port", toBase64(port)},
+ {"username", toBase64(userName)},
+ {"password", toBase64(Uri.EscapeDataString(password))},
+ {"database", toBase64(database)},
+ }.ToImmutableDictionary();
+
+ static string toBase64(string plainText)
+ {
+ var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
+ return System.Convert.ToBase64String(plainTextBytes);
+ }
+ }
+}
+
+public class CosmosDBMongoDBArgs
+{
+ public Input<string> ResourceGroupName { get; set; }
+ public string DatabaseName { get; set; }
+}

ADD
azure-cs-aks-cosmos-helm/Pulumi.yaml
+name: azure-cs-aks-cosmos-helm
+runtime: dotnet
+description: A Helm chart deployed to AKS that stores TODOs in an Azure Cosmos DB MongoDB API

Azure C# AKS + Cosmos DB example (#980)