How do I set up cosmosdb emulator locally from powershell script

1.5k views Asked by At

I am doing some testing on my cosmos db and I would like to use Cosmos Db emulator to be set up locally using scripts. I would like to use PowerShell scripts to create Db , containers , populate test data using PowerShell in cosmos db emulator but I couldn't find any documentation online. Can someone direct me or help me in doing this. Till now I have followed this documentation which allows me to start CosmosDb emulator using PowerShell

1

There are 1 answers

9
Gaurav Mantri On BEST ANSWER

I would like to use PowerShell scripts to create Db , containers , populate test data using PowerShell in cosmos db emulator but I couldn't find any documentation online.

The PowerShell module (Az.Cosmos) provided by Microsoft focuses only on the Cosmos DB accounts in the cloud. As of version 5.8.0, it does not have a support for Cosmos DB emulator.

Luckily there's a community solution available that you can use: https://github.com/PlagueHO/CosmosDB.

To create a context for emulator account, this is what you will have to do:

$cosmosDbContext = New-CosmosDbContext -Emulator -Database 'MyDatabase'

Once you have the context, you should be able to create databases and containers. For example:

New-CosmosDbDatabase -Context $cosmosDbContext -Id 'MyDatabase' -OfferThroughput 1200

New-CosmosDbCollection -Context $cosmosDbContext -Id 'MyNewCollection' -PartitionKey 'id' -OfferThroughput 50000

This project was last updated 6 months ago so I am not sure if it has all the features you're looking for.

Other idea would be to make use of Cosmos DB .Net SDK and use that in PowerShell scripts of your own.

UPDATE

This is what I did:

  1. I opened the PowerShell console in Admin mode.
  2. I installed Cosmos module using Install-Module -Name CosmosDB. I got an error initially (something about module not found) which I fixed by setting the TLS command to 1.2 using [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12.
  3. Then I started the emulator using your commands.
  4. After that I created the context using $cosmosDbContext = New-CosmosDbContext -Emulator.
  5. After that I listed the databases in my Cosmos emulator account and was able to successfully do so.

enter image description here