Skip to content

Commit

Permalink
Merge pull request #24 from seesharprun/rework
Browse files Browse the repository at this point in the history
Rework
  • Loading branch information
seesharprun authored Oct 22, 2024
2 parents 9c5badd + 7e4e5df commit b877aed
Show file tree
Hide file tree
Showing 15 changed files with 136 additions and 124 deletions.
2 changes: 1 addition & 1 deletion .devcontainer/devcontainer.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"image": "mcr.microsoft.com/devcontainers/javascript-node:22",
"image": "mcr.microsoft.com/devcontainers/javascript-node:20",
"features": {
"ghcr.io/devcontainers/features/azure-cli:1": {},
"ghcr.io/devcontainers/features/docker-in-docker:2": {},
Expand Down
46 changes: 46 additions & 0 deletions .github/workflows/azure-dev.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
# Run when commits are pushed to main
on:
workflow_dispatch:
push:
# Run when commits are pushed to mainline branch (main or master)
# Set this to the mainline branch you are using
branches:
- main

# Set up permissions for deploying with secretless Azure federated credentials
# https://learn.microsoft.com/en-us/azure/developer/github/connect-from-azure?tabs=azure-portal%2Clinux#set-up-azure-login-with-openid-connect-authentication
permissions:
id-token: write
contents: read


jobs:
build:
runs-on: ubuntu-latest
env:
AZURE_CLIENT_ID: ${{ vars.AZURE_CLIENT_ID }}
AZURE_TENANT_ID: ${{ vars.AZURE_TENANT_ID }}
AZURE_SUBSCRIPTION_ID: ${{ vars.AZURE_SUBSCRIPTION_ID }}
AZURE_ENV_NAME: ${{ vars.AZURE_ENV_NAME }}
AZURE_LOCATION: ${{ vars.AZURE_LOCATION }}
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Install azd
uses: Azure/[email protected]
- name: Log in with Azure (Federated Credentials)
run: |
azd auth login `
--client-id "$Env:AZURE_CLIENT_ID" `
--federated-credential-provider "github" `
--tenant-id "$Env:AZURE_TENANT_ID"
shell: pwsh


- name: Provision Infrastructure
run: azd provision --no-prompt
env:
AZD_INITIAL_ENVIRONMENT_CONFIG: ${{ secrets.AZD_INITIAL_ENVIRONMENT_CONFIG }}

- name: Deploy Application
run: azd deploy --no-prompt
2 changes: 2 additions & 0 deletions azure.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ services:
docker:
path: ./Dockerfile
context: ./
pipeline:
provider: github
hooks:
postprovision:
windows:
Expand Down
43 changes: 19 additions & 24 deletions infra/app/database.bicep
Original file line number Diff line number Diff line change
Expand Up @@ -10,36 +10,31 @@ param appPrincipalId string
@description('Id of the user principals to assign database and application roles.')
param userPrincipalId string = ''

var database = {
name: 'cosmicworks' // Based on AdventureWorksLT data set
}

var containers = [
{
name: 'products' // Set of products
partitionKeyPaths: [
'/category' // Partition on the product category
]
autoscale: true // Scale at the container level
throughput: 1000 // Enable autoscale with a minimum of 100 RUs and a maximum of 1,000 RUs
}
]

module cosmosDbAccount 'br/public:avm/res/document-db/database-account:0.6.1' = {
name: 'cosmos-db-account'
params: {
name: accountName
location: location
locations: [
{
failoverPriority: 0
locationName: location
isZoneRedundant: false
}
]
tags: tags
disableKeyBasedMetadataWriteAccess: true
disableLocalAuth: true
capabilitiesToAdd: [
'EnableServerless'
]
sqlRoleDefinitions: [
{
name: 'nosql-data-plane-contributor'
dataAction: [
'Microsoft.DocumentDB/databaseAccounts/readMetadata' // Read account metadata
'Microsoft.DocumentDB/databaseAccounts/sqlDatabases/containers/items/*' // Create items
'Microsoft.DocumentDB/databaseAccounts/sqlDatabases/containers/*' // Manage items
'Microsoft.DocumentDB/databaseAccounts/readMetadata'
'Microsoft.DocumentDB/databaseAccounts/sqlDatabases/containers/items/*'
'Microsoft.DocumentDB/databaseAccounts/sqlDatabases/containers/*'
]
}
]
Expand All @@ -55,18 +50,18 @@ module cosmosDbAccount 'br/public:avm/res/document-db/database-account:0.6.1' =
)
sqlDatabases: [
{
name: database.name
name: 'cosmicworks'
containers: [
for container in containers: {
name: container.name
paths: container.partitionKeyPaths
autoscaleSettingsMaxThroughput: container.throughput
{
name: 'products'
paths: [
'/category'
]
}
]
}
]
}
}

output name string = cosmosDbAccount.outputs.name
output endpoint string = cosmosDbAccount.outputs.endpoint
1 change: 0 additions & 1 deletion infra/app/identity.bicep
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ module userAssignedIdentity 'br/public:avm/res/managed-identity/user-assigned-id
}
}

output name string = userAssignedIdentity.outputs.name
output resourceId string = userAssignedIdentity.outputs.resourceId
output principalId string = userAssignedIdentity.outputs.principalId
output clientId string = userAssignedIdentity.outputs.clientId
1 change: 0 additions & 1 deletion infra/app/registry.bicep
Original file line number Diff line number Diff line change
Expand Up @@ -32,5 +32,4 @@ module registryUserAssignment 'br/public:avm/ptn/authorization/resource-role-ass
}
}

output name string = containerRegistry.outputs.name
output endpoint string = containerRegistry.outputs.loginServer
30 changes: 18 additions & 12 deletions infra/app/web.bicep
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,13 @@ module containerAppsJsApp 'br/public:avm/res/app/container-app:0.9.0' = {
tags: union(tags, { 'azd-service-name': jsServiceTag })
ingressTargetPort: 3000
ingressExternal: true
ingressTransport: 'auto'
ingressTransport: 'http'
corsPolicy: {
allowCredentials: true
allowedOrigins: [
'*'
]
}
managedIdentities: {
systemAssigned: false
userAssignedResourceIds: [
Expand All @@ -71,8 +77,8 @@ module containerAppsJsApp 'br/public:avm/res/app/container-app:0.9.0' = {
image: 'mcr.microsoft.com/azuredocs/containerapps-helloworld:latest'
name: 'web-front-end'
resources: {
cpu: '0.25'
memory: '0.5Gi'
cpu: '1'
memory: '2Gi'
}
env: [
{
Expand All @@ -97,7 +103,13 @@ module containerAppsTsApp 'br/public:avm/res/app/container-app:0.9.0' = {
tags: union(tags, { 'azd-service-name': tsServiceTag })
ingressTargetPort: 3000
ingressExternal: true
ingressTransport: 'auto'
ingressTransport: 'http'
corsPolicy: {
allowCredentials: true
allowedOrigins: [
'*'
]
}
managedIdentities: {
systemAssigned: false
userAssignedResourceIds: [
Expand All @@ -121,8 +133,8 @@ module containerAppsTsApp 'br/public:avm/res/app/container-app:0.9.0' = {
image: 'mcr.microsoft.com/azuredocs/containerapps-helloworld:latest'
name: 'web-front-end'
resources: {
cpu: '0.25'
memory: '0.5Gi'
cpu: '1'
memory: '2Gi'
}
env: [
{
Expand All @@ -138,9 +150,3 @@ module containerAppsTsApp 'br/public:avm/res/app/container-app:0.9.0' = {
]
}
}

output jsEndpoint string = 'https://${containerAppsJsApp.outputs.fqdn}'
output tsEndpoint string = 'https://${containerAppsTsApp.outputs.fqdn}'
output envName string = containerAppsJsApp.outputs.name
output jsSystemAssignedManagedIdentityPrincipalId string = containerAppsJsApp.outputs.systemAssignedMIPrincipalId
output tsSystemAssignedManagedIdentityPrincipalId string = containerAppsTsApp.outputs.systemAssignedMIPrincipalId
23 changes: 2 additions & 21 deletions infra/main.bicep
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
targetScope = 'subscription'
targetScope = 'resourceGroup'

@minLength(1)
@maxLength(64)
Expand All @@ -25,21 +25,14 @@ param typeScriptServiceName string = 'typescript-web'
param javaScriptServiceName string = 'javascript-web'

var abbreviations = loadJsonContent('abbreviations.json')
var resourceToken = toLower(uniqueString(subscription().id, environmentName, location))
var resourceToken = toLower(uniqueString(resourceGroup().id, environmentName, location))
var tags = {
'azd-env-name': environmentName
repo: 'https://github.com/azure-samples/cosmos-db-nosql-nodejs-quickstart'
}

resource resourceGroup 'Microsoft.Resources/resourceGroups@2022-09-01' = {
name: environmentName
location: location
tags: tags
}

module identity 'app/identity.bicep' = {
name: 'identity'
scope: resourceGroup
params: {
identityName: '${abbreviations.userAssignedIdentity}-${resourceToken}'
location: location
Expand All @@ -49,7 +42,6 @@ module identity 'app/identity.bicep' = {

module database 'app/database.bicep' = {
name: 'database'
scope: resourceGroup
params: {
accountName: !empty(cosmosDbAccountName) ? cosmosDbAccountName : '${abbreviations.cosmosDbAccount}-${resourceToken}'
location: location
Expand All @@ -61,7 +53,6 @@ module database 'app/database.bicep' = {

module registry 'app/registry.bicep' = {
name: 'registry'
scope: resourceGroup
params: {
registryName: !empty(containerRegistryName) ? containerRegistryName : '${abbreviations.containerRegistry}${resourceToken}'
location: location
Expand All @@ -71,7 +62,6 @@ module registry 'app/registry.bicep' = {

module web 'app/web.bicep' = {
name: 'web'
scope: resourceGroup
params: {
workspaceName: !empty(logWorkspaceName) ? logWorkspaceName : '${abbreviations.logAnalyticsWorkspace}-${resourceToken}'
envName: !empty(containerAppsEnvName) ? containerAppsEnvName : '${abbreviations.containerAppsEnv}-${resourceToken}'
Expand All @@ -87,14 +77,5 @@ module web 'app/web.bicep' = {
}
}

// Database outputs
output AZURE_COSMOS_DB_NOSQL_ENDPOINT string = database.outputs.endpoint

// Container outputs
output AZURE_CONTAINER_REGISTRY_ENDPOINT string = registry.outputs.endpoint
output AZURE_CONTAINER_REGISTRY_NAME string = registry.outputs.name

// Application outputs
output AZURE_CONTAINER_APP_JS_ENDPOINT string = web.outputs.jsEndpoint
output AZURE_CONTAINER_APP_TS_ENDPOINT string = web.outputs.tsEndpoint
output AZURE_CONTAINER_ENVIRONMENT_NAME string = web.outputs.envName
86 changes: 26 additions & 60 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,83 +13,49 @@ products:

# Quickstart: Azure Cosmos DB for NoSQL client library for Node.js

This is a simple Express web application to illustrate common basic usage of Azure Cosmos DB for NoSQL's client library for Node.js. This sample application accesses an existing account, database, and container using the [`@azure/cosmos`](https://www.npmjs.com/package/@azure/cosmos) and [`@azure/identity`](https://www.npmjs.com/package/@azure/identity) packages. Modify the source code and leverage the Infrastructure as Code (IaC) Bicep assets to get up and running quickly.

When you are finished, you will have a fully functional web application deployed to Azure.

![Screenshot of the deployed web application.](assets/web.png)
This is a simple Express web application to illustrate common basic usage of Azure Cosmos DB for NoSQL's client library for Node.js. This sample application accesses an existing account, database, and container using the [`@azure/cosmos`](https://www.npmjs.com/package/@azure/cosmos) and [`@azure/identity`](https://www.npmjs.com/package/@azure/identity) packages.

### Prerequisites

> This template will create infrastructure and deploy code to Azure. If you don't have an Azure Subscription, you can sign up for a [free account here](https://azure.microsoft.com/free/). Make sure you have the contributor role in the Azure subscription.
The following prerequisites are required to use this application. Please ensure that you have them all installed locally.

- [Docker](https://www.docker.com/)
- [Azure Developer CLI](https://aka.ms/azd-install)
- [Node.js 22 or newer](https://nodejs.org/)

### Quickstart

To learn how to get started with any template, follow the steps in [this quickstart](https://learn.microsoft.com/azure/cosmos-db/nosql/quickstart-nodejs) with this template (`cosmos-db-nosql-nodejs-quickstart`).

This quickstart will show you how to authenticate on Azure, initialize using a template, provision infrastructure and deploy code on Azure via the following commands:

```bash
# Log in to azd. Only required once per-install.
azd auth login

# First-time project setup. Initialize a project in the current directory, using this template.
# Omit the --template argument if you are running in a development container.
azd init --template cosmos-db-nosql-nodejs-quickstart

# Provision and deploy to Azure
azd up
```

### Application Architecture

This application utilizes the following Azure resources:
1. Log in to Azure Developer CLI.

- [**Azure Container Registry**](https://learn.microsoft.com/azure/container-registry/)
- This services hosts the container image.
- [**Azure Container Apps**](https://learn.microsoft.com/azure/container-apps/)
- This service hosts the Express web application.
- [**Azure Cosmos DB for NoSQL**](https://learn.microsoft.com/azure/cosmos-db/)
- This service stores the NoSQL data.
```bash
azd auth login
```

Here's a high level architecture diagram that illustrates these components. Notice that these are all contained within a single **resource group**, that will be created for you when you create the resources.
> [!TIP]
> This is only required once per-install.

```mermaid
%%{ init: { 'theme': 'base', 'themeVariables': { 'background': '#243A5E', 'primaryColor': '#50E6FF', 'primaryBorderColor': '#243A5E', 'tertiaryBorderColor': '#50E6FF', 'tertiaryColor': '#243A5E', 'fontFamily': 'Segoe UI', 'lineColor': '#FFFFFF', 'primaryTextColor': '#243A5E', 'tertiaryTextColor': '#FFFFFF' } }}%%
flowchart TB
subgraph web-app[Azure Container Apps]
app-framework(["Node.js 22 | Express 4"])
end
subgraph cosmos-db[Azure Cosmos DB]
subgraph database-cosmicworks[Database: cosmicworks]
subgraph container-products[Container: products]
prd-yamba[Product: Yamba Surfboard]
prd-kiama-classic[Product: Kiama Classic Surfboard]
end
end
end
web-app --> cosmos-db
```
1. Initialize this template (`cosmos-db-nosql-nodejs-quickstart`) using `azd init`

### Cost of provisioning and deploying this template
```bash
azd init --template cosmos-db-nosql-nodejs-quickstart
```

This template provisions resources to an Azure subscription that you will select upon provisioning them. Refer to the [Pricing calculator for Microsoft Azure](https://azure.microsoft.com/pricing/calculator/) to estimate the cost you might incur when this template is running on Azure and, if needed, update the included Azure resource definitions found in [`infra/main.bicep`](infra/main.bicep) to suit your needs.
1. Ensure that **Docker** is running in your environment.

### Application Code
1. Use `azd up` to provision your Azure infrastructure and deploy the web application to Azure.

This template is structured to follow the [Azure Developer CLI](https://aka.ms/azure-dev/overview). You can learn more about `azd` architecture in [the official documentation](https://learn.microsoft.com/azure/developer/azure-developer-cli/make-azd-compatible?pivots=azd-create#understand-the-azd-architecture).
```bash
azd up
```

### Next Steps
1. Observed the deployed web application

At this point, you have a complete application deployed on Azure. But there is much more that the Azure Developer CLI can do. These next steps will introduce you to additional commands that will make creating applications on Azure much easier. Using the Azure Developer CLI, you can setup your pipelines, monitor your application, test and debug locally.
![Screenshot of the deployed web application.](assets/web.png)

- [`azd pipeline config`](https://learn.microsoft.com/azure/developer/azure-developer-cli/configure-devops-pipeline?tabs=GitHub) - to configure a CI/CD pipeline (using GitHub Actions or Azure DevOps) to deploy your application whenever code is pushed to the main branch.
1. (Optionally) Run this web application locally in either the `src/js` or `src/ts` folders:

- [Run and Debug Locally](https://learn.microsoft.com/azure/developer/azure-developer-cli/debug?pivots=ide-vs-code) - using Visual Studio Code and the Azure Developer CLI extension
```bash
npm install
npm run dev
```

- [`azd down`](https://learn.microsoft.com/azure/developer/azure-developer-cli/reference#azd-down) - to delete all the Azure resources created with this template
> [!IMPORTANT]
> When your Azure infrastructure is provisioned, the endpoint for your deployed Azure Cosmos DB for NoSQL account is automatically saved in the *.env* file for both the JavaScript and TypeScript local projects to make debugging easier.
1 change: 1 addition & 0 deletions src/js/.webappignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
.env
Loading

0 comments on commit b877aed

Please sign in to comment.