Skip to content

Latest commit

 

History

History
435 lines (309 loc) · 13 KB

test.md

File metadata and controls

435 lines (309 loc) · 13 KB

If you know the client_id (appId) az ad sp show --id <CLIENT_ID> --query "id" -o tsv

Get the SP object ID that the cluster is currently using

az aks show -g xxxxx-test -n xxxxx-xxx-test-k8s
--query "servicePrincipalProfile.clientId" -o tsv

Then get its object ID

SP_APP_ID=$(az aks show -g xxxxxx-main-test -n xxxxxx-main-test-k8s
--query "servicePrincipalProfile.clientId" -o tsv)

az ad sp show --id "$SP_APP_ID" --query "id" -o tsv

Step 1 — Export ALL current SP roles (run first, save output)

Save to file — this is your rollback reference

az role assignment list
--assignee d
--all
--query "[].{Role:roleDefinitionName, Scope:scope}"
-o json > sp-roles-backup.json

Also view in table

cat sp-roles-backup.json | az rest --method get
--body @- 2>/dev/null ||
az role assignment list
--assignee d
--all
--query "[].{Role:roleDefinitionName, Scope:scope}"
-o table

Step 2 — Enable Managed Identity on the cluster

Disable monitoring first

az aks disable-addons -a monitoring
-g xxxx-main-test
-n xxxx-main-test-k8s

Switch to SystemAssigned MI

az aks update
-g xxxx-main-test
-n xxxx-main-test-k8s
--enable-managed-identity

Wait ~5 min

Step 3 — Get new MI principal IDs

SUB="4"

MI=$(az aks show -g xxxx-main-test -n xxxx-main-test-k8s
--query "identity.principalId" -o tsv) echo "Control plane MI: $MI"

KUBELET_MI=$(az aks show -g xxxx-main-test -n xxxx-main-test-k8s
--query "identityProfile.kubeletidentity.objectId" -o tsv) echo "Kubelet MI: $KUBELET_MI"

Step 4 — Reassign ALL roles to MI SUB=""

Contributor — main RG

az role assignment create --assignee "$MI" --role "Contributor"
--scope "/subscriptions/${SUB}/resourceGroups/xxxx-main-test"

Tel-IT-AccessAdministrator — all RGs it had

for RG in
"xxx-main-test"
"xxx-main-test-acr-rg"
"xxx-test-dns"
"xxx-main-test-runner-rg"
"TEST_RG"
"Cloud-shell-storage-westeurope"
"rg-ci-vnet"
"rg-automation"
"xxxx-test-lim"
"xxxx-gpu-training"
"xxxx-main-test-node"; do echo "Assigning Tel-IT-AccessAdministrator → $RG" az role assignment create --assignee "$MI"
--role "Tel-IT-AccessAdministrator"
--scope "/subscriptions/${SUB}/resourceGroups/${RG}"
--output none 2>/dev/null || echo " Skipped (already exists or no access)" done

AcrPull — assign to KUBELET MI

az role assignment create --assignee "$KUBELET_MI" --role "AcrPull"
--scope "/subscriptions/${SUB}/resourceGroups/xxxx-main-test-acr-rg/providers/Microsoft.ContainerRegistry/registries/sem"

Key Vault Secrets Officer

az role assignment create --assignee "$MI" --role "Key Vault Secrets Officer"
--scope "/subscriptions/${SUB}/resourceGroups/xxxx-main-test/providers/Microsoft.KeyVault/vaults/xxxxteststkv1"

Monitoring Metrics Publisher — skip if MSI monitoring re-enabled below

az role assignment create --assignee "$MI" --role "Monitoring Metrics Publisher"
--scope "/subscriptions/${SUB}/resourceGroups/xxxx-main-test/providers/Microsoft.ContainerService/managedClusters/xxxx-main-test-k8s"

Step 5 — Re-enable monitoring with MSI

WORKSPACE_ID=$(az monitor log-analytics workspace list
-g xxxx-main-test --query "[0].id" -o tsv)

az aks enable-addons -a monitoring
-g xxxx-main-test
-n xxxx-main-test-k8s
--workspace-resource-id "$WORKSPACE_ID"

Step 6 — Verify

All MI roles

az role assignment list --assignee "$MI" --all
--query "[].{Role:roleDefinitionName, Scope:scope}" -o table

Kubelet roles

az role assignment list --assignee "$KUBELET_MI" --all
--query "[].{Role:roleDefinitionName, Scope:scope}" -o table

Cluster working

kubectl get nodes kubectl get pods -A

Step 7 — Retire the SP (only after everything verified)

---tf changes

