Post

Create an Azure Function with the Azure Cosmos DB Trigger to listen to the Change Feed

In this tutorial we will set up an Azure Cosmos DB and Azure Function App using Terraform and from there we will create and deploy an Azure Function written in Node.js that listens to the Azure Cosmos DB change feed for changes to the database

Creating an Azure Function with the Azure Cosmos DB Trigger

Terraform Configuration File

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
terraform {
  required_providers {
    azurerm = {
      source  = "hashicorp/azurerm"
      version = "=3.110.0"
    }
  }
}

provider "azurerm" {
  features {
    resource_group {
      prevent_deletion_if_contains_resources = false
    }
  }
}

resource "azurerm_resource_group" "rg" {
  name     = "ces-tf-terraform-rg"
  location = "West US 2"

  tags = {
    environment = "dev"
    source = "terraform"
    owner = "cloudengineerskills"
  }
}

resource "azurerm_storage_account" "func_storage" {
  name                     = "cloudengineerskillstfsa"
  resource_group_name      = azurerm_resource_group.rg.name
  location                 = azurerm_resource_group.rg.location
  account_tier             = "Standard"
  account_replication_type = "LRS"
    tags = {
    environment = "dev"
    source = "terraform"
    owner = "cloudengineerskills"
  }
}

resource "azurerm_service_plan" "func_consumption_plan" {
  name                = "cloudengineerskillstfconsumptionplan"
  resource_group_name = azurerm_resource_group.rg.name
  location            = azurerm_resource_group.rg.location
  os_type             = "Linux"
  sku_name            = "Y1"
  tags = {
    environment = "dev"
    source = "terraform"
    owner = "cloudengineerskills"
  }
}

resource "azurerm_log_analytics_workspace" "logs" {
  name                = "workspace-test"
  location            = azurerm_resource_group.rg.location
  resource_group_name = azurerm_resource_group.rg.name
  sku                 = "PerGB2018"
  retention_in_days   = 30

  tags = {
    environment = "dev"
    source = "terraform"
    owner = "cloudengineerskills"
  }
}

resource "azurerm_application_insights" "insights" {
  name                = "tf-test-appinsights"
  location            = azurerm_resource_group.rg.location
  resource_group_name = azurerm_resource_group.rg.name
  workspace_id        = azurerm_log_analytics_workspace.logs.id
  application_type    = "Node.JS"

  tags = {
    environment = "dev"
    source = "terraform"
    owner = "cloudengineerskills"
  }
}

resource "azurerm_linux_function_app" "func_app" {
  name                = "cloudengineerskillstffuncapp"
  resource_group_name = azurerm_resource_group.rg.name
  location            = azurerm_resource_group.rg.location

  storage_account_name       = azurerm_storage_account.func_storage.name
  storage_account_access_key = azurerm_storage_account.func_storage.primary_access_key
  service_plan_id = azurerm_service_plan.func_consumption_plan.id

  site_config {
    application_stack {
      node_version = 20
    }

    application_insights_connection_string = azurerm_application_insights.insights.connection_string
    application_insights_key = azurerm_application_insights.insights.instrumentation_key
  }

  app_settings = {
    "COSMOSDB_CONNECTION_STRING" = azurerm_cosmosdb_account.db_account.primary_sql_connection_string
  }

  tags = {
    environment = "dev"
    source = "terraform"
    owner = "cloudengineerskills"
  }
}

resource "azurerm_cosmosdb_account" "db_account" {
  name                      = "cloudengineerskills-tf-dbacc"
  location                  = azurerm_resource_group.rg.location
  resource_group_name       = azurerm_resource_group.rg.name
  offer_type                = "Standard"
  kind                      = "GlobalDocumentDB"

  geo_location {
    location          = azurerm_resource_group.rg.location
    failover_priority = 0
  }

  consistency_policy {
    consistency_level       = "Session"
  }

  capabilities {
    name = "EnableServerless"
  }

  free_tier_enabled = true

  depends_on = [
    azurerm_resource_group.rg
  ]

  tags = {
    environment = "dev"
    source = "terraform"
    owner = "cloudengineerskills"
  }
}

resource "azurerm_cosmosdb_sql_database" "db" {
  name                = "my-database"
  resource_group_name = azurerm_resource_group.rg.name
  account_name        = azurerm_cosmosdb_account.db_account.name
}

resource "azurerm_cosmosdb_sql_container" "db_container" {
  name                  = "my-container"
  resource_group_name   = azurerm_resource_group.rg.name
  account_name          = azurerm_cosmosdb_account.db_account.name
  database_name         = azurerm_cosmosdb_sql_database.db.name

  partition_key_paths   = ["/id"]
  partition_key_version = 1

  indexing_policy {
    indexing_mode = "consistent"

    included_path {
      path = "/*"
    }

    included_path {
      path = "/included/?"
    }

    excluded_path {
      path = "/excluded/?"
    }
  }
}

Provision the Azure Resources

1
2
terraform init
terraform apply

Create and Deploy the Azure Function

1
2
func init
func new

Trigger Function Code

1
2
3
4
5
6
7
8
9
10
11
const { app } = require("@azure/functions");

app.cosmosDB("cosmosDBTrigger", {
  connection: "COSMOSDB_CONNECTION_STRING",
  databaseName: "my-database",
  containerName: "my-container",
  createLeaseContainerIfNotExists: true,
  handler: (documents, context) => {
    context.log(`Cosmos DB function processed ${documents.length} documents`);
  },
});

Deploy the Azure Function

1
func azure functionapp publish cloudengineerskillstffuncapp

Using the Azure Portal to Monitor Azure Function Logs after Cosmos DB

  1. Go into the Azure Portal and in the Resource Groups section you should see the resource group provisioned by Azure
  2. If you select the resource group, go into the Azure Function App resource
  3. Select your cosmosDBTrigger function, go into Logs and wait for Application Insights to connect
  4. Back in your resource group, go into the Azure Cosmos DB account resource
  5. Have a look in the Data Explorer and you should see the Azure Cosmos DB database resource
  6. Within the Azure Cosmos DB database resource you should see the Azure Cosmos DB container resource
  7. Using the Data Explorer create a new item and save it, check the logs for the cosmosDBTrigger function and verify a new log has been created
  8. Try creating, updating, and deleting more items and review the function logs. Note that the change feed monitors for creates and updates but does not track deletions.

Sample items you can add to your database container

1
2
3
4
5
6
7
8
{
  "id": "1",
  "title": "Complete Project Report",
  "description": "Compile all project data and create a comprehensive report covering all phases of the project, including milestones, deliverables, and outcomes.",
  "status": "In Progress",
  "priority": "High",
  "due_date": "2024-09-15"
}
1
2
3
4
5
6
7
8
{
  "id": "2",
  "title": "Design Marketing Campaign",
  "description": "Develop a creative marketing campaign for the upcoming product launch, focusing on social media and email marketing strategies.",
  "status": "Not Started",
  "priority": "Medium",
  "due_date": "2024-10-01"
}

Cleaning up the resources

1
terraform destroy

Further Reading

  • https://learn.microsoft.com/en-us/javascript/api/@azure/functions/cosmosdbv4functionoptions?view=azure-node-latest
This post is licensed under CC BY 4.0 by the author.