Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(azure): connect cae to azure monitor #1486

Merged
merged 9 commits into from
Nov 21, 2024

Conversation

arealmaas
Copy link
Collaborator

@arealmaas arealmaas commented Nov 18, 2024

Description

Related to #1485

Related Issue(s)

Verification

  • Your code builds clean without any errors or warnings
  • Manual testing done (required)
  • Relevant automated test added (if you find this hard, leave it and we'll help out)

Documentation

  • Documentation is updated (either in docs-directory, Altinnpedia or a separate linked PR in altinn-studio-docs., if applicable)

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced a new module for managing container app identities.
    • Enhanced monitoring configurations with new parameters for Application Insights and metrics ingestion.
    • Added functionality for assigning Monitoring Metrics Publisher roles to specified identities.
    • Introduced new resources for data collection endpoints and rules for improved monitoring capabilities.
  • Improvements

    • Updated existing modules to support new identity and monitoring features, enhancing overall deployment capabilities.

Copy link
Contributor

coderabbitai bot commented Nov 18, 2024

📝 Walkthrough
📝 Walkthrough

Walkthrough

The pull request introduces several modifications to Azure Bicep templates, including the addition of new modules for user-assigned managed identities and monitoring metrics publisher roles. The containerAppEnv module is updated with new parameters for Application Insights and managed identities. Additionally, new resources for data collection endpoints and rules are added to enhance monitoring capabilities. Outputs related to metrics ingestion are also introduced. The changes aim to improve deployment configurations while maintaining the existing structure of the Bicep files.

Changes

File Path Change Summary
.azure/infrastructure/main.bicep - Added containerAppIdentity module.
- Updated containerAppEnv module with new parameters.
- Added monitorMetricsPublisherRoles module.
.azure/modules/containerAppEnv/main.bicep - Added parameters: appInsightsConnectionString, monitorMetricsIngestionEndpoint, userAssignedIdentityId.
- Updated API version to 2024-02-02-preview.
.azure/modules/managedIdentity/main.bicep - Added parameters: location, name, tags.
- Introduced managed identity resource and outputs for IDs.
.azure/modules/monitor-workspace/addMetricsPublisherRoles.bicep - Added parameters: monitorWorkspaceName, principalIds.
- Introduced role assignment resources for metrics publishing.
.azure/modules/monitor-workspace/main.bicep - Added resources: dataCollectionEndpoint, dataCollectionRule.
- Introduced outputs: containerAppEnvironmentMetricsIngestionEndpoint, containerAppEnvironmentLogsIngestionEndpoint.

Possibly related PRs

Suggested reviewers

  • oskogstad
  • knuhau
  • MagnusSandgren

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@arealmaas arealmaas marked this pull request as ready for review November 20, 2024 16:18
@arealmaas arealmaas requested review from a team as code owners November 20, 2024 16:18
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Outside diff range and nitpick comments (6)
.azure/modules/managedIdentity/main.bicep (2)

1-8: Add parameter validations for better error handling

Consider adding parameter validations to ensure proper values are provided during deployment:

 @description('The location where the resources will be deployed')
+@allowed([
+  'northeurope'
+  'westeurope'
+  // Add other valid Azure locations
+])
 param location string

 @description('The name of the managed identity')
+@minLength(3)
+@maxLength(128)
+@pattern('^[a-zA-Z0-9-]*$')
 param name string

 @description('Tags to apply to resources')
 param tags object

10-14: Consider adding a resource lock

For managed identities that are critical to your application's functionality, consider adding a resource lock to prevent accidental deletion:

 resource managedIdentity 'Microsoft.ManagedIdentity/userAssignedIdentities@2023-01-31' = {
   name: name
   location: location
   tags: tags
 }
+
+resource managedIdentityLock 'Microsoft.Authorization/locks@2020-05-01' = {
+  name: '${name}-lock'
+  scope: managedIdentity
+  properties: {
+    level: 'CanNotDelete'
+    notes: 'Protect against accidental deletion of managed identity'
+  }
+}
.azure/modules/monitor-workspace/addMetricsPublisherRoles.bicep (3)

1-5: Consider adding parameter validation.

The parameters are well-documented and follow Azure naming conventions. However, consider adding parameter validation to ensure robust deployment.

 @description('The name of the Monitor workspace')
+@minLength(3)
+@maxLength(63)
+@pattern('^[a-zA-Z0-9-]+$')
 param monitorWorkspaceName string

 @description('Array of principal IDs to assign the Monitoring Metrics Publisher role to')
+@minLength(1)
 param principalIds array

17-25: Consider making principalType configurable.

The role assignment implementation is solid, but hardcoding principalType to 'ServicePrincipal' might limit reusability. Consider making it a parameter to support other principal types (like 'User' or 'Group').

 @description('Array of principal IDs to assign the Monitoring Metrics Publisher role to')
 param principalIds array

+@description('Type of principals being assigned roles (ServicePrincipal, User, or Group)')
+@allowed([
+  'ServicePrincipal'
+  'User'
+  'Group'
+])
+param principalType string = 'ServicePrincipal'

 resource roleAssignment 'Microsoft.Authorization/roleAssignments@2022-04-01' = [for principalId in principalIds: {
   scope: monitorWorkspace
   name: guid(monitorWorkspace.id, principalId, monitoringMetricsPublisherRole.id)
   properties: {
     roleDefinitionId: monitoringMetricsPublisherRole.id
     principalId: principalId
-    principalType: 'ServicePrincipal'
+    principalType: principalType
   }
 }]

1-25: Consider enhancing monitoring capabilities.

While the current implementation correctly sets up metrics publishing permissions, consider adding:

  1. Diagnostic settings for audit logging of role assignments
  2. Tags for better resource tracking
  3. Alerts for failed role assignments

This would provide better operational visibility and troubleshooting capabilities.

.azure/modules/containerAppEnv/main.bicep (1)

66-66: Include the protocol in the endpoint URL

Ensure that the endpoint in otlpConfigurations includes the protocol (e.g., https://) to avoid connection issues.

Apply this diff to include the protocol:

-            endpoint: monitorMetricsIngestionEndpoint
+            endpoint: 'https://${monitorMetricsIngestionEndpoint}'
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between cfdae62 and db646bc.

📒 Files selected for processing (5)
  • .azure/infrastructure/main.bicep (1 hunks)
  • .azure/modules/containerAppEnv/main.bicep (2 hunks)
  • .azure/modules/managedIdentity/main.bicep (1 hunks)
  • .azure/modules/monitor-workspace/addMetricsPublisherRoles.bicep (1 hunks)
  • .azure/modules/monitor-workspace/main.bicep (1 hunks)
🔇 Additional comments (15)
.azure/modules/managedIdentity/main.bicep (2)

1-17: Overall implementation looks good!

The managed identity module is well-structured and follows Azure Bicep best practices. It provides the necessary functionality for the CAE to Azure Monitor integration. The suggested improvements around parameter validation and resource locks would add extra safety but are not blocking issues.


16-17: Verify the outputs usage in dependent modules

The outputs look correct. Let's verify how these outputs are being used in the dependent modules:

.azure/modules/monitor-workspace/addMetricsPublisherRoles.bicep (2)

11-15: LGTM! Well-documented built-in role reference.

The role definition is correctly configured using the official Monitoring Metrics Publisher role GUID. The documentation link and description provide excellent context.


7-9: Verify Monitor workspace API version compatibility.

The resource reference is correctly structured. However, let's verify the API version compatibility with your Azure environment.

.azure/modules/monitor-workspace/main.bicep (3)

20-30: Verify 'publicNetworkAccess' setting for 'dataCollectionEndpoint'

In the dataCollectionEndpoint resource (lines 20-30), publicNetworkAccess is set to 'Enabled' (line 26). For security best practices, ensure that this endpoint does not expose sensitive data. If public access is not required, consider setting publicNetworkAccess to 'Disabled'.

Would you like to update the publicNetworkAccess setting? If so, apply this change:

          networkAcls: {
-            publicNetworkAccess: 'Enabled'
+            publicNetworkAccess: 'Disabled'
          }

32-68: Ensure correct configuration of 'dataCollectionRule' for metrics ingestion

The dataCollectionRule resource (lines 32-68) is set up to forward Prometheus metrics to the monitoring account. Please verify the following:

  • Data Sources: The prometheusForwarder data source is defined (lines 38-47). Ensure that this aligns with your Prometheus setup.
  • Destinations: The monitoringAccounts destination references monitorWorkspace.id (lines 48-55). Confirm that this ID is correct.
  • Data Flows: Streams are correctly mapped to destinations (lines 56-65).

Consider validating that all resource references and configurations match your intended monitoring infrastructure.


72-73: Confirm the availability of 'metricsIngestion' and 'logsIngestion' endpoints

The outputs monitorMetricsIngestionEndpoint (line 72) and monitorLogsIngestionEndpoint (line 73) reference dataCollectionEndpoint.properties.metricsIngestion.endpoint and dataCollectionEndpoint.properties.logsIngestion.endpoint, respectively. Ensure that these properties are available and correctly populated in the dataCollectionEndpoint resource.

Run the following script to verify the existence of these properties:

✅ Verification successful

Let me verify the Azure Bicep schema to confirm if these properties are available in the response.


Properties metricsIngestion and logsIngestion are not defined in the resource but accessed in outputs

Based on the verification results, I can see that the dataCollectionEndpoint resource definition doesn't explicitly define the metricsIngestion and logsIngestion properties, but these properties are being accessed in the output declarations. However, these properties are part of the resource's response payload after deployment, not the deployment template properties.

  • The dataCollectionEndpoint resource at line 72-73 attempts to access properties.metricsIngestion.endpoint and properties.logsIngestion.endpoint
  • These properties are not defined in the resource declaration but are automatically populated by Azure after the resource is created
  • This is a valid usage as these properties are available in the resource's runtime response
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify properties of 'dataCollectionEndpoint'

# Locate the 'dataCollectionEndpoint' resource definition
rg -A 15 "resource dataCollectionEndpoint" .azure/modules/monitor-workspace/main.bicep

# Expected: The properties 'metricsIngestion.endpoint' and 'logsIngestion.endpoint' should be present.

Length of output: 546


Script:

#!/bin/bash
# Search for any other references or examples of dataCollectionEndpoint properties
rg -A 5 -B 5 "properties.*Ingestion" .azure/modules/monitor-workspace/

# Also check if there's any documentation or schema references
fd -e md -e json . .azure/modules/monitor-workspace/ -x cat {}

Length of output: 787

.azure/modules/containerAppEnv/main.bicep (6)

50-52: Validate appInsightsConfiguration properties

Ensure that the appInsightsConfiguration block includes all necessary properties and that connectionString is correctly referenced.

Run the following script to confirm the configuration:

✅ Verification successful

appInsightsConfiguration implementation is correct

The appInsightsConfiguration block is properly implemented with the required connectionString property, which correctly references the appInsightsConnectionString parameter. This configuration is part of a Container App Environment resource using the latest API version (2024-02-02-preview) and follows the expected schema.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify `appInsightsConfiguration` usage in the codebase.

# Search for `appInsightsConfiguration` blocks.
rg -A 5 'appInsightsConfiguration' -t bicep

# Check for correct reference to `appInsightsConnectionString`.

Length of output: 73


Script:

#!/bin/bash
# Search for appInsightsConfiguration without file type restriction
rg -A 5 'appInsightsConfiguration'

# Also search for any references to connection string
rg 'appInsightsConnectionString'

Length of output: 67


Script:

#!/bin/bash
# Let's check the content of the specific file and its directory
cat .azure/modules/containerAppEnv/main.bicep

# Also list files in the module directory to see related files
ls -la .azure/modules/containerAppEnv/

Length of output: 2436


53-72: Review openTelemetryConfiguration settings

The openTelemetryConfiguration section is critical for monitoring. Verify that all settings for traces, logs, and metrics are correctly configured and align with your monitoring strategy.

Run the following script to inspect openTelemetryConfiguration:

✅ Verification successful

OpenTelemetry configuration is correctly set up for comprehensive monitoring

The configuration in the Bicep file is properly structured with:

  • Traces and logs configured to send data to Application Insights
  • Metrics configured to send to a dedicated metrics ingestion endpoint
  • Secure OTLP configuration with proper endpoint settings

This aligns with the application's monitoring implementation as evidenced by:

  • All three main services (WebApi, Service, and GraphQL) have proper telemetry configuration
  • Application Insights integration is consistently implemented across services
  • Recent changelog entries show active maintenance of OpenTelemetry features
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find all `openTelemetryConfiguration` instances and review their settings.

# Search for `openTelemetryConfiguration` in Bicep files.
rg -A 15 'openTelemetryConfiguration' -t bicep

Length of output: 76


Script:

#!/bin/bash
# Search for openTelemetryConfiguration in all files since bicep extension is not recognized
rg -A 15 'openTelemetryConfiguration'

# Also search for any other telemetry or monitoring related configurations
rg -A 10 'monitoring|telemetry|appInsights'

Length of output: 25008


16-17: Ensure appInsightsConnectionString is securely managed

The appInsightsConnectionString contains sensitive information. Ensure that it's not hard-coded or exposed in version control. Consider retrieving it from Azure Key Vault or using a secure parameter file.

Run the following script to check for any hard-coded values of appInsightsConnectionString:

✅ Verification successful

Parameter is properly handled as a secure input

The review of the module shows that appInsightsConnectionString is:

  1. Properly defined as an input parameter without any hardcoded values
  2. Used correctly within the appInsightsConfiguration block of the Container App Environment
  3. Not exposed or stored in the bicep file

The module follows security best practices by:

  • Accepting the connection string as a parameter
  • Using it directly in the resource configuration
  • Not storing or exposing sensitive values in the code
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Search for hard-coded `appInsightsConnectionString` values in the codebase.

# Look for assignments of `appInsightsConnectionString` that contain actual connection strings.
rg -U -t yaml -t json -t bicep 'appInsightsConnectionString\s*[:=]\s*["'\''].*["'\'']'

Length of output: 118


Script:

#!/bin/bash
# Search for any potential hardcoded connection strings or references to appInsightsConnectionString
rg -U 'appInsightsConnectionString.*=.*' 

# Also check parameter files that might contain the value
fd -e parameters.json -x cat {}

# Check if it's being referenced from KeyVault
rg -U '@Microsoft.KeyVault' -A 5 -B 5

Length of output: 116


Script:

#!/bin/bash
# Let's check the entire module to understand how this parameter is used
cat .azure/modules/containerAppEnv/main.bicep

# Check for any parameter files in the repository
fd parameters

# Look for any references to this module to see how it's being used
rg -U "containerAppEnv"

Length of output: 2347


19-21: Verify correctness of monitorMetricsIngestionEndpoint

Ensure that the monitorMetricsIngestionEndpoint parameter is correctly specified and that it matches the endpoint provided by Azure Monitor.

Run the following script to confirm the usage and value of monitorMetricsIngestionEndpoint:

✅ Verification successful

monitorMetricsIngestionEndpoint parameter is correctly used in Container Apps Environment configuration

The parameter is properly utilized within the Container Apps Environment resource's OpenTelemetry configuration. It's specifically used as the endpoint for metrics ingestion in the otlpConfigurations array, which is the correct usage according to Azure's Container Apps Environment specifications for metrics monitoring.

  • The parameter is used in .azure/modules/containerAppEnv/main.bicep under openTelemetryConfiguration.destinationsConfiguration.otlpConfigurations
  • It's properly integrated with other monitoring configurations including Application Insights and Log Analytics
  • The parameter's usage aligns with Azure's Container Apps Environment metrics ingestion requirements
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find all usages of `monitorMetricsIngestionEndpoint` and ensure it's correctly referenced.

# Search for `monitorMetricsIngestionEndpoint` in the codebase.
rg 'monitorMetricsIngestionEndpoint'

# Verify that the endpoint value is obtained from the correct source.

Length of output: 36


Script:

#!/bin/bash
# Let's search for any Bicep files that might be referencing this parameter
fd -e bicep -x cat {} \; | rg -A 5 -B 5 'monitorMetricsIngestionEndpoint'

# Also search for any workflow or pipeline files that might be setting this parameter
fd -e yaml -e yml | xargs rg 'monitorMetricsIngestionEndpoint'

Length of output: 139


Script:

#!/bin/bash
# Let's examine the specific containerAppEnv module and its parent templates
cat .azure/modules/containerAppEnv/main.bicep

# Also check for any parameter files that might be setting this value
fd -e parameters.json -e parameters.bicep | xargs cat

Length of output: 2277


32-37: Assign necessary permissions to the managed identity

After adding the identity block, ensure the user-assigned managed identity has the required permissions to access resources like Application Insights and Azure Monitor.

Run the following script to identify where the managed identity is being assigned roles:

✅ Verification successful

The managed identity already has the necessary permissions configured

Looking at the infrastructure code, the necessary permissions are already being assigned through the monitorMetricsPublisherRoles module, which grants the container app's managed identity the Monitoring Metrics Publisher role. This is exactly what's needed for the managed identity to publish metrics to Azure Monitor.

Specifically:

  • The managed identity is created via containerAppIdentity module
  • The monitorMetricsPublisherRoles module assigns the required role to this identity
  • The identity is properly configured in the container app environment
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for role assignments to the managed identity.

# Search for role assignments involving `userAssignedIdentityId`.
rg -A 5 'roleAssignments.*principalId:\s*userAssignedIdentityId' -t bicep

Length of output: 105


Script:

#!/bin/bash
# Search for role assignments in bicep files
rg -A 5 'roleAssignments.*principalId' ./*.bicep ./**/*.bicep

# Search for any references to role assignments or permissions
rg -A 5 'roleAssignment|roleDefinition' ./*.bicep ./**/*.bicep

# Look for files that might contain role definitions
fd -e bicep -x cat {} \; | grep -i "role"

Length of output: 387


Script:

#!/bin/bash
# First, let's find all bicep files in the repository
fd ".*\.bicep$"

# Then search for role assignments and permissions in the found files
rg -A 5 'roleAssignment|roleDefinition|role:' .azure/

# Look specifically in the containerAppEnv module and related files
ls -R .azure/modules/containerAppEnv/

Length of output: 8057


Script:

#!/bin/bash
# Let's examine the main.bicep file in containerAppEnv module
cat .azure/modules/containerAppEnv/main.bicep

# Check if there are any other bicep files that reference containerAppEnv
rg -l "containerAppEnv" .azure/

Length of output: 4346


Script:

#!/bin/bash
# Let's check the infrastructure main.bicep file as it might contain role assignments
cat .azure/infrastructure/main.bicep

# Also check the monitor workspace configuration since we're dealing with Application Insights and Azure Monitor
cat .azure/modules/monitor-workspace/main.bicep

Length of output: 12859


22-24: Confirm the definition of userAssignedIdentityId

Ensure that userAssignedIdentityId is defined and properly references an existing user-assigned managed identity.

Run the following script to check the definition and usage of userAssignedIdentityId:

✅ Verification successful

userAssignedIdentityId is properly defined and used

The parameter is correctly used in the Container App Environment module. The identity is created through the containerAppIdentity module and its ID is properly passed to the Container App Environment. The managed identity is also granted the necessary Monitor Metrics Publisher role.

Key validations:

  • Identity is created via containerAppIdentity module
  • Identity ID is passed correctly to Container App Environment
  • Required roles are assigned through monitorMetricsPublisherRoles module
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that `userAssignedIdentityId` is defined and correctly used.

# Search for the resource definition of the user-assigned identity.
rg -A 5 'resource.*userAssignedIdentity.*' -t bicep

# Check for parameter definitions.
rg 'param userAssignedIdentityId' -t bicep

Length of output: 158


Script:

#!/bin/bash
# Search for the resource definition and usage of user-assigned identity without file type restriction
rg -A 5 'resource.*userAssignedIdentity.*'

# Check for parameter definitions
rg 'param userAssignedIdentityId'

# Find all bicep files to understand the infrastructure setup
fd -e bicep

Length of output: 94


Script:

#!/bin/bash
# Let's first check the content of the containerAppEnv module to understand the context
cat .azure/modules/containerAppEnv/main.bicep

# Find any references to this module in other bicep files
rg 'containerAppEnv'

# Check for any user identity related configurations in the entire codebase
rg -i 'userAssignedIdentity'

Length of output: 2271


Script:

#!/bin/bash
# Let's check for references to this module and how the userAssignedIdentityId is passed
find . -type f -name "*.bicep" -exec grep -l "containerAppEnv" {} \;

# Look for user assigned identity resource definitions
find . -type f -name "*.bicep" -exec grep -l "type.*UserAssigned" {} \;

# Check the content of any main deployment files
cat .azure/main.bicep 2>/dev/null || true

Length of output: 824


Script:

#!/bin/bash
# Let's check the infrastructure main file which likely defines the user identity
cat .azure/infrastructure/main.bicep

# Also check one of the application files to see how the containerAppEnv module is used
cat .azure/applications/web-api-eu/main.bicep

Length of output: 14916

.azure/infrastructure/main.bicep (2)

302-304: ⚠️ Potential issue

Update the containerAppEnv module to accept new parameters

New parameters appInsightsConnectionString, monitorMetricsIngestionEndpoint, and userAssignedIdentityId are being passed to the containerAppEnv module. Verify that the module ../modules/containerAppEnv/main.bicep is updated to accept these new parameters.

Run the following script to confirm the module parameters:


285-293: Verify the existence and outputs of the managedIdentity module

The module containerAppIdentity references ../modules/managedIdentity/main.bicep and expects outputs managedIdentityId and managedIdentityPrincipalId. Ensure that this module exists and that these outputs are correctly defined.

Run the following script to confirm the module and outputs:

✅ Verification successful

Let me verify the correct path by searching for the bicep module file.


Let me try one more search with a different approach to locate any bicep files and their content.


Based on the code review, I can now provide a final response since I found the managed identity module and can verify its outputs.

The managed identity module exists and is correctly defined

The module ../modules/managedIdentity/main.bicep exists and correctly outputs both:

  • managedIdentityId as string
  • managedIdentityPrincipalId as string

These outputs match the expected outputs referenced in the containerAppIdentity module.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the existence of the managedIdentity module and its outputs.

# Test: Check if the managedIdentity module file exists.
if [ -f "../modules/managedIdentity/main.bicep" ]; then
  echo "ManagedIdentity module exists."
else
  echo "ManagedIdentity module does not exist."
fi

# Test: Check for the required outputs in the module file.
ast-grep --pattern $'output managedIdentityId string\noutput managedIdentityPrincipalId string' ../modules/managedIdentity/main.bicep

Length of output: 356


Script:

#!/bin/bash
# Search for the managedIdentity bicep module file
fd "main.bicep" --type f

# Check content of any managedIdentity related bicep files
rg -l "managedIdentity" -g "*.bicep"

Length of output: 210


Script:

#!/bin/bash
# List all .bicep files in the repository
find . -name "*.bicep" -type f

# If any bicep files are found, check their content
find . -name "*.bicep" -type f -exec cat {} \;

Length of output: 103962

.azure/modules/containerAppEnv/main.bicep Show resolved Hide resolved
.azure/infrastructure/main.bicep Show resolved Hide resolved
oskogstad
oskogstad previously approved these changes Nov 20, 2024
Copy link

sonarcloud bot commented Nov 21, 2024

Quality Gate Failed Quality Gate failed

Failed conditions
3 Security Hotspots

See analysis details on SonarQube Cloud

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Outside diff range and nitpick comments (1)
.azure/infrastructure/main.bicep (1)

302-304: LGTM! Consider monitoring data retention

The Container App Environment is correctly configured with Application Insights and Azure Monitor integration. The managed identity will be used for secure metrics ingestion.

Consider defining data retention policies for the monitoring data to manage costs and compliance requirements. You can configure this in the Azure Monitor workspace settings.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between db646bc and 40e06b6.

📒 Files selected for processing (2)
  • .azure/infrastructure/main.bicep (1 hunks)
  • .azure/modules/monitor-workspace/main.bicep (1 hunks)
🔇 Additional comments (7)
.azure/modules/monitor-workspace/main.bicep (5)

Line range hint 1-73: Implementation looks good with some considerations

The Azure Monitor integration implementation is well-structured and complete. However, before final approval, please ensure:

  1. Security implications of public network access are reviewed
  2. Prometheus metrics configuration matches monitoring requirements
  3. Integration with dependent modules is verified

Once these are addressed, the changes look good to proceed.


Line range hint 11-13: Consider addressing the TODO comment

Since this PR implements the connection to the monitor workspace (as per PR objectives), we should review if this TODO can be addressed and if publicNetworkAccess should still be 'Enabled'.

✅ Verification successful

The TODO comment is still relevant as issue #1462 remains open

The issue #1462 "Add an Azure Monitor Workspace in our IAC" is still open, indicating that the TODO comment about ensuring connection and reviewing public network access settings is still relevant and should be maintained.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if issue #1462 is still open
gh issue view 1462 --json state,title

Length of output: 108


72-73: Verify output usage in dependent modules

The new outputs for metrics and logs ingestion endpoints are added. Based on the AI summary, these should be used by the containerAppEnv module.


32-68: Verify Prometheus metrics configuration

The Data Collection Rule is set up for Prometheus metrics collection. The configuration looks correct, but please ensure:

  1. The stream type 'Microsoft-PrometheusMetrics' matches your monitoring requirements
  2. The data flow configuration aligns with the metrics you plan to collect from the Container App Environment
✅ Verification successful

Prometheus metrics configuration is correctly implemented

The Data Collection Rule configuration is the only instance of Prometheus metrics setup in the Azure infrastructure code, and it follows the correct pattern:

  • Uses standard stream type 'Microsoft-PrometheusMetrics'
  • Properly configures the prometheusForwarder data source
  • Correctly sets up the data flow from source to monitoring account destination
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Look for other Prometheus configurations in the codebase for consistency
rg -A 5 'Microsoft-PrometheusMetrics' --type bicep

Length of output: 80


Script:

#!/bin/bash
# Look for Prometheus configurations using regular ripgrep without file type restriction
rg -A 5 'Microsoft-PrometheusMetrics'

Length of output: 37


Script:

#!/bin/bash
# Search for any Prometheus-related configurations in the codebase
rg -i 'prometheus' .azure/

Length of output: 352


20-30: Review security implications of public network access

The Data Collection Endpoint is configured with public network access enabled. While this might be necessary for the initial setup, consider:

  1. If this aligns with security requirements
  2. If network restrictions should be implemented
  3. If private endpoints should be used instead
.azure/infrastructure/main.bicep (2)

285-293: LGTM! Verify managed identity permissions

The managed identity module is well-structured and follows naming conventions. The identity will be used for Azure Monitor metrics ingestion.

Let's verify the managed identity's role assignments:

✅ Verification successful

Role assignments are properly configured for the managed identity

The managed identity setup is correctly implemented with appropriate role assignments:

  • The managed identity is created via containerAppIdentity module
  • The monitorMetricsPublisherRoles module assigns the necessary monitoring roles to this identity
  • The identity is properly linked to the Container App Environment for metrics ingestion

The implementation follows a secure pattern where:

  1. The managed identity is created first
  2. Its ID is passed to the Container App Environment
  3. Required monitoring roles are assigned via dedicated role assignment module
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify role assignments for the managed identity
# Look for any existing role assignments that might conflict or complement the new one

rg "roleAssignment.*managedIdentity" -A 3

Length of output: 43


Script:

#!/bin/bash
# Let's check the entire infrastructure directory for role assignments and managed identity references
# First, find all bicep files
fd -e bicep -x cat {} | grep -A 5 -B 5 "roleAssignment\|managedIdentity"

# Also specifically check the modules directory for role assignments
fd -e bicep . .azure/infrastructure/modules/ -x cat {}

Length of output: 253


Script:

#!/bin/bash
# Let's first check what bicep files exist in the repository
fd -e bicep

# Then examine the content of main.bicep and any role assignment modules
cat .azure/infrastructure/main.bicep

Length of output: 10785


310-317: LGTM! Verify role definition scope

The Monitoring Metrics Publisher role is correctly assigned to the managed identity for metrics ingestion.

Let's verify the role definition and scope:

@arealmaas arealmaas merged commit cf18b90 into main Nov 21, 2024
18 of 19 checks passed
@arealmaas arealmaas deleted the feat/connect-cae-to-azure-monitor branch November 21, 2024 13:05
arealmaas pushed a commit that referenced this pull request Nov 21, 2024
🤖 I have created a release *beep* *boop*
---


##
[1.38.0](v1.37.0...v1.38.0)
(2024-11-21)


### Features

* **azure:** connect cae to azure monitor
([#1486](#1486))
([cf18b90](cf18b90))

---
This PR was generated with [Release
Please](https://github.com/googleapis/release-please). See
[documentation](https://github.com/googleapis/release-please#release-please).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants