diff --git a/modules/python/clusterloader2/in_cluster.py b/modules/python/clusterloader2/in_cluster.py new file mode 100644 index 0000000000..dba4eab569 --- /dev/null +++ b/modules/python/clusterloader2/in_cluster.py @@ -0,0 +1,230 @@ +import base64 +from functools import partial +import json +from pathlib import Path +import subprocess +import time +import uuid + + +def _kubectl(kubeconfig, namespace, *args, check=True, stdout=subprocess.PIPE, stdin=None): + # A command can span multiple 30s API requests (e.g. wait for 90s or copy reports). + result = subprocess.run( + ["kubectl", "--kubeconfig", kubeconfig, "--request-timeout=30s", "-n", namespace, *args], + input=stdin, stdout=stdout, stderr=subprocess.PIPE, timeout=120, check=False, + ) + if check and result.returncode: + raise RuntimeError(f"kubectl {' '.join(args)}: {result.stderr.decode(errors='replace')}") + return result + + +def run_cl2_job(kubeconfig, image, config_dir, report_dir, arguments): + """Keep reports available until copied; publish-results returns the saved exit status.""" + report_dir = Path(report_dir).resolve() + report_dir.mkdir(parents=True, exist_ok=True) + name = f"cl2-driver-{uuid.uuid4().hex[:12]}" + status_file = report_dir / f"{name}.exit-code" + status_file.write_text("1", encoding="ascii") + exit_code, pod, created = 1, None, False + + kubectl = partial(_kubectl, kubeconfig, name) + config_maps, sources = [], [] + for path in sorted(Path(config_dir).rglob("*")): + if path.is_file(): + content = path.read_bytes() + if len(content) > 1048576: + raise ValueError(f"CL2 config file exceeds the ConfigMap 1 MiB limit: {path}") + config_name = f"{name}-config-{len(config_maps)}" + config_maps.append({ + "apiVersion": "v1", + "kind": "ConfigMap", + "metadata": {"name": config_name}, + "binaryData": {"config": base64.b64encode(content).decode("ascii")}, + }) + sources.append({ + "configMap": { + "name": config_name, + "items": [{ + "key": "config", + "path": path.relative_to(config_dir).as_posix(), + }], + }, + }) + if not config_maps: + raise ValueError("CL2 configuration must be nonempty") + + timeout = 86400 + root = "/root/perf-tests/clusterloader2" + run_and_collect_script = '''./clusterloader2 "$@" +rc=$? +printf '%s\\n' "$rc" > /cl2-control/exit-code.tmp +mv /cl2-control/exit-code.tmp /cl2-control/exit-code || exit 1 +for i in $(seq 1 300); do + test -f /cl2-control/reports-collected && exit "$rc" + sleep 2 +done +echo "Report collection timed out" >&2 +exit 124 +''' + resources = [ + { + "apiVersion": "v1", + "kind": "ServiceAccount", + "metadata": {"name": name}, + }, + # CL2 installs CRDs and Prometheus RBAC across this disposable test cluster. + { + "apiVersion": "rbac.authorization.k8s.io/v1", + "kind": "ClusterRole", + "metadata": {"name": name}, + "rules": [ + { + "apiGroups": ["*"], + "resources": ["*"], + "verbs": ["*"], + }, + { + "nonResourceURLs": ["/metrics"], + "verbs": ["get"], + }, + ], + }, + { + "apiVersion": "rbac.authorization.k8s.io/v1", + "kind": "ClusterRoleBinding", + "metadata": {"name": name}, + "roleRef": { + "apiGroup": "rbac.authorization.k8s.io", + "kind": "ClusterRole", + "name": name, + }, + "subjects": [{ + "kind": "ServiceAccount", + "name": name, + "namespace": name, + }], + }, + *config_maps, + { + "apiVersion": "batch/v1", + "kind": "Job", + "metadata": {"name": name}, + "spec": { + "backoffLimit": 0, + "activeDeadlineSeconds": timeout + 600, + "template": { + "spec": { + "serviceAccountName": name, + "restartPolicy": "Never", + "nodeSelector": {"kubernetes.io/os": "linux"}, + "containers": [{ + "name": "cl2", + "image": image, + "command": ["/bin/sh", "-c"], + "args": [run_and_collect_script, "cl2", *arguments], + "resources": { + "requests": { + "cpu": "1", + "memory": "2Gi", + }, + }, + "volumeMounts": [ + { + "name": "config", + "mountPath": f"{root}/config", + "readOnly": True, + }, + { + "name": "reports", + "mountPath": f"{root}/results", + }, + { + "name": "control", + "mountPath": "/cl2-control", + }, + ], + }], + "volumes": [ + { + "name": "config", + "projected": {"sources": sources}, + }, + { + "name": "reports", + "emptyDir": {}, + }, + { + "name": "control", + "emptyDir": {}, + }, + ], + }, + }, + }, + }, + ] + try: + kubectl("create", "namespace", name) + created = True + kubectl("create", "-f", "-", stdin=json.dumps( + { + "apiVersion": "v1", + "kind": "List", + "items": resources, + }).encode()) + deadline = time.monotonic() + timeout + startup_deadline = time.monotonic() + 300 + started = False + while time.monotonic() < deadline: + pods = json.loads(kubectl("get", "pods", "-l", f"job-name={name}", "-o", "json").stdout)["items"] + if pods: + pod = pods[0]["metadata"]["name"] + phase = pods[0].get("status", {}).get("phase") + if phase in ("Failed", "Succeeded"): + raise RuntimeError(f"CL2 Pod {pod} terminated before report collection") + if phase == "Pending": + kubectl("wait", "--for=condition=PodScheduled", f"pod/{pod}", "--timeout=90s") + if phase == "Running": + started = True + result = kubectl("exec", pod, "--", "cat", "/cl2-control/exit-code", check=False) + if result.returncode: + time.sleep(5) + continue + code = int(result.stdout) + if not 0 <= code <= 255: + raise ValueError(f"Invalid CL2 exit code: {code}") + kubectl("cp", f"{pod}:{root}/results/.", str(report_dir)) + if code == 0: + kubectl("exec", pod, "--", "test", "-s", f"{root}/results/junit.xml") + kubectl("exec", pod, "--", "touch", "/cl2-control/reports-collected") + kubectl("wait", f"--for=jsonpath={{.status.containerStatuses[0].state.terminated.exitCode}}={code}", + f"pod/{pod}", "--timeout=60s") + exit_code = code + break + elif pod: + raise RuntimeError(f"CL2 Pod {pod} disappeared before report collection") + if not started and time.monotonic() >= startup_deadline: + raise TimeoutError("CL2 Pod did not start within five minutes") + time.sleep(5) + else: + exit_code = 124 + raise TimeoutError("CL2 Job timed out") + finally: + if pod: + try: + with (report_dir / f"{name}.log").open("wb") as output: + result = kubectl("logs", pod, stdout=output, check=False) + if result.returncode: + print(f"Warning: CL2 log collection failed: {result.stderr.decode(errors='replace')}") + except (OSError, subprocess.TimeoutExpired) as error: + print(f"Warning: CL2 log collection failed: {error}") + if created: + try: + kubectl("delete", "namespace,clusterrole,clusterrolebinding", name, + "--ignore-not-found", "--wait=false") + except (OSError, RuntimeError, subprocess.TimeoutExpired) as error: + print(f"CL2 cleanup failed; cluster teardown is required: {error}") + exit_code = exit_code or 1 + status_file.write_text(str(exit_code), encoding="ascii") + print(f"CL2 Job exited {exit_code}; reports and status saved to {report_dir}") + return exit_code diff --git a/modules/python/clusterloader2/utils.py b/modules/python/clusterloader2/utils.py index 50deb2ed85..32a5dff18d 100644 --- a/modules/python/clusterloader2/utils.py +++ b/modules/python/clusterloader2/utils.py @@ -1,8 +1,8 @@ from xml.dom import minidom import json import os -import docker -from clients.docker_client import DockerClient +import shlex +from clusterloader2.in_cluster import run_cl2_job from utils.logger_config import get_logger, setup_logging setup_logging() @@ -26,13 +26,10 @@ def run_cl2_command(kubeconfig, cl2_image, cl2_config_dir, cl2_report_dir, provider, cl2_config_file="config.yaml", overrides=False, enable_prometheus=False, tear_down_prometheus=True, enable_exec_service=False, scrape_kubelets=False, scrape_containerd=False, scrape_ksm=False, scrape_metrics_server=False): - docker_client = DockerClient() - command = f"""--provider={provider} --v=2 --enable-exec-service={enable_exec_service} --enable-prometheus-server={enable_prometheus} --prometheus-scrape-kubelets={scrape_kubelets} ---kubeconfig /root/.kube/config --testconfig /root/perf-tests/clusterloader2/config/{cl2_config_file} --report-dir /root/perf-tests/clusterloader2/results --tear-down-prometheus-server={tear_down_prometheus} @@ -45,38 +42,8 @@ def run_cl2_command(kubeconfig, cl2_image, cl2_config_dir, cl2_report_dir, provi if overrides: command += " --testoverrides=/root/perf-tests/clusterloader2/config/overrides.yaml" - volumes = { - kubeconfig: {'bind': '/root/.kube/config', 'mode': 'rw'}, - cl2_config_dir: {'bind': '/root/perf-tests/clusterloader2/config', 'mode': 'rw'}, - cl2_report_dir: { - 'bind': '/root/perf-tests/clusterloader2/results', 'mode': 'rw'} - } - - if provider == "aws": - aws_path = os.path.expanduser("~/.aws/credentials") - volumes[aws_path] = {'bind': '/root/.aws/credentials', 'mode': 'rw'} - - if provider == "aks": - azure_path = os.path.expanduser("~/.azure") - volumes[azure_path] = {'bind': '/root/.azure', 'mode': 'rw'} - - logger.info( - f"Running clusterloader2 with command: {command} and volumes: {volumes}") - try: - container = docker_client.run_container( - cl2_image, command, volumes, detach=True) - for log in container.logs(stream=True): - log_line = log.decode('utf-8').rstrip('\n') - if log_line: - logger.info(log_line) - result = container.wait() - exit_code = result['StatusCode'] - if exit_code != 0: - logger.error( - f"clusterloader2 exited with a non-zero status code {exit_code}. Make sure to check the logs to confirm whether the error is expected!") - except docker.errors.ContainerError as e: - logger.error( - f"Container exited with a non-zero status code: {e.exit_status}\n{e.stderr.decode('utf-8')}") + return run_cl2_job(kubeconfig, cl2_image, cl2_config_dir, cl2_report_dir, + shlex.split(command) + ["--run-from-cluster=true"]) def get_measurement(file_path): diff --git a/modules/terraform/azure/aks-cli/main.tf b/modules/terraform/azure/aks-cli/main.tf index 8fb69ad84c..41d611c932 100644 --- a/modules/terraform/azure/aks-cli/main.tf +++ b/modules/terraform/azure/aks-cli/main.tf @@ -149,11 +149,11 @@ locals { aad_parameter = ( var.aks_aad_enabled == true ? format( - "--enable-aad --enable-azure-rbac --aad-admin-group-object-ids %s --aad-tenant-id %s", + "--enable-aad --enable-azure-rbac --aad-admin-group-object-ids %s --aad-tenant-id %s --disable-local-accounts", data.azurerm_client_config.current.object_id, data.azurerm_client_config.current.tenant_id ) - : "" + : "--disable-local-accounts" ) custom_configurations = ( diff --git a/modules/terraform/azure/aks-cli/variables.tf b/modules/terraform/azure/aks-cli/variables.tf index 3fb1c427f1..dd0a8ac14a 100644 --- a/modules/terraform/azure/aks-cli/variables.tf +++ b/modules/terraform/azure/aks-cli/variables.tf @@ -44,7 +44,7 @@ variable "disk_encryption_sets" { variable "aks_aad_enabled" { description = "Indicates whether Azure Active Directory integration is enabled for AKS" type = bool - default = false + default = true } variable "acr_pull_scopes_map" { @@ -118,4 +118,3 @@ variable "aks_cli_config" { disk_encryption_set_name = optional(string, null) # Name of the Disk Encryption Set to use for OS disk encryption }) } - diff --git a/modules/terraform/azure/aks/main.tf b/modules/terraform/azure/aks/main.tf index cb9212a4b7..647b1f7ea9 100644 --- a/modules/terraform/azure/aks/main.tf +++ b/modules/terraform/azure/aks/main.tf @@ -140,6 +140,7 @@ resource "azurerm_kubernetes_cluster" "aks" { workload_identity_enabled = var.aks_config.workload_identity_enabled kubernetes_version = var.aks_config.kubernetes_version edge_zone = var.aks_config.edge_zone + local_account_disabled = true dynamic "azure_active_directory_role_based_access_control" { for_each = var.aks_aad_enabled == true ? [1] : [] diff --git a/modules/terraform/azure/aks/variables.tf b/modules/terraform/azure/aks/variables.tf index 98765882b5..fefa39f302 100644 --- a/modules/terraform/azure/aks/variables.tf +++ b/modules/terraform/azure/aks/variables.tf @@ -63,7 +63,7 @@ variable "network_dataplane" { variable "aks_aad_enabled" { description = "Indicates whether Azure Active Directory integration is enabled for AKS" type = bool - default = false + default = true } variable "key_vaults" { diff --git a/modules/terraform/azure/azapi/main.tf b/modules/terraform/azure/azapi/main.tf index e19a8b8d16..d12db24a22 100644 --- a/modules/terraform/azure/azapi/main.tf +++ b/modules/terraform/azure/azapi/main.tf @@ -18,11 +18,12 @@ locals { properties = { for k, v in { - kubernetesVersion = var.azapi_config.kubernetes_version - dnsPrefix = var.azapi_config.dns_prefix - agentPoolProfiles = local.agent_pool_profiles - networkProfile = local.network_profile - enableRBAC = var.azapi_config.aad_enabled ? true : null + kubernetesVersion = var.azapi_config.kubernetes_version + dnsPrefix = var.azapi_config.dns_prefix + agentPoolProfiles = local.agent_pool_profiles + networkProfile = local.network_profile + enableRBAC = var.azapi_config.aad_enabled ? true : null + disableLocalAccounts = true aadProfile = var.azapi_config.aad_enabled ? { managed = true enableAzureRBAC = true diff --git a/modules/terraform/azure/azapi/variables.tf b/modules/terraform/azure/azapi/variables.tf index 7ed9dbd282..9e9dad7314 100644 --- a/modules/terraform/azure/azapi/variables.tf +++ b/modules/terraform/azure/azapi/variables.tf @@ -15,13 +15,13 @@ variable "tags" { } variable "azapi_config" { - description = "Configuration for creating an AKS cluster via Azure REST API (AzAPI provider). aad_enabled opts into managed Microsoft Entra ID integration and Azure RBAC for Kubernetes authorization." + description = "Configuration for creating an AKS cluster via Azure REST API (AzAPI provider). aad_enabled defaults to managed Microsoft Entra ID integration and Azure RBAC for Kubernetes authorization." type = object({ role = string aks_name = string dns_prefix = string api_version = optional(string, "2025-10-01") - aad_enabled = optional(bool, false) + aad_enabled = optional(bool, true) metrics_reader_enabled = optional(bool, false) sku = optional(object({ diff --git a/modules/terraform/azure/main.tf b/modules/terraform/azure/main.tf index ea48654f41..8634541584 100644 --- a/modules/terraform/azure/main.tf +++ b/modules/terraform/azure/main.tf @@ -10,7 +10,7 @@ locals { aks_custom_headers = lookup(var.json_input, "aks_custom_headers", []) k8s_machine_type = lookup(var.json_input, "k8s_machine_type", null) k8s_os_disk_type = lookup(var.json_input, "k8s_os_disk_type", null) - aks_aad_enabled = lookup(var.json_input, "aks_aad_enabled", false) + aks_aad_enabled = lookup(var.json_input, "aks_aad_enabled", true) enable_apiserver_vnet_integration = lookup(var.json_input, "enable_apiserver_vnet_integration", false) public_key_path = lookup(var.json_input, "public_key_path", null) ssh_public_key = local.public_key_path != null ? (fileexists(local.public_key_path) ? file(local.public_key_path) : null) : null diff --git a/modules/terraform/azure/tests/test_aks_aad.tftest.hcl b/modules/terraform/azure/tests/test_aks_aad.tftest.hcl index c8a3bbc24b..66119d660d 100644 --- a/modules/terraform/azure/tests/test_aks_aad.tftest.hcl +++ b/modules/terraform/azure/tests/test_aks_aad.tftest.hcl @@ -9,6 +9,11 @@ mock_provider "azurerm" { } } +# Command assertions use dry_run; do not install CLI extensions during tests. +override_resource { + target = module.aks-cli["client"].terraform_data.enable_aks_cli_preview_extension[0] +} + variables { scenario_type = "perf-eval" scenario_name = "my_scenario" @@ -70,6 +75,11 @@ run "valid_aad_enabled" { error_message = "Expected: default object_id from service principal to be used as admin group" } + assert { + condition = module.aks["test"].aks_cluster.local_account_disabled + error_message = "Expected: local accounts disabled with AAD" + } + assert { condition = module.aks["test"].aks_cluster.azure_active_directory_role_based_access_control[0].azure_rbac_enabled == true error_message = "Expected: azure_rbac_enabled defaults to true" @@ -81,8 +91,8 @@ run "valid_aad_enabled" { } } -# Test case 2: Verify AAD is disabled when aks_aad_enabled is not set -run "valid_aad_disabled" { +# Test case 2: Verify AAD is enabled when aks_aad_enabled is not set +run "valid_aad_default" { command = plan @@ -95,8 +105,8 @@ run "valid_aad_disabled" { } assert { - condition = length(module.aks["test"].aks_cluster.azure_active_directory_role_based_access_control) == 0 - error_message = "Expected: AAD block should not exist when not enabled" + condition = length(module.aks["test"].aks_cluster.azure_active_directory_role_based_access_control) == 1 && module.aks["test"].aks_cluster.local_account_disabled + error_message = "Expected: AAD enabled and local accounts disabled by default" } } @@ -115,8 +125,8 @@ run "valid_aad_explicitly_disabled" { } assert { - condition = length(module.aks["test"].aks_cluster.azure_active_directory_role_based_access_control) == 0 - error_message = "Expected: AAD block should not exist when explicitly disabled" + condition = length(module.aks["test"].aks_cluster.azure_active_directory_role_based_access_control) == 0 && module.aks["test"].aks_cluster.local_account_disabled + error_message = "Expected: AAD absent but local accounts always disabled" } } @@ -221,13 +231,13 @@ run "valid_aks_cli_aad_disabled" { # Verify the CLI command does NOT include any AAD-related flags assert { - condition = !can(regex("--aad-", module.aks-cli["client"].aks_cli_command)) - error_message = "Expected: CLI command should NOT include any --aad-* flags when disabled\nActual: ${module.aks-cli["client"].aks_cli_command}" + condition = !can(regex("--aad-", module.aks-cli["client"].aks_cli_command)) && can(regex("--disable-local-accounts", module.aks-cli["client"].aks_cli_command)) + error_message = "Expected: no AAD flags but local accounts always disabled" } } -# Test case 6: Verify AAD parameters are omitted in aks-cli when not set (default behavior) -run "valid_aks_cli_aad_not_set" { +# Test case 6: Verify null also uses the enabled default (omitted inputs are covered by test_aks_cli) +run "valid_aks_cli_aad_null" { command = apply @@ -235,7 +245,8 @@ run "valid_aks_cli_aad_not_set" { json_input = { "run_id" : "123456789", "region" : "eastus", - "public_key_path" : "public_key_path" + "public_key_path" : "public_key_path", + "aks_aad_enabled" : null } aks_config_list = [] @@ -257,15 +268,30 @@ run "valid_aks_cli_aad_not_set" { ] } - # Verify the CLI command does NOT include --enable-aad flag when not set assert { - condition = !can(regex("--enable-aad", module.aks-cli["client"].aks_cli_command)) - error_message = "Expected: CLI command should NOT include --enable-aad flag when not set\nActual: ${module.aks-cli["client"].aks_cli_command}" + condition = can(regex("--enable-aad", module.aks-cli["client"].aks_cli_command)) + error_message = "Expected: CLI command should include --enable-aad by default" + } + + assert { + condition = can(regex("--enable-azure-rbac", module.aks-cli["client"].aks_cli_command)) && can(regex("--disable-local-accounts", module.aks-cli["client"].aks_cli_command)) + error_message = "Expected: Azure RBAC and disabled local accounts by default" + } +} + +run "valid_aad_null" { + command = plan + + variables { + json_input = { + run_id = "123456789" + region = "eastus" + aks_aad_enabled = null + } } - # Verify the CLI command does NOT include any AAD-related flags when not set assert { - condition = !can(regex("--aad-", module.aks-cli["client"].aks_cli_command)) - error_message = "Expected: CLI command should NOT include any --aad-* flags when not set\nActual: ${module.aks-cli["client"].aks_cli_command}" + condition = length(module.aks["test"].aks_cluster.azure_active_directory_role_based_access_control) == 1 && module.aks["test"].aks_cluster.local_account_disabled + error_message = "Expected: explicit null uses the enabled AAD default" } } diff --git a/modules/terraform/azure/tests/test_aks_cli.tftest.hcl b/modules/terraform/azure/tests/test_aks_cli.tftest.hcl index 9a198d01a1..725def8f5d 100644 --- a/modules/terraform/azure/tests/test_aks_cli.tftest.hcl +++ b/modules/terraform/azure/tests/test_aks_cli.tftest.hcl @@ -9,6 +9,11 @@ mock_provider "azurerm" { } } +# Keep timestamp-dependent command assertions local: never install CLI extensions. +override_resource { + target = module.aks-cli["client"].terraform_data.enable_aks_cli_preview_extension[0] +} + variables { scenario_type = "perf-eval" scenario_name = "my_scenario" @@ -47,7 +52,7 @@ run "test_aks_cli2" { assert { # Check if the generated command matches the expected AKS CLI command format condition = length(regex( - "az aks create -g 123456789 -n test --location eastus --tier Standard --tags SkipAKSCluster=1 creation_time=.* deletion_due_time=.* owner=aks role=client run_id=123456789 scenario=perf-eval-my_scenario --no-ssh-key --enable-managed-identity --nodepool-name default --node-count 2 --node-vm-size Standard_D2s_v3 --vm-set-type VirtualMachineScaleSets --node-osdisk-type Managed\\s*$", + "az aks create -g 123456789 -n test --location eastus --tier Standard --tags SkipAKSCluster=1 creation_time=.* deletion_due_time=.* owner=aks role=client run_id=123456789 scenario=perf-eval-my_scenario --no-ssh-key --enable-managed-identity --enable-aad --enable-azure-rbac --aad-admin-group-object-ids \\S+ --aad-tenant-id 00000000-0000-0000-0000-000000000000 --disable-local-accounts --nodepool-name default --node-count 2 --node-vm-size Standard_D2s_v3 --vm-set-type VirtualMachineScaleSets --node-osdisk-type Managed\\s*$", replace(module.aks-cli["client"].aks_cli_command, "/\\s+/", " ") # normalize whitespace for comparison )) > 0 error_message = "Actual: ${replace(module.aks-cli["client"].aks_cli_command, "\\s+", " ")}" @@ -83,7 +88,7 @@ run "test_aks_cli_automatic" { assert { condition = length(regex( - "az aks create -g 123456789 -n test --location eastus --tier Standard --tags SkipAKSCluster=1 creation_time=.* deletion_due_time=.* owner=aks role=client run_id=123456789 scenario=perf-eval-my_scenario --no-ssh-key --sku automatic --zones 1 2 3 --enable-managed-identity\\s*$", + "az aks create -g 123456789 -n test --location eastus --tier Standard --tags SkipAKSCluster=1 creation_time=.* deletion_due_time=.* owner=aks role=client run_id=123456789 scenario=perf-eval-my_scenario --no-ssh-key --sku automatic --zones 1 2 3 --enable-managed-identity --enable-aad --enable-azure-rbac --aad-admin-group-object-ids \\S+ --aad-tenant-id 00000000-0000-0000-0000-000000000000 --disable-local-accounts\\s*$", replace(module.aks-cli["client"].aks_cli_command, "/\\s+/", " ") # normalize whitespace for comparison )) > 0 error_message = "Actual: ${replace(module.aks-cli["client"].aks_cli_command, "/\\s+/", " ")}" diff --git a/modules/terraform/azure/tests/test_azapi.tftest.hcl b/modules/terraform/azure/tests/test_azapi.tftest.hcl index 6757ff2910..a403094bba 100644 --- a/modules/terraform/azure/tests/test_azapi.tftest.hcl +++ b/modules/terraform/azure/tests/test_azapi.tftest.hcl @@ -62,6 +62,17 @@ run "azapi_with_control_plane_scaling" { condition = module.azapi["test-azapi-h2"].resource_body.properties.controlPlaneScalingProfile.scalingSize == "H2" error_message = "controlPlaneScalingProfile.scalingSize should be 'H2'" } + + assert { + condition = ( + module.azapi["test-azapi-h2"].resource_body.properties.enableRBAC && + module.azapi["test-azapi-h2"].resource_body.properties.aadProfile.managed && + module.azapi["test-azapi-h2"].resource_body.properties.aadProfile.enableAzureRBAC && + module.azapi["test-azapi-h2"].resource_body.properties.aadProfile.tenantID == "00000000-0000-0000-0000-000000000000" && + module.azapi["test-azapi-h2"].resource_body.properties.disableLocalAccounts + ) + error_message = "AzAPI must default to managed Entra ID and Azure RBAC with local accounts disabled." + } } # Test case 2: Verify AzAPI resource works without controlPlaneScalingProfile @@ -80,6 +91,7 @@ run "azapi_without_control_plane_scaling" { role = "client" aks_name = "test-azapi-std" dns_prefix = "test-azapi-std" + aad_enabled = false kubernetes_version = "1.33.0" default_node_pool = { name = "systempool1" @@ -112,6 +124,15 @@ run "azapi_without_control_plane_scaling" { condition = !contains(keys(module.azapi["test-azapi-std"].resource_body.properties), "controlPlaneScalingProfile") error_message = "controlPlaneScalingProfile should not be present when not specified" } + + assert { + condition = ( + !contains(keys(module.azapi["test-azapi-std"].resource_body.properties), "aadProfile") && + !contains(keys(module.azapi["test-azapi-std"].resource_body.properties), "enableRBAC") && + module.azapi["test-azapi-std"].resource_body.properties.disableLocalAccounts + ) + error_message = "Explicit AAD false must omit AAD settings but keep local accounts disabled." + } } # Test case 3: Verify empty azapi_config_list produces no resources diff --git a/modules/terraform/azure/variables.tf b/modules/terraform/azure/variables.tf index e2c1ef6784..bd33d47feb 100644 --- a/modules/terraform/azure/variables.tf +++ b/modules/terraform/azure/variables.tf @@ -7,7 +7,7 @@ variable "json_input" { aks_kubernetes_version = optional(string, null) aks_network_policy = optional(string, null) aks_network_dataplane = optional(string, null) - aks_aad_enabled = optional(bool, null) + aks_aad_enabled = optional(bool, true) aks_custom_headers = optional(list(string), []) k8s_machine_type = optional(string, null) k8s_os_disk_type = optional(string, null) @@ -522,13 +522,13 @@ variable "arm_endpoint" { } variable "azapi_config_list" { - description = "List of AKS cluster configurations to create via Azure REST API (AzAPI provider). aad_enabled opts into managed Microsoft Entra ID integration and Azure RBAC for Kubernetes authorization." + description = "List of AKS cluster configurations to create via Azure REST API (AzAPI provider). aad_enabled defaults to managed Microsoft Entra ID integration and Azure RBAC for Kubernetes authorization." type = list(object({ role = string aks_name = string dns_prefix = string api_version = optional(string, "2025-10-01") - aad_enabled = optional(bool, false) + aad_enabled = optional(bool, true) metrics_reader_enabled = optional(bool, false) sku = optional(object({ diff --git a/steps/cloud/azure/install-kubelogin.yml b/steps/cloud/azure/install-kubelogin.yml index b90ccb75e2..7da99b2646 100644 --- a/steps/cloud/azure/install-kubelogin.yml +++ b/steps/cloud/azure/install-kubelogin.yml @@ -21,7 +21,7 @@ steps: install_success=false for i in $(seq 1 $max_retries); do - if az aks install-cli; then + if sudo az aks install-cli; then echo "Successfully installed via az aks install-cli" install_success=true break diff --git a/steps/cloud/azure/update-kubeconfig.yml b/steps/cloud/azure/update-kubeconfig.yml index 2eeef79104..b124a9376d 100644 --- a/steps/cloud/azure/update-kubeconfig.yml +++ b/steps/cloud/azure/update-kubeconfig.yml @@ -30,3 +30,8 @@ steps: ROLE: ${{ parameters.role }} ALIAS: ${{ parameters.alias }} displayName: "Update kubeconfig" + +- template: /steps/cloud/azure/install-kubelogin.yml + parameters: + cloud: azure + region: ${{ parameters.region }} diff --git a/steps/publish-results.yml b/steps/publish-results.yml index 69231cd898..90f85bbfae 100644 --- a/steps/publish-results.yml +++ b/steps/publish-results.yml @@ -33,3 +33,24 @@ steps: parameters: credential_type: ${{ parameters.credential_type }} cloud: ${{ parameters.cloud }} + +- ${{ if eq(parameters.engine, 'clusterloader2') }}: + - bash: | + set -euo pipefail + status=0 + found=false + while IFS= read -r -d '' file; do + found=true + code=$(cat "$file") + if [[ ! "$code" =~ ^(0|[1-9][0-9]{0,2})$ ]] || (( code > 255 )); then + echo "Invalid CL2 exit status in $file" >&2 + status=1 + elif (( code != 0 && status == 0 )); then + status=$code + fi + artifact="${file%.exit-code}.log" + if [[ -f "$artifact" ]]; then echo "##vso[task.uploadfile]$artifact"; fi + done < <(find "$(Pipeline.Workspace)/s/modules/python/clusterloader2" -name 'cl2-driver-*.exit-code' -print0) + if [[ "$found" == false ]]; then echo "CL2 Job exit status missing" >&2; exit 1; fi + exit "$status" + displayName: "Return CL2 Job exit status after collection" diff --git a/steps/topology/cluster-automatic/validate-resources.yml b/steps/topology/cluster-automatic/validate-resources.yml index dc54d62e91..98c3e72c15 100644 --- a/steps/topology/cluster-automatic/validate-resources.yml +++ b/steps/topology/cluster-automatic/validate-resources.yml @@ -13,12 +13,6 @@ steps: region: ${{ parameters.regions[0] }} alias: automatic -- ${{ if eq(parameters.cloud, 'azure') }}: - - template: /steps/cloud/azure/install-kubelogin.yml - parameters: - cloud: ${{ parameters.cloud }} - region: ${{ parameters.regions[0] }} - - ${{ if eq(parameters.engine, 'aks-store-demo') }}: - template: /steps/topology/cluster-automatic/aks-store-demo-python.yml parameters: diff --git a/steps/topology/hyperscale-cluster/validate-resources.yml b/steps/topology/hyperscale-cluster/validate-resources.yml index 200f39db4c..f8daf18acd 100644 --- a/steps/topology/hyperscale-cluster/validate-resources.yml +++ b/steps/topology/hyperscale-cluster/validate-resources.yml @@ -12,12 +12,6 @@ steps: role: client region: ${{ parameters.regions[0] }} -- ${{ if eq(parameters.cloud, 'azure') }}: - - template: /steps/cloud/azure/install-kubelogin.yml - parameters: - cloud: ${{ parameters.cloud }} - region: ${{ parameters.regions[0] }} - - script: | echo "Checking API server GOMAXPROCS (max CPU cores available)..." GOMAXPROCS_LINE=$(kubectl get --raw /metrics | grep '^go_sched_gomaxprocs_threads') diff --git a/steps/topology/karpenter/validate-resources.yml b/steps/topology/karpenter/validate-resources.yml index ca08a35726..8f2f2f8dfa 100644 --- a/steps/topology/karpenter/validate-resources.yml +++ b/steps/topology/karpenter/validate-resources.yml @@ -11,11 +11,6 @@ steps: parameters: role: nap region: ${{ parameters.regions[0] }} - - ${{ if eq(parameters.cloud, 'azure') }}: - - template: /steps/cloud/azure/install-kubelogin.yml - parameters: - cloud: ${{ parameters.cloud }} - region: ${{ parameters.regions[0] }} - bash: | set -euo pipefail set -x