Search code examples
azureazure-devopsterraform

How to output the Cosmos DB Connection String using Terraform


I'm using Terraform to build a Cosmos DB using the Mongo API in Azure but can't figure out how to return or output the connection string once it's built.

I've built several Cosmos DB's but can't find any material on how to output the connection string. I'm using module to build the resource which call's my main.tf and variable.tf. If I knew what to put in the output.tf file I'd put it in there so my module could leverage it.

Module { variable inputs }

I don't have any error messages to post as I don't know how to call the connection string. I did parse the Azure Provider and have posted a pic of the JSON from the Mongo DB Cosmos section. Pic of the JSON below: ![Mongo Cosmos DB JSON from the Azure TF Provider]https://i.sstatic.net/XNkfY.png


Solution

  • You need to read the data from the CosmosDB Account. It contains a connection_strings array.´Should look something like this:

    // Look for this
    resource "azurerm_cosmosdb_account" "cosdb"{
       ...
    }
    
    output "cosmosdb_connectionstrings" {
       value = azurerm_cosmosdb_account.cosdb.connection_strings
       sensitive   = true
    }
    

    You can also use string interpolation to build the connection string by combining the primary key and the endpoint. This also works if you don't manage the account with terraform. You can use the CosmosDB Data Source to access the keys.

    data "azurerm_cosmosdb_account" "cosdb" {
      name                = "${var.cosmosdbname}"
      resource_group_name = "${var.cosmosdbresourcegroupname}"
    }
    
    output "cosmosdb_connectionstrings" {
       value = "AccountEndpoint=${data.azurerm_cosmosdb_account.cosdb.endpoint};AccountKey=${data.azurerm_cosmosdb_account.cosdb.primary_key};"
       sensitive   = true
    }