Exact Changes for SP → MI Migration File: main.tf Line Action Code 15 ✅ ADDED oidc_issuer_enabled = true # ADDED 2026-08-25: drift fix 38-40 ❌ REMOVED service_principal { client_id = ... client_secret = ... } 41-47 ✅ ADDED identity { type = "SystemAssigned" }

File: variables.tf Line Action Code ~45-50 ❌ COMMENTED OUT variable "client_id" { ... } ~52-57 ❌ COMMENTED OUT variable "client_secret" { ... }

File: main.tf (root) Line Action Code ~25 ❌ COMMENTED OUT # client_id = var.client_id ~26 ❌ COMMENTED OUT # client_secret = var.client_secret

File: variables.tf (root) Line Action Code ~10-15 ✅ DESCRIPTION UPDATED description = "SP client_id — Terraform provider auth only, NOT used by AKS" ~17-22 ✅ DESCRIPTION UPDATED description = "SP client_secret — Terraform provider auth only, NOT used by AKS"

Files NOT changed File Reason .env SP vars not stored here .gitlab-ci.yml ARM_CLIENT_ID/ARM_CLIENT_SECRET still needed for Terraform provider auth terraform.tfvars SP values kept — used for provider auth only

kubectl get pods -n kube-system 2>&1 | grep -E "oms|monitor|agent"

Check omsagent pods are running kubectl get pods -n kube-system | grep oms

Check omsagent is NOT crashing

kubectl logs -n kube-system -l component=oms-agent --tail=50

Verify workspace has data — check last heartbeat

az monitor log-analytics query
--workspace fenixdev-main-dev
--analytics-query "Heartbeat | summarize max(TimeGenerated) by Computer"
--resource-group fenixdev-main-dev


WS_ID=$(az monitor log-analytics workspace show -g fenixdev-main-dev -n fenixdev-main-dev --query customerId -o tsv) && echo "Workspace ID: $WS_ID" && az monitor log-analytics query --workspace "$WS_ID" --analytics-query "Heartbeat | summarize max(TimeGenerated) by Computer | take 5" -o table 2>&1

WS_ID=$(az monitor log-analytics workspace show -g fenixdev-main-dev -n fenixdev-main-dev --query customerId -o tsv) && echo "Workspace ID: $WS_ID" && az monitor log-analytics query --workspace "$WS_ID" --analytics-query "Heartbeat | summarize max(TimeGenerated) by Computer | take 5" -o table 2>&1


kubectl exec -n kube-system ama-logs-96vb8 -c ama-logs -- tail -30 /var/opt/microsoft/linuxmonagent/log/mdsd.err 2>&1

kubectl exec -n kube-system ama-logs-rs-69949c6bff-qq5vj -c addon-token-adapter -- env 2>&1 | grep -E "PROXY|proxy|ENDPOINT|endpoint|MSI|AUTH" 2>&1

kubectl exec -n kube-system ama-logs-rs-69949c6bff-qq5vj -c ama-logs -- cat /var/opt/microsoft/linuxmonagent/log/mdsd.info 2>&1 | tail -30 2>&1



Container Insights Cost Optimization

This guide documents the Terraform configuration for reducing Azure Monitor Container Insights log costs and filtering unnecessary container logs.

Configuration Overview

The configuration has four parts:

  1. AKS enables Container Insights.
  2. Log Analytics stores ContainerLogV2 as Basic Logs.
  3. The Kubernetes ConfigMap filters stdout, stderr, and namespaces.
  4. Environment-specific values are supplied through a .tfvars file.

1. Enable Container Insights

File and line:

modules/azure/aks-k8s/main.tf:57

Resource:

azurerm_kubernetes_cluster.k8s

Required block:

oms_agent {
  log_analytics_workspace_id = var.log_analytics_workspace_id
}

The root module passes the workspace ID here:

log_analytics_workspace_id = module.log_analytics.log_analytics_workspace_id

This installs the Azure Monitor agent and sends AKS monitoring data to Log Analytics.

2. Configure ContainerLogV2 as Basic Logs

File and line:

modules/azure/log_analytics/main.tf:23-29

Resource:

azurerm_log_analytics_workspace_table.container_logs

Current configuration:

resource "azurerm_log_analytics_workspace_table" "container_logs" {
  name                    = "ContainerLogV2"
  workspace_id            = azurerm_log_analytics_workspace.log_analytics.id
  plan                    = "Basic"
  total_retention_in_days = 30
}

Basic Logs reduces ingestion cost for high-volume container logs. Basic Logs may have query charges and is not suitable for every alerting scenario.

The total retention value must be valid for Azure. 30 days is valid. Do not use 8 with total_retention_in_days; Azure rejects that value for this table configuration.

3. Manage Container Log Collection with Terraform

