Saturday, October 23, 2021

Bicep Templates for Cosmos DB Setup

 Recently I came up with a few templates for setting up Cosmos DB Infrastructure for a demonstration. Following steps will show how to setup the Cosmos DB, Create Collections,  Create Private DNS Zones and Setup a Custom SQL role. 

The complete example is available publicly on GitHub.

1. Setup Cosmos DB Account

Here we are creating a Standard type account with Session consistency level. Given I am not enabling multiple regions, this will be sufficient. 

2. Create a database

Here I am setting the name with path to the Cosmos DB account. Also the account is added as a dependency. 

3. Create a container

Here I am setting up a container, name passed as a parameter and the partition key is set to be 'id' field. This is ideal for a write heavy workload.

If you are not concerned on security and only focused on getting the DB Setup,  those above setups will be sufficient. 

4. Setting up Private Link

By setting up a private link, you can ensure the data are only accessed within the resources inside a virtual network. As we are subnetting, by using Network Security Groups you can setup which subnets talk to what. 

This example creates following resources. 

privateEndpoint 'Microsoft.Network/privateEndpoints@2020-07-01'
privateDnsZone 'Microsoft.Network/privateDnsZones@2018-09-01'
privateDnsZone_A_1 'Microsoft.Network/privateDnsZones/A@2018-09-01'
privateDnsZone_A_2 'Microsoft.Network/privateDnsZones/A@2018-09-01'
privateDnsZone_SOA 'Microsoft.Network/privateDnsZones/SOA@2018-09-01'
vnetLink 'Microsoft.Network/privateDnsZones/virtualNetworkLinks@2018-09-01'

Here I am creating the private endpoint as well. as private DNS Zones as I can access them via a FQDN with that. The GitHub example. contains parameters for all of them.

5. Setup SQL Role Definition and Role Assignment

The above resources are for creating a new role definition. Allowed data actions are described in the dataActions variable. Also in role assignment I do have apiAppPrincipalId which is the id of the resource. where I am going to assign the principal. 

When you are writing code, you can use this identity and get the keys for accessing data without storing them anywhere in app configuration or source code.

No comments:

Post a Comment