File and lines:

  • providers.tf:8-11 declares the Kubernetes provider.
  • providers.tf:30-37 configures the provider from the AKS kubeconfig.
  • modules/azure/aks-k8s/outputs.tf
  • main.tf

Kubernetes provider

providers.tf declares the Kubernetes provider and configures it from the AKS kubeconfig output:

kubernetes = {
  source  = "hashicorp/kubernetes"
  version = "~> 2.35"
}

The provider uses:

locals {
  aks_kubeconfig = yamldecode(module.kubernetes_cluster.kube_config_raw)
}

provider "kubernetes" {
  host                   = local.aks_kubeconfig.clusters[0].cluster.server
  cluster_ca_certificate = base64decode(local.aks_kubeconfig.clusters[0].cluster["certificate-authority-data"])
  client_certificate     = base64decode(local.aks_kubeconfig.users[0].user["client-certificate-data"])
  client_key             = base64decode(local.aks_kubeconfig.users[0].user["client-key-data"])
}

AKS kubeconfig output

modules/azure/aks-k8s/outputs.tf:11-15 exposes the kubeconfig used by the provider:

output "kube_config_raw" {
  value       = azurerm_kubernetes_cluster.k8s.kube_config_raw
  description = "raw kubeconfig used by the Kubernetes provider"
  sensitive   = true
}

Container Insights ConfigMap

main.tf:68-88 declares this resource after the AKS module:

resource "kubernetes_config_map_v1" "container_azm_ms_agentconfig" {
  metadata {
    name      = "container-azm-ms-agentconfig"
    namespace = "kube-system"
  }

  data = {
    "schema-version" = "v1"
    "config-version" = var.container_logs_config_version
    "log-data-collection-settings" = <<-EOT
      [log-data-collection-settings]
        [log-data-collection-settings.stdout]
          enabled = ${var.container_logs_stdout_enabled}
          exclude_namespaces = ${jsonencode(var.container_logs_exclude_namespaces)}
        [log-data-collection-settings.stderr]
          enabled = ${var.container_logs_stderr_enabled}
    EOT
  }

  depends_on = [module.kubernetes_cluster]
}

This configuration:

  • Collects stdout logs by default.
  • Disables stderr logs by default.
  • Excludes kube-system and gatekeeper-system by default.
  • Applies to the Azure Monitor agent ConfigMap in kube-system.

4. Environment-Specific Variables

File and lines:

variables.tf:202-224

The reusable variables are:

variable "container_logs_config_version" {
  type    = string
  default = "ver1"
}

variable "container_logs_stdout_enabled" {
  type    = bool
  default = true
}

variable "container_logs_stderr_enabled" {
  type    = bool
  default = false
}

variable "container_logs_exclude_namespaces" {
  type    = list(string)
  default = ["kube-system", "gatekeeper-system"]
}

File and lines:

production.tfvars:8-11

Production values:

container_logs_config_version      = "ver1"
container_logs_stdout_enabled      = true
container_logs_stderr_enabled      = false
container_logs_exclude_namespaces  = ["kube-system", "gatekeeper-system"]

For another environment, create another tfvars file, for example test.tfvars:

container_logs_config_version     = "ver1"
container_logs_stdout_enabled     = true
container_logs_stderr_enabled     = false
container_logs_exclude_namespaces = ["kube-system", "gatekeeper-system", "dev-noisy-namespace"]

To collect stderr in a troubleshooting environment:

container_logs_stderr_enabled = true

Apply and Validate

From the Terraform directory:

cd terraform
terraform fmt -check
terraform init
terraform validate
terraform plan -var-file=production.tfvars
terraform apply -var-file=production.tfvars

Check the ConfigMap after applying:

kubectl get configmap container-azm-ms-agentconfig -n kube-system -o yaml

Check the Azure Monitor pods:

kubectl get pods -n kube-system | grep ama-logs

Important Notes

  • The AKS cluster must exist before the Kubernetes ConfigMap can be created.
  • The Kubernetes provider uses the AKS kubeconfig output, so the first apply may need to create AKS before the ConfigMap can be applied successfully. If Terraform cannot configure the provider during the first apply, run the apply in two stages: create AKS first, then apply again for the ConfigMap.
  • The ConfigMap controls which container stdout/stderr logs are collected. The Log Analytics table plan controls the storage and ingestion pricing tier.
  • The DCR/logs preset controls which Container Insights tables are collected. The current Terraform configuration does not create a custom DCR; use the Azure Monitor logs preset or add a dedicated DCR if tables such as Perf, KubeEvents, or InsightsMetrics should also be filtered.
  • Basic Logs can affect alerting and query behavior. Keep frequently queried or alerting data on the Analytics plan where required.
  • The local backend is currently configured in providers.tf with state stored in terraform.tfstate. Restore the GitLab HTTP backend before using the GitLab pipeline.