From eb5a45dcb3c4e0ca996b6781a1533c67f58f54fc Mon Sep 17 00:00:00 2001 From: Wei Weng Date: Tue, 24 Nov 2026 19:11:29 +0000 Subject: [PATCH 01/16] ci: support isolated runs in a shared E2E resource group Add opt-in run-specific resource naming, scoped role grants, and ownership-verified per-run cleanup while preserving disposable resource group behavior by default. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- ...26-11-24-1842-shared-e2e-resource-group.md | 46 ++ .pipeline/e2e-tests.yaml | 40 +- test/README.md | 46 +- test/e2e/framework/workload_manager.go | 6 + test/e2e/framework/workload_manager_test.go | 46 ++ test/e2e/traffic_manager_test.go | 7 + test/scripts/afd_test.go | 4 +- test/scripts/aks-dynamic-ip-allocation.sh | 13 +- test/scripts/aks-no-networking.sh | 9 +- test/scripts/aks-peered-vnet.sh | 17 +- test/scripts/aks-shared-vnet.sh | 21 +- test/scripts/bootstrap.sh | 98 ++-- test/scripts/cleanup-shared-group.sh | 310 +++++++++++ test/scripts/cleanup.sh | 8 + test/scripts/e2e-config.sh | 77 ++- test/scripts/install-afd.sh | 12 +- test/scripts/shared_group_test.go | 487 ++++++++++++++++++ 17 files changed, 1173 insertions(+), 74 deletions(-) create mode 100644 .github/.copilot/breadcrumbs/2026-11-24-1842-shared-e2e-resource-group.md create mode 100644 test/e2e/framework/workload_manager_test.go create mode 100644 test/scripts/cleanup-shared-group.sh create mode 100644 test/scripts/shared_group_test.go diff --git a/.github/.copilot/breadcrumbs/2026-11-24-1842-shared-e2e-resource-group.md b/.github/.copilot/breadcrumbs/2026-11-24-1842-shared-e2e-resource-group.md new file mode 100644 index 00000000..352e777e --- /dev/null +++ b/.github/.copilot/breadcrumbs/2026-11-24-1842-shared-e2e-resource-group.md @@ -0,0 +1,46 @@ +# Shared E2E resource group + +## Requirements and decisions + +- User approved an opt-in shared resource group mode with unique run identities, safe cleanup, offline tests and documentation; existing disposable-group behavior remains the default. +- Push a new branch based on main. Do not run live Azure E2E or cleanup without separate approval. +- Shared group `fleet-networking-e2e` was created in the test subscription, westus2. Proposed grants and WIF service connection are not yet deployed. +- Prior work: [retry PR #459](https://github.com/Azure/fleet-networking/pull/459). + +## Plan + +1. [x] Trace E2E setup, tests, Azure dependencies, resource ownership and cleanup. +2. [x] Add offline tests for concurrent run isolation, configuration and fail-closed cleanup. +3. [x] Implement opt-in shared-group setup, naming, permissions and safe per-run cleanup; preserve existing behavior. +4. [x] Update documentation and validate targeted tests and shell checks. +5. [ ] Push branch and report unverified live behavior and remaining risks. + +## Before + +Each Azure DevOps scenario creates and deletes a unique resource group. Fixed resource and cluster names assume one run per group. + +## Investigation + +- `test/scripts/bootstrap.sh` creates the whole group, fixed cluster names, a registry named from the group, Azure identities and role assignments. The network topology scripts create fixed VNet names. +- `test/e2e/e2e_test.go`, `test/e2e/framework/workload_manager.go` and `test/scripts/install-afd.sh` assume fixed cluster or registry names. AFD validates the member node resource groups before assigning roles. +- Traffic Manager profiles are named from Kubernetes object UIDs and tagged with the namespaced profile name; Front Door profiles use Kubernetes hub and Gateway ownership tags. The Traffic Manager E2E also creates an independently named public IP. These resources cannot safely be selected for cleanup using only a generic run-name prefix. +- The proposed WIF identity and grants have not been deployed. Existing E2E scripts assign roles using `--assignee`, and the AFD proof needs separate Network Contributor on member node groups for its test caller. +- A correct shared-group implementation needs durable per-run ownership evidence for controller-generated resources, exact ownership checks and cleanup ordering, including partial setup and cancellation. The current group-deletion cleanup cannot be reused. + +## Status + +Shared-group mode is opt-in. The Azure DevOps pipeline supplies a unique run ID per scenario and attempt; scripts derive physical Azure names and retain the established logical Kubernetes contexts. Setup requires a new run-specific kubeconfig, verifies the group and rejects name or ownership collisions before enabling cleanup. + +Cleanup verifies the group, run tags, resource IDs, AKS node-group ownership, role scopes and peering targets. It verifies Traffic Manager namespace tags and Front Door hub/Gateway identity, stops the run's hub controllers before deleting their profiles, deletes only identified roles and resources, and never deletes the shared group. It fails explicitly when ownership, controller quiescence or deletion cannot be verified. + +Shared AFD requires the test principal object ID, grants it Network Contributor only on verified member node groups, and records the principal for cleanup. The pipeline service connection remains unchanged by default and can be selected explicitly after its grants are deployed. + +Changed files: `.pipeline/e2e-tests.yaml`, `test/README.md`, the `test/scripts` setup, topology, configuration, AFD and cleanup scripts and tests, plus E2E framework workload naming and Traffic Manager public-IP tagging. + +## Validation and risks + +- `GOTOOLCHAIN=go1.26.10 go test -count=1 ./test/scripts ./test/e2e/framework` passed, including mocked concurrent-run, collision, profile, peering, role, cleanup and legacy cases. +- `GOTOOLCHAIN=go1.26.10 go vet ./test/scripts ./test/e2e/framework` passed. +- `GOTOOLCHAIN=go1.26.10 go test -tags=e2e -run '^$' ./test/e2e` and `go vet -tags=e2e ./test/e2e` passed without executing live E2E. +- Installed Azure CLI AFD option checks, Bash syntax, pipeline YAML parsing and `git diff --check` passed. +- No live Azure provisioning, permission, test or cleanup operation was run. The proposed grants and service connection have not been enabled. Cleanup can fail closed and leave resources; there is no stale-run sweeper. Contributor on the shared RG is not a security boundary between runs. diff --git a/.pipeline/e2e-tests.yaml b/.pipeline/e2e-tests.yaml index 2a9bf5e0..596482aa 100644 --- a/.pipeline/e2e-tests.yaml +++ b/.pipeline/e2e-tests.yaml @@ -8,6 +8,15 @@ trigger: pr: none parameters: + - name: sharedResourceGroup + type: boolean + default: false + - name: serviceConnection + type: string + default: 'aks fleetnetworking' + - name: testPrincipalId + type: string + default: 'none' - name: scenarios type: object default: @@ -61,7 +70,13 @@ jobs: AZURE_NETWORK_SETTING: ${{ scenario.value.AZURE_NETWORK_SETTING }} ENABLE_TRAFFIC_MANAGER: ${{ lower(scenario.value.ENABLE_TRAFFIC_MANAGER) }} ENABLE_AZURE_FRONT_DOOR: ${{ lower(scenario.value.ENABLE_AZURE_FRONT_DOOR) }} - AZURE_RESOURCE_GROUP: 'fleet-ado-$(Build.BuildId)-$(SCENARIO)-$(System.JobAttempt)' + ${{ if eq(parameters.sharedResourceGroup, true) }}: + AZURE_RESOURCE_GROUP: 'fleet-networking-e2e' + ${{ else }}: + AZURE_RESOURCE_GROUP: 'fleet-ado-$(Build.BuildId)-$(SCENARIO)-$(System.JobAttempt)' + E2E_SHARED_RESOURCE_GROUP: ${{ lower(parameters.sharedResourceGroup) }} + E2E_RUN_ID: '$(Build.BuildId)-$(SCENARIO)-$(System.JobAttempt)' + E2E_TEST_PRINCIPAL_ID: ${{ parameters.testPrincipalId }} ENABLE_AFD_PRIVATE_LINK_AUTO_APPROVAL: '$(ENABLE_AZURE_FRONT_DOOR)' RETAIN_AFD_E2E_SETUP: 'false' BUILDX_BUILDER_NAME: 'fleet-e2e-$(Build.BuildId)-$(SCENARIO)-$(System.JobAttempt)' @@ -95,7 +110,7 @@ jobs: - bash: | set -euo pipefail : "${AZURE_SUBSCRIPTION_ID:?Set AZURE_SUBSCRIPTION_ID as a non-secret ADO pipeline variable}" - for tool in az docker helm kubectl jq yq make timeout; do + for tool in az docker helm kubectl jq yq make timeout sha256sum; do command -v "$tool" done go version @@ -115,7 +130,7 @@ jobs: displayName: Set up E2E environment timeoutInMinutes: 180 inputs: - azureSubscription: 'aks fleetnetworking' + azureSubscription: ${{ parameters.serviceConnection }} scriptType: bash scriptLocation: inlineScript addSpnToEnvironment: false @@ -129,11 +144,16 @@ jobs: exit 1 fi exists=$(az group exists --subscription "$AZURE_SUBSCRIPTION_ID" -n "$AZURE_RESOURCE_GROUP") - if [[ "$exists" != false ]]; then + if [[ "$E2E_SHARED_RESOURCE_GROUP" == true && "$exists" != true ]]; then + echo "error: shared resource group $AZURE_RESOURCE_GROUP does not exist" >&2 + exit 1 + elif [[ "$E2E_SHARED_RESOURCE_GROUP" != true && "$exists" != false ]]; then echo "error: refusing to reuse resource group $AZURE_RESOURCE_GROUP" >&2 exit 1 fi - echo "##vso[task.setvariable variable=e2eResourcesStarted]true" + if [[ "$E2E_SHARED_RESOURCE_GROUP" != true ]]; then + echo "##vso[task.setvariable variable=e2eResourcesStarted]true" + fi make e2e-setup - bash: | @@ -150,7 +170,7 @@ jobs: displayName: Run E2E tests timeoutInMinutes: ${{ scenario.value.E2E_TEST_TIMEOUT }} inputs: - azureSubscription: 'aks fleetnetworking' + azureSubscription: ${{ parameters.serviceConnection }} scriptType: bash scriptLocation: inlineScript addSpnToEnvironment: false @@ -187,9 +207,9 @@ jobs: - task: AzureCLI@2 displayName: Clean up this run's resource group condition: and(always(), eq(variables['e2eResourcesStarted'], 'true')) - timeoutInMinutes: 20 + timeoutInMinutes: ${{ iif(parameters.sharedResourceGroup, 90, 20) }} inputs: - azureSubscription: 'aks fleetnetworking' + azureSubscription: ${{ parameters.serviceConnection }} scriptType: bash scriptLocation: inlineScript addSpnToEnvironment: false @@ -197,6 +217,10 @@ jobs: keepAzSessionActive: true inlineScript: | set -euo pipefail + if [[ "$E2E_SHARED_RESOURCE_GROUP" == true ]]; then + make e2e-cleanup + exit 0 + fi expected="fleet-ado-$BUILD_BUILDID-$SCENARIO-$SYSTEM_JOBATTEMPT" if [[ "$AZURE_RESOURCE_GROUP" != "$expected" ]]; then echo "error: refusing cleanup outside this run's resource group" >&2 diff --git a/test/README.md b/test/README.md index 2f5ec947..71f74ff7 100644 --- a/test/README.md +++ b/test/README.md @@ -13,7 +13,8 @@ networking components, and runs the Ginkgo tests under `test/e2e`. - [`jq`](https://jqlang.github.io/jq/download/) - [`yq`](https://github.com/mikefarah/yq#install) - Bash and GNU Make -- An Azure subscription in which the signed-in identity has the Owner role +- An Azure subscription in which the signed-in identity can provision the test resources and + create the required role assignments Sign in and select the subscription before starting: @@ -26,6 +27,49 @@ az account set --subscription "${AZURE_SUBSCRIPTION_ID}" The setup builds and pushes test images, creates an Azure Container Registry and AKS clusters, and assigns Azure roles. Use a test subscription rather than a production subscription. +### Opt-in shared resource group + +The Azure DevOps E2E pipeline can use the pre-created `fleet-networking-e2e` resource group by +setting the `sharedResourceGroup` pipeline parameter to `true`. The default remains a disposable +resource group per job. Before opting in, an administrator must deploy the scoped permissions +and authorize the intended service connection; choose it with the `serviceConnection` parameter. +For automated AFD Private Link approval, `testPrincipalId` must be that connection's service +principal **object ID**. + +For a local run, set the following in addition to the scenario variables: + +```bash +export AZURE_RESOURCE_GROUP=fleet-networking-e2e +export E2E_SHARED_RESOURCE_GROUP=true +export E2E_RUN_ID= +export KUBECONFIG= +# Required only when AFD automatic approval is enabled: +export E2E_TEST_PRINCIPAL_ID= +``` + +Use a unique `E2E_RUN_ID` for every concurrent run and retry; never reuse an ID while a prior run +or its cleanup is active. The pipeline derives it from the build ID, scenario and job attempt. +Setup checks the shared group's expected management tags and refuses existing run resources. +Physical Azure cluster names, VNets, identities and the registry are run-specific, while the +isolated kubeconfig retains the `hub-admin` and `member-*-admin` context names. +Shared-group mode does not support the separate `perf-test` topology. AFD shared mode requires +the default Gateway controller namespace and deployment name. + +`make e2e-cleanup` in shared mode **never deletes the resource group**. It verifies run tags, +resource IDs, controller profile ownership and AKS-managed node groups before removing the +run's resources and relevant role assignments. If ownership cannot be established, the hub is +unavailable when controller cleanup is needed, or Azure cleanup fails, the command stops with an +error and resources may remain. Keep the run ID and inspect leftovers before retrying; do not +delete the shared group. For AFD auto-approval, supply the same `E2E_TEST_PRINCIPAL_ID` during +cleanup. There is no automatic stale-run sweeper. + +Run-specific names and cleanup checks prevent accidental cross-run deletion; they are not an Azure +security boundary. An identity with Contributor on the shared group can modify other runs' resources +and delete the group. Node groups still need their own permissions outside the shared group. + +These shared-group permissions and cleanup paths require a separately approved live Azure run +before production use. Offline tests do not establish Azure provisioning or deletion behavior. + ## Choose an E2E scenario All scenarios use the same setup, test, and cleanup targets. The environment variables determine diff --git a/test/e2e/framework/workload_manager.go b/test/e2e/framework/workload_manager.go index 93b0470b..fba6392b 100644 --- a/test/e2e/framework/workload_manager.go +++ b/test/e2e/framework/workload_manager.go @@ -430,6 +430,9 @@ func defaultBackOff() wait.Backoff { // TODO(mainred): Before the app image is publicly available, we use the one built from e2e bootstrap. // The app image construction must be aligned with the steps in test/scripts/bootstrap.sh. func appImage() string { + if registry := os.Getenv("REGISTRY"); registry != "" { + return fmt.Sprintf("%s/app", registry) + } resourceGroupName := os.Getenv("AZURE_RESOURCE_GROUP") registryName := strings.ReplaceAll(resourceGroupName, "-", "") return fmt.Sprintf("%s.azurecr.io/app", registryName) @@ -437,5 +440,8 @@ func appImage() string { // UniqueTestNamespace gives a unique namespace name. func UniqueTestNamespace() string { + if prefix := os.Getenv("E2E_RESOURCE_PREFIX"); os.Getenv("E2E_SHARED_RESOURCE_GROUP") == "true" && prefix != "" { + return fmt.Sprintf("%s-%s", prefix, uniquename.RandomLowerCaseAlphabeticString(5)) + } return fmt.Sprintf("%s-%s", TestNamespacePrefix, uniquename.RandomLowerCaseAlphabeticString(5)) } diff --git a/test/e2e/framework/workload_manager_test.go b/test/e2e/framework/workload_manager_test.go new file mode 100644 index 00000000..5bbd892b --- /dev/null +++ b/test/e2e/framework/workload_manager_test.go @@ -0,0 +1,46 @@ +/* +Copyright (c) Microsoft Corporation. +Licensed under the MIT license. +*/ + +package framework + +import ( + "strings" + "testing" + + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/util/validation" +) + +func TestSharedRunWorkloadNames(t *testing.T) { + t.Setenv("E2E_SHARED_RESOURCE_GROUP", "true") + t.Setenv("E2E_RESOURCE_PREFIX", "fne0123456789abcdef") + t.Setenv("REGISTRY", "fne0123456789abcdefacr.azurecr.io") + if got := appImage(); got != "fne0123456789abcdefacr.azurecr.io/app" { + t.Fatalf("app image uses the wrong run registry: %s", got) + } + namespace := UniqueTestNamespace() + if !strings.HasPrefix(namespace, "fne0123456789abcdef-") { + t.Fatalf("namespace does not identify this run: %s", namespace) + } + workload := WorkloadManager{ + namespace: namespace, + service: corev1.Service{ObjectMeta: metav1.ObjectMeta{Name: "hello-world-service"}}, + } + label := workload.BuildServiceDNSLabelName(&Cluster{name: "member-1"}) + if problems := validation.IsDNS1123Label(label); len(problems) != 0 { + t.Fatalf("shared run DNS label %q is invalid: %v", label, problems) + } + + t.Setenv("E2E_SHARED_RESOURCE_GROUP", "false") + t.Setenv("REGISTRY", "") + t.Setenv("AZURE_RESOURCE_GROUP", "fleet-legacy-123") + if got := appImage(); got != "fleetlegacy123.azurecr.io/app" { + t.Fatalf("legacy registry naming changed: %s", got) + } + if got := UniqueTestNamespace(); !strings.HasPrefix(got, "my-ns-") { + t.Fatalf("legacy namespace naming changed: %s", got) + } +} diff --git a/test/e2e/traffic_manager_test.go b/test/e2e/traffic_manager_test.go index a9f0fc45..8ca7a0b4 100644 --- a/test/e2e/traffic_manager_test.go +++ b/test/e2e/traffic_manager_test.go @@ -619,6 +619,9 @@ var _ = Describe("Test exporting service via Azure traffic manager", Ordered, fu It("Creating extra Azure traffic manager endpoint directly and then updating trafficManagerBackend", func() { By("Creating a public IP address") publicIPAddressName := fmt.Sprintf("e2e-test-public-ip-%s", uniquename.RandomLowerCaseAlphabeticString(5)) + if os.Getenv("E2E_SHARED_RESOURCE_GROUP") == "true" { + publicIPAddressName = fmt.Sprintf("%s-ip-%s", os.Getenv("E2E_RESOURCE_PREFIX"), uniquename.RandomLowerCaseAlphabeticString(5)) + } publicIPReq := armnetwork.PublicIPAddress{ Name: ptr.To(publicIPAddressName), Location: ptr.To(clusterLocation), @@ -632,6 +635,10 @@ var _ = Describe("Test exporting service via Azure traffic manager", Ordered, fu Name: ptr.To(armnetwork.PublicIPAddressSKUNameStandard), }, } + if runID := os.Getenv("E2E_RUN_ID"); os.Getenv("E2E_SHARED_RESOURCE_GROUP") == "true" { + Expect(runID).ShouldNot(BeEmpty()) + publicIPReq.Tags = map[string]*string{"source": ptr.To("fleet-networking"), "fleet-e2e-run": ptr.To(runID)} + } publicIPResp, err := pipClient.CreateOrUpdate(ctx, atmValidator.ResourceGroup, publicIPAddressName, publicIPReq) Expect(err).Should(Succeed(), "Failed to create public IP address") diff --git a/test/scripts/afd_test.go b/test/scripts/afd_test.go index e0c4ee23..427f69f5 100644 --- a/test/scripts/afd_test.go +++ b/test/scripts/afd_test.go @@ -326,7 +326,7 @@ case "$kind" in printf '{"id":"%s","provisioningState":"Succeeded"}\n' "$id" ;; "role assignment create"|"role assignment list") if [[ "$verb" == list && "${AFD_TEST_EMPTY_BINDINGS:-}" == true ]]; then printf '[]\n'; exit 0; fi - printf '[{"principalId":"hub-principal","scope":"%s","roleDefinitionId":"/roles/acdd72a7-3385-48ef-bd42-f606fba81ae7"}]\n' "$scope" ;; + printf '[{"principalId":"%s-principal","scope":"%s","roleDefinitionId":"/roles/acdd72a7-3385-48ef-bd42-f606fba81ae7"}]\n' "${HUB_AZURE_CLUSTER:-hub}" "$scope" ;; *) echo "unexpected Azure operation: $kind" >&2; exit 1 ;; esac ` @@ -373,6 +373,8 @@ func afdTestEnvironment(t *testing.T) { "ENABLE_AFD_PRIVATE_LINK_AUTO_APPROVAL", "RETAIN_AFD_E2E_SETUP", "HUB_CLUSTER", "MEMBER_CLUSTER_1", "MEMBER_CLUSTER_2", + "E2E_SHARED_RESOURCE_GROUP", "E2E_RUN_ID", "E2E_RESOURCE_PREFIX", "E2E_TEST_PRINCIPAL_ID", + "HUB_AZURE_CLUSTER", "MEMBER_1_AZURE_CLUSTER", "MEMBER_2_AZURE_CLUSTER", "REGISTRY_NAME", "HUB_GATEWAY_CONTROLLER_MANAGER_IMAGE_NAME", "HUB_GATEWAY_CONTROLLER_MANAGER_IMAGE_VERSION", "AFD_PROOF_CONTROLLER_NAMESPACE", "AFD_PROOF_CONTROLLER_DEPLOYMENT", "AFD_TEST_FAIL_COMMAND", "AFD_TEST_EMPTY_BINDINGS", "AFD_TEST_REAL_HELM", diff --git a/test/scripts/aks-dynamic-ip-allocation.sh b/test/scripts/aks-dynamic-ip-allocation.sh index 4980b118..c22c974d 100644 --- a/test/scripts/aks-dynamic-ip-allocation.sh +++ b/test/scripts/aks-dynamic-ip-allocation.sh @@ -3,6 +3,7 @@ set -o errexit set -o nounset set -o pipefail set -x +source "$(dirname "${BASH_SOURCE[0]}")/e2e-config.sh" # dynamic-ip-allocation creates two member clusters using dynamic allocation of IPs and enhanced subnet support in the same vnet. @@ -15,12 +16,12 @@ set -x # https://docs.microsoft.com/en-us/azure/aks/configure-azure-cni#configure-networking---cli-with-dynamic-allocation-of-ips-and-enhanced-subnet-support # Create virutal network and podsubnet and nodesubnet for both member clusters. -export VNET=fleet +export VNET="${E2E_RESOURCE_PREFIX:+${E2E_RESOURCE_PREFIX}-}fleet" export MEMBER_1_NODE_SUBNET=member-1-node export MEMBER_1_POD_SUBNET=member-1-pod export MEMBER_2_NODE_SUBNET=member-2-node export MEMBER_2_POD_SUBNET=member-2-pod -az network vnet create -g $RESOURCE_GROUP --location $MEMBER_1_LOCATION --name $VNET --address-prefixes 10.0.0.0/8 -o none +az network vnet create -g $RESOURCE_GROUP --location $MEMBER_1_LOCATION --name $VNET --address-prefixes 10.0.0.0/8 -o none "${E2E_RESOURCE_TAGS[@]}" az network vnet subnet create -g $RESOURCE_GROUP --vnet-name $VNET --name $MEMBER_1_NODE_SUBNET --address-prefixes 10.242.0.0/16 -o none az network vnet subnet create -g $RESOURCE_GROUP --vnet-name $VNET --name $MEMBER_1_POD_SUBNET --address-prefixes 10.243.0.0/16 -o none az network vnet subnet create -g $RESOURCE_GROUP --vnet-name $VNET --name $MEMBER_2_NODE_SUBNET --address-prefixes 10.244.0.0/16 -o none @@ -30,7 +31,7 @@ az network vnet subnet create -g $RESOURCE_GROUP --vnet-name $VNET --name $MEMBE az aks create \ --location $MEMBER_1_LOCATION \ --resource-group $RESOURCE_GROUP \ - --name $MEMBER_CLUSTER_1 \ + --name $MEMBER_1_AZURE_CLUSTER \ --node-count $NODE_COUNT \ --node-vm-size Standard_A2_v2 \ --generate-ssh-keys \ @@ -39,13 +40,13 @@ az aks create \ --network-plugin azure \ --vnet-subnet-id "/subscriptions/$AZURE_SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP/providers/Microsoft.Network/virtualNetworks/$VNET/subnets/$MEMBER_1_NODE_SUBNET" \ --pod-subnet-id "/subscriptions/$AZURE_SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP/providers/Microsoft.Network/virtualNetworks/$VNET/subnets/$MEMBER_1_POD_SUBNET" \ - --no-wait + --no-wait "${E2E_RESOURCE_TAGS[@]}" # Create aks member cluster2, specifying amd64 VM size to ensure linux/amd64 docker images can be consumed. az aks create \ --location $MEMBER_2_LOCATION \ --resource-group $RESOURCE_GROUP \ - --name $MEMBER_CLUSTER_2 \ + --name $MEMBER_2_AZURE_CLUSTER \ --node-count $NODE_COUNT \ --node-vm-size Standard_A2_v2 \ --generate-ssh-keys \ @@ -54,4 +55,4 @@ az aks create \ --network-plugin azure \ --vnet-subnet-id "/subscriptions/$AZURE_SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP/providers/Microsoft.Network/virtualNetworks/$VNET/subnets/$MEMBER_2_NODE_SUBNET" \ --pod-subnet-id "/subscriptions/$AZURE_SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP/providers/Microsoft.Network/virtualNetworks/$VNET/subnets/$MEMBER_2_POD_SUBNET" \ - --no-wait + --no-wait "${E2E_RESOURCE_TAGS[@]}" diff --git a/test/scripts/aks-no-networking.sh b/test/scripts/aks-no-networking.sh index 119ff5c2..1c4cd5ae 100644 --- a/test/scripts/aks-no-networking.sh +++ b/test/scripts/aks-no-networking.sh @@ -3,6 +3,7 @@ set -o errexit set -o nounset set -o pipefail set -x +source "$(dirname "${BASH_SOURCE[0]}")/e2e-config.sh" # aks-no-networking creates two member clusters @@ -15,23 +16,23 @@ set -x az aks create \ --location $MEMBER_1_LOCATION \ --resource-group $RESOURCE_GROUP \ - --name $MEMBER_CLUSTER_1 \ + --name $MEMBER_1_AZURE_CLUSTER \ --node-count $NODE_COUNT \ --node-vm-size Standard_A2_v2 \ --generate-ssh-keys \ --enable-aad \ --enable-azure-rbac \ - --no-wait + --no-wait "${E2E_RESOURCE_TAGS[@]}" # Create aks member cluster2, specifying amd64 VM size to ensure linux/amd64 docker images can be consumed. az aks create \ --location $MEMBER_2_LOCATION \ --resource-group $RESOURCE_GROUP \ - --name $MEMBER_CLUSTER_2 \ + --name $MEMBER_2_AZURE_CLUSTER \ --node-count $NODE_COUNT \ --node-vm-size Standard_A2_v2 \ --generate-ssh-keys \ --enable-aad \ --enable-azure-rbac \ - --no-wait + --no-wait "${E2E_RESOURCE_TAGS[@]}" diff --git a/test/scripts/aks-peered-vnet.sh b/test/scripts/aks-peered-vnet.sh index b71b38df..29199f67 100644 --- a/test/scripts/aks-peered-vnet.sh +++ b/test/scripts/aks-peered-vnet.sh @@ -3,6 +3,7 @@ set -o errexit set -o nounset set -o pipefail set -x +source "$(dirname "${BASH_SOURCE[0]}")/e2e-config.sh" # peered-vnet creates two member clusters with network peered by virtual network peering. The vnet and member clusters @@ -20,9 +21,9 @@ set -x # Create virutal network and subnet for both member clusters. export MEMBER_1_TO_MEMBER_2=member-1-to-member-2 export MEMBER_2_TO_MEMBER_1=member-2-to-member-1 -export MEMBER_1_VNET=member-1-vnet +export MEMBER_1_VNET="${E2E_RESOURCE_PREFIX:+${E2E_RESOURCE_PREFIX}-}member-1-vnet" export MEMBER_1_SUBNET=member-1-subnet -export MEMBER_2_VNET=member-2-vnet +export MEMBER_2_VNET="${E2E_RESOURCE_PREFIX:+${E2E_RESOURCE_PREFIX}-}member-2-vnet" export MEMBER_2_SUBNET=member-2-subnet az network vnet create \ @@ -31,7 +32,7 @@ az network vnet create \ --name $MEMBER_1_VNET \ --resource-group $RESOURCE_GROUP \ --subnet-name $MEMBER_1_SUBNET \ - --subnet-prefixes 10.1.0.0/24 + --subnet-prefixes 10.1.0.0/24 "${E2E_RESOURCE_TAGS[@]}" az network vnet create \ --location $MEMBER_2_LOCATION \ @@ -39,7 +40,7 @@ az network vnet create \ --name $MEMBER_2_VNET \ --resource-group $RESOURCE_GROUP \ --subnet-name $MEMBER_2_SUBNET \ - --subnet-prefixes 10.2.0.0/24 + --subnet-prefixes 10.2.0.0/24 "${E2E_RESOURCE_TAGS[@]}" # Get the id for MEMBER_1_VNET. MEMBER_1_VNET_ID=$(az network vnet show \ @@ -72,7 +73,7 @@ az network vnet peering create \ az aks create \ --location $MEMBER_1_LOCATION \ --resource-group $RESOURCE_GROUP \ - --name $MEMBER_CLUSTER_1 \ + --name $MEMBER_1_AZURE_CLUSTER \ --node-count $NODE_COUNT \ --node-vm-size Standard_A2_v2 \ --generate-ssh-keys \ @@ -80,13 +81,13 @@ az aks create \ --enable-azure-rbac \ --network-plugin azure \ --vnet-subnet-id "/subscriptions/$AZURE_SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP/providers/Microsoft.Network/virtualNetworks/$MEMBER_1_VNET/subnets/$MEMBER_1_SUBNET" \ - --no-wait + --no-wait "${E2E_RESOURCE_TAGS[@]}" # Create aks member cluster2, specifying amd64 VM size to ensure linux/amd64 docker images can be consumed. az aks create \ --location $MEMBER_2_LOCATION \ --resource-group $RESOURCE_GROUP \ - --name $MEMBER_CLUSTER_2 \ + --name $MEMBER_2_AZURE_CLUSTER \ --node-count $NODE_COUNT \ --node-vm-size Standard_A2_v2 \ --generate-ssh-keys \ @@ -94,4 +95,4 @@ az aks create \ --enable-azure-rbac \ --network-plugin azure \ --vnet-subnet-id "/subscriptions/$AZURE_SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP/providers/Microsoft.Network/virtualNetworks/$MEMBER_2_VNET/subnets/$MEMBER_2_SUBNET" \ - --no-wait + --no-wait "${E2E_RESOURCE_TAGS[@]}" diff --git a/test/scripts/aks-shared-vnet.sh b/test/scripts/aks-shared-vnet.sh index 6cf513ea..17f02038 100644 --- a/test/scripts/aks-shared-vnet.sh +++ b/test/scripts/aks-shared-vnet.sh @@ -3,6 +3,7 @@ set -o errexit set -o nounset set -o pipefail set -x +source "$(dirname "${BASH_SOURCE[0]}")/e2e-config.sh" # shared-vnet creates two member clusters from subnets within one vnet. @@ -15,7 +16,7 @@ set -x # https://docs.microsoft.com/en-us/azure/virtual-network/tutorial-connect-virtual-networks-cli # Create virutal network and subnet for both member clusters. -export VNET=fleet +export VNET="${E2E_RESOURCE_PREFIX:+${E2E_RESOURCE_PREFIX}-}fleet" export MEMBER_1_SUBNET=member-1 export MEMBER_2_SUBNET=member-2 @@ -23,7 +24,7 @@ az network vnet create \ --name $VNET \ --location $MEMBER_1_LOCATION \ -g $RESOURCE_GROUP \ - --address-prefixes 10.0.0.0/8 + --address-prefixes 10.0.0.0/8 "${E2E_RESOURCE_TAGS[@]}" az network vnet subnet create \ --vnet-name $VNET \ @@ -41,7 +42,7 @@ if [ "$ENABLE_TRAFFIC_MANAGER" == "false" ]; then az aks create \ --location $MEMBER_1_LOCATION \ --resource-group $RESOURCE_GROUP \ - --name $MEMBER_CLUSTER_1 \ + --name $MEMBER_1_AZURE_CLUSTER \ --node-count $NODE_COUNT \ --node-vm-size Standard_A2_v2 \ --generate-ssh-keys \ @@ -49,12 +50,12 @@ if [ "$ENABLE_TRAFFIC_MANAGER" == "false" ]; then --enable-azure-rbac \ --network-plugin azure \ --vnet-subnet-id "/subscriptions/$AZURE_SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP/providers/Microsoft.Network/virtualNetworks/$VNET/subnets/$MEMBER_1_SUBNET" \ - --no-wait + --no-wait "${E2E_RESOURCE_TAGS[@]}" else az aks create \ --location $MEMBER_1_LOCATION \ --resource-group $RESOURCE_GROUP \ - --name $MEMBER_CLUSTER_1 \ + --name $MEMBER_1_AZURE_CLUSTER \ --node-count $NODE_COUNT \ --node-vm-size Standard_A2_v2 \ --generate-ssh-keys \ @@ -63,7 +64,7 @@ else --network-plugin azure \ --vnet-subnet-id "/subscriptions/$AZURE_SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP/providers/Microsoft.Network/virtualNetworks/$VNET/subnets/$MEMBER_1_SUBNET" \ --enable-managed-identity --assign-identity ${MEMBER_CLUSTER_1_AKS_IDENTITY_ID} --assign-kubelet-identity ${MEMBER_CLUSTER_1_AKS_KUBELET_IDENTITY_ID} \ - --no-wait + --no-wait "${E2E_RESOURCE_TAGS[@]}" fi # Create aks member cluster2, specifying amd64 VM size to ensure linux/amd64 docker images can be consumed. @@ -71,7 +72,7 @@ if [ "$ENABLE_TRAFFIC_MANAGER" == "false" ]; then az aks create \ --location $MEMBER_2_LOCATION \ --resource-group $RESOURCE_GROUP \ - --name $MEMBER_CLUSTER_2 \ + --name $MEMBER_2_AZURE_CLUSTER \ --node-count $NODE_COUNT \ --node-vm-size Standard_A2_v2 \ --generate-ssh-keys \ @@ -79,12 +80,12 @@ if [ "$ENABLE_TRAFFIC_MANAGER" == "false" ]; then --enable-azure-rbac \ --network-plugin azure \ --vnet-subnet-id "/subscriptions/$AZURE_SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP/providers/Microsoft.Network/virtualNetworks/$VNET/subnets/$MEMBER_2_SUBNET" \ - --no-wait + --no-wait "${E2E_RESOURCE_TAGS[@]}" else az aks create \ --location $MEMBER_2_LOCATION \ --resource-group $RESOURCE_GROUP \ - --name $MEMBER_CLUSTER_2 \ + --name $MEMBER_2_AZURE_CLUSTER \ --node-count $NODE_COUNT \ --node-vm-size Standard_A2_v2 \ --generate-ssh-keys \ @@ -93,5 +94,5 @@ else --network-plugin azure \ --vnet-subnet-id "/subscriptions/$AZURE_SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP/providers/Microsoft.Network/virtualNetworks/$VNET/subnets/$MEMBER_2_SUBNET" \ --enable-managed-identity --assign-identity ${MEMBER_CLUSTER_2_AKS_IDENTITY_ID} --assign-kubelet-identity ${MEMBER_CLUSTER_2_AKS_KUBELET_IDENTITY_ID} \ - --no-wait + --no-wait "${E2E_RESOURCE_TAGS[@]}" fi diff --git a/test/scripts/bootstrap.sh b/test/scripts/bootstrap.sh index 7defc958..8eeed431 100644 --- a/test/scripts/bootstrap.sh +++ b/test/scripts/bootstrap.sh @@ -40,15 +40,45 @@ az account set -s ${AZURE_SUBSCRIPTION_ID} # RANDOM ID promises workflow runs don't interface one another. export RESOURCE_GROUP="${AZURE_RESOURCE_GROUP:-fleet-networking-e2e-$RANDOM}" export LOCATION="${LOCATION:-eastus2}" -az group create --name $RESOURCE_GROUP --location $LOCATION --tags "source=fleet-networking" +if [[ "$E2E_SHARED_RESOURCE_GROUP" == true ]]; then + if [[ -z "${KUBECONFIG:-}" || "$KUBECONFIG" == *:* || -e "$KUBECONFIG" || -L "$KUBECONFIG" ]]; then + echo "error: shared setup requires a new, run-specific KUBECONFIG path" >&2 + exit 1 + fi + group="$(az group show --subscription "$AZURE_SUBSCRIPTION_ID" --name "$RESOURCE_GROUP" -o json)" + jq -e --arg id "/subscriptions/$AZURE_SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP" \ + '(.id | ascii_downcase) == ($id | ascii_downcase) and .tags.managedBy == "aks-rp/ci-resources" and .tags.workload == "fleet-networking-e2e"' \ + <<<"$group" > /dev/null + resources="$(az resource list --subscription "$AZURE_SUBSCRIPTION_ID" --resource-group "$RESOURCE_GROUP" -o json)" + if ! jq -e --arg prefix "$E2E_RESOURCE_PREFIX" --arg run "$E2E_RUN_ID" ' + all(.[]; + ((.name | ascii_downcase | startswith($prefix)) | not) and + .tags["fleet-e2e-run"] != $run and + ((.tags["networking.fleet.azure.com.trafficManagerProfile"] // "") | startswith($prefix + "-") | not) and + ((.tags["networking.fleet.azure.com.gateway-namespace"] // "") | startswith($prefix + "-") | not)) + ' <<<"$resources" >/dev/null; then + echo "error: refusing to reuse resources for run $E2E_RUN_ID" >&2 + exit 1 + fi + echo "##vso[task.setvariable variable=e2eResourcesStarted]true" +else + az group create --name $RESOURCE_GROUP --location $LOCATION --tags "source=fleet-networking" +fi # Defer function to recycle created Azure resource. function cleanup { - az group delete -n $RESOURCE_GROUP --no-wait --yes + if [[ "$E2E_SHARED_RESOURCE_GROUP" == true ]]; then + echo "shared resource group setup interrupted; run explicit per-run cleanup" >&2 + else + az group delete -n $RESOURCE_GROUP --no-wait --yes + fi } if [[ "$RETAIN_AFD_E2E_SETUP" == true ]]; then trap 'echo "AFD setup interrupted; retaining resources for explicit later cleanup" >&2; exit 130' INT trap 'echo "AFD setup interrupted; retaining resources for explicit later cleanup" >&2; exit 143' TERM +elif [[ "$E2E_SHARED_RESOURCE_GROUP" == true ]]; then + trap 'echo "Shared setup interrupted; run explicit per-run cleanup" >&2; exit 130' INT + trap 'echo "Shared setup interrupted; run explicit per-run cleanup" >&2; exit 143' TERM else trap cleanup INT TERM fi @@ -56,8 +86,12 @@ fi # Pubilsh fleet networking agent images. # TODO(mainred): Once we have a specific Azure sub for fleet networking e2e test, we can reuse that registry. # Registry name must conform to the following pattern: '^[a-zA-Z0-9]*$'. -export REGISTRY_NAME="${RESOURCE_GROUP//-}" -az acr create -g $RESOURCE_GROUP -n $REGISTRY_NAME --sku standard --tags "source=fleet-networking" +if [[ "$E2E_SHARED_RESOURCE_GROUP" == true ]]; then + az acr create -g "$RESOURCE_GROUP" -n "$REGISTRY_NAME" --sku standard "${E2E_RESOURCE_TAGS[@]}" +else + export REGISTRY_NAME="${RESOURCE_GROUP//-}" + az acr create -g "$RESOURCE_GROUP" -n "$REGISTRY_NAME" --sku standard --tags "source=fleet-networking" +fi # Enable anonymous to not wait for the long-running AKS creation. # When attach-acr and `--enable-managed-identity` are both specified, AKS requires us to wait until the whole operation # succeeds, and as AuthN and AuthZ for member cluster agents to hub cluster in our test requires managed identity, @@ -89,20 +123,20 @@ if [ "$ENABLE_TRAFFIC_MANAGER" == "false" ]; then az aks create \ --location $LOCATION \ --resource-group $RESOURCE_GROUP \ - --name $HUB_CLUSTER \ + --name $HUB_AZURE_CLUSTER \ --node-count $NODE_COUNT \ --node-vm-size Standard_A2_v2 \ --generate-ssh-keys \ --enable-aad \ --enable-azure-rbac \ --network-plugin azure \ - --no-wait + --no-wait "${E2E_RESOURCE_TAGS[@]}" else # Create aks identity echo "Creating hub control-plane identity: ${HUB_CLUSTER_AKS_ID_NAME}" - HUB_CLUSTER_AKS_IDENTITY=$(az identity create -g ${RESOURCE_GROUP} -n ${HUB_CLUSTER_AKS_ID_NAME}) + HUB_CLUSTER_AKS_IDENTITY=$(az identity create -g ${RESOURCE_GROUP} -n ${HUB_CLUSTER_AKS_ID_NAME} "${E2E_RESOURCE_TAGS[@]}") echo "Creating hub kubelet identity: ${HUB_CLUSTER_AKS_KUBELET_ID_NAME}" - HUB_CLUSTER_AKS_KUBELET_IDENTITY=$(az identity create -g ${RESOURCE_GROUP} -n ${HUB_CLUSTER_AKS_KUBELET_ID_NAME}) + HUB_CLUSTER_AKS_KUBELET_IDENTITY=$(az identity create -g ${RESOURCE_GROUP} -n ${HUB_CLUSTER_AKS_KUBELET_ID_NAME} "${E2E_RESOURCE_TAGS[@]}") HUB_CLUSTER_AKS_IDENTITY_ID=$(echo ${HUB_CLUSTER_AKS_IDENTITY} | jq -r '. | .id') HUB_CLUSTER_AKS_KUBELET_IDENTITY_ID=$(echo ${HUB_CLUSTER_AKS_KUBELET_IDENTITY} | jq -r '. | .id') @@ -114,7 +148,7 @@ else az aks create \ --location $LOCATION \ --resource-group $RESOURCE_GROUP \ - --name $HUB_CLUSTER \ + --name $HUB_AZURE_CLUSTER \ --node-count $NODE_COUNT \ --node-vm-size Standard_A2_v2 \ --generate-ssh-keys \ @@ -122,13 +156,13 @@ else --enable-azure-rbac \ --network-plugin azure \ --enable-managed-identity --assign-identity ${HUB_CLUSTER_AKS_IDENTITY_ID} --assign-kubelet-identity ${HUB_CLUSTER_AKS_KUBELET_IDENTITY_ID} \ - --no-wait + --no-wait "${E2E_RESOURCE_TAGS[@]}" # Create aks identity for member-1 echo "Creating member-1 control-plane identity: ${MEMBER_CLUSTER_1_AKS_ID_NAME}" - MEMBER_CLUSTER_1_AKS_IDENTITY=$(az identity create -g ${RESOURCE_GROUP} -n ${MEMBER_CLUSTER_1_AKS_ID_NAME}) + MEMBER_CLUSTER_1_AKS_IDENTITY=$(az identity create -g ${RESOURCE_GROUP} -n ${MEMBER_CLUSTER_1_AKS_ID_NAME} "${E2E_RESOURCE_TAGS[@]}") echo "Creating member-1 kubelet identity: ${MEMBER_CLUSTER_1_AKS_KUBELET_ID_NAME}" - MEMBER_CLUSTER_1_AKS_KUBELET_IDENTITY=$(az identity create -g ${RESOURCE_GROUP} -n ${MEMBER_CLUSTER_1_AKS_KUBELET_ID_NAME}) + MEMBER_CLUSTER_1_AKS_KUBELET_IDENTITY=$(az identity create -g ${RESOURCE_GROUP} -n ${MEMBER_CLUSTER_1_AKS_KUBELET_ID_NAME} "${E2E_RESOURCE_TAGS[@]}") export MEMBER_CLUSTER_1_AKS_IDENTITY_ID=$(echo ${MEMBER_CLUSTER_1_AKS_IDENTITY} | jq -r '. | .id') export MEMBER_CLUSTER_1_AKS_KUBELET_IDENTITY_ID=$(echo ${MEMBER_CLUSTER_1_AKS_KUBELET_IDENTITY} | jq -r '. | .id') @@ -137,9 +171,9 @@ else # Create aks identity for member-2 echo "Creating member-2 control-plane identity: ${MEMBER_CLUSTER_2_AKS_ID_NAME}" - MEMBER_CLUSTER_2_AKS_IDENTITY=$(az identity create -g ${RESOURCE_GROUP} -n ${MEMBER_CLUSTER_2_AKS_ID_NAME}) + MEMBER_CLUSTER_2_AKS_IDENTITY=$(az identity create -g ${RESOURCE_GROUP} -n ${MEMBER_CLUSTER_2_AKS_ID_NAME} "${E2E_RESOURCE_TAGS[@]}") echo "Creating member-2 kubelet identity: ${MEMBER_CLUSTER_2_AKS_KUBELET_ID_NAME}" - MEMBER_CLUSTER_2_AKS_KUBELET_IDENTITY=$(az identity create -g ${RESOURCE_GROUP} -n ${MEMBER_CLUSTER_2_AKS_KUBELET_ID_NAME}) + MEMBER_CLUSTER_2_AKS_KUBELET_IDENTITY=$(az identity create -g ${RESOURCE_GROUP} -n ${MEMBER_CLUSTER_2_AKS_KUBELET_ID_NAME} "${E2E_RESOURCE_TAGS[@]}") export MEMBER_CLUSTER_2_AKS_IDENTITY_ID=$(echo ${MEMBER_CLUSTER_2_AKS_IDENTITY} | jq -r '. | .id') export MEMBER_CLUSTER_2_AKS_KUBELET_IDENTITY_ID=$(echo ${MEMBER_CLUSTER_2_AKS_KUBELET_IDENTITY} | jq -r '. | .id') @@ -184,9 +218,9 @@ case $AZURE_NETWORK_SETTING in ;; esac -az aks wait --created --interval 10 --name $HUB_CLUSTER --resource-group $RESOURCE_GROUP --timeout 1800 -az aks wait --created --interval 10 --name $MEMBER_CLUSTER_1 --resource-group $RESOURCE_GROUP --timeout 1800 -az aks wait --created --interval 10 --name $MEMBER_CLUSTER_2 --resource-group $RESOURCE_GROUP --timeout 1800 +az aks wait --created --interval 10 --name $HUB_AZURE_CLUSTER --resource-group $RESOURCE_GROUP --timeout 1800 +az aks wait --created --interval 10 --name $MEMBER_1_AZURE_CLUSTER --resource-group $RESOURCE_GROUP --timeout 1800 +az aks wait --created --interval 10 --name $MEMBER_2_AZURE_CLUSTER --resource-group $RESOURCE_GROUP --timeout 1800 if [ "${AZURE_NETWORK_SETTING}" == "perf-test" ] then az aks wait --created --interval 10 --name $MEMBER_CLUSTER_3 --resource-group $RESOURCE_GROUP --timeout 1800 @@ -195,11 +229,11 @@ fi # hack: add role assignments to kubelet identity if [ "$ENABLE_TRAFFIC_MANAGER" == "true" ]; then - AKS_HUB_CLUSTER=$(az aks show -g $RESOURCE_GROUP -n $HUB_CLUSTER) + AKS_HUB_CLUSTER=$(az aks show -g $RESOURCE_GROUP -n $HUB_AZURE_CLUSTER) AKS_HUB_CLUSTER_NODE_RESOURCE_GROUP=$(echo ${AKS_HUB_CLUSTER} | jq -r '. | .nodeResourceGroup') echo "Assigning Azure Kubernetes Fleet Manager Hub Agent Role to hub kubelet identity on the resourceGroup of the hub cluster" - az role assignment create --role "de2b316d-7a2c-4143-b4cd-c148f6a355a1" --assignee ${HUB_CLUSTER_KUBELET_PRINCIPAL_ID} --scope "/subscriptions/${AZURE_SUBSCRIPTION_ID}/resourceGroups/${RESOURCE_GROUP}" > /dev/null + az role assignment create --role "de2b316d-7a2c-4143-b4cd-c148f6a355a1" --assignee-object-id ${HUB_CLUSTER_KUBELET_PRINCIPAL_ID} --assignee-principal-type ServicePrincipal --scope "/subscriptions/${AZURE_SUBSCRIPTION_ID}/resourceGroups/${RESOURCE_GROUP}" > /dev/null # Creating azure configuration file for the controllers echo "Generating azure configuration file:" $(pwd)/hub_azure_config.yaml @@ -213,14 +247,14 @@ if [ "$ENABLE_TRAFFIC_MANAGER" == "true" ]; then location: "${LOCATION}" EOF - AKS_MEMBER_1=$(az aks show -g $RESOURCE_GROUP -n $MEMBER_CLUSTER_1) + AKS_MEMBER_1=$(az aks show -g $RESOURCE_GROUP -n $MEMBER_1_AZURE_CLUSTER) AKS_MEMBER_1_NODE_RESOURCE_GROUP=$(echo ${AKS_MEMBER_1} | jq -r '. | .nodeResourceGroup') echo "Assigning Azure Kubernetes Fleet Manager Hub Agent Role to hub kubelet identity on the MC_resourceGroup of the member cluster" - az role assignment create --role "de2b316d-7a2c-4143-b4cd-c148f6a355a1" --assignee ${HUB_CLUSTER_KUBELET_PRINCIPAL_ID} --scope "/subscriptions/${AZURE_SUBSCRIPTION_ID}/resourceGroups/${AKS_MEMBER_1_NODE_RESOURCE_GROUP}" > /dev/null + az role assignment create --role "de2b316d-7a2c-4143-b4cd-c148f6a355a1" --assignee-object-id ${HUB_CLUSTER_KUBELET_PRINCIPAL_ID} --assignee-principal-type ServicePrincipal --scope "/subscriptions/${AZURE_SUBSCRIPTION_ID}/resourceGroups/${AKS_MEMBER_1_NODE_RESOURCE_GROUP}" > /dev/null echo "Assigning roles to member-1 kubelet identity on the MC_resourceGroup of the member cluster" - az role assignment create --role "Network Contributor" --assignee ${MEMBER_CLUSTER_1_KUBELET_PRINCIPAL_ID} --scope "/subscriptions/${AZURE_SUBSCRIPTION_ID}/resourceGroups/${AKS_MEMBER_1_NODE_RESOURCE_GROUP}" > /dev/null + az role assignment create --role "Network Contributor" --assignee-object-id ${MEMBER_CLUSTER_1_KUBELET_PRINCIPAL_ID} --assignee-principal-type ServicePrincipal --scope "/subscriptions/${AZURE_SUBSCRIPTION_ID}/resourceGroups/${AKS_MEMBER_1_NODE_RESOURCE_GROUP}" > /dev/null # Creating azure configuration file for the controllers echo "Generating azure configuration file:" $(pwd)/member_1_azure_config.yaml @@ -235,14 +269,14 @@ EOF EOF - AKS_MEMBER_2=$(az aks show -g $RESOURCE_GROUP -n $MEMBER_CLUSTER_2) + AKS_MEMBER_2=$(az aks show -g $RESOURCE_GROUP -n $MEMBER_2_AZURE_CLUSTER) AKS_MEMBER_2_NODE_RESOURCE_GROUP=$(echo ${AKS_MEMBER_2} | jq -r '. | .nodeResourceGroup') echo "Assigning Azure Kubernetes Fleet Manager Hub Agent Role to hub kubelet identity on the MC_resourceGroup of the member cluster" - az role assignment create --role "de2b316d-7a2c-4143-b4cd-c148f6a355a1" --assignee ${HUB_CLUSTER_KUBELET_PRINCIPAL_ID} --scope "/subscriptions/${AZURE_SUBSCRIPTION_ID}/resourceGroups/${AKS_MEMBER_2_NODE_RESOURCE_GROUP}" > /dev/null + az role assignment create --role "de2b316d-7a2c-4143-b4cd-c148f6a355a1" --assignee-object-id ${HUB_CLUSTER_KUBELET_PRINCIPAL_ID} --assignee-principal-type ServicePrincipal --scope "/subscriptions/${AZURE_SUBSCRIPTION_ID}/resourceGroups/${AKS_MEMBER_2_NODE_RESOURCE_GROUP}" > /dev/null echo "Assigning roles to member-2 kubelet identity on the MC_resourceGroup of the member cluster" - az role assignment create --role "Network Contributor" --assignee ${MEMBER_CLUSTER_2_KUBELET_PRINCIPAL_ID} --scope "/subscriptions/${AZURE_SUBSCRIPTION_ID}/resourceGroups/${AKS_MEMBER_2_NODE_RESOURCE_GROUP}" > /dev/null + az role assignment create --role "Network Contributor" --assignee-object-id ${MEMBER_CLUSTER_2_KUBELET_PRINCIPAL_ID} --assignee-principal-type ServicePrincipal --scope "/subscriptions/${AZURE_SUBSCRIPTION_ID}/resourceGroups/${AKS_MEMBER_2_NODE_RESOURCE_GROUP}" > /dev/null # Creating azure configuration file for the controllers echo "Generating azure configuration file:" $(pwd)/member_2_azure_config.yaml @@ -258,9 +292,9 @@ EOF fi # Export kubeconfig. -az aks get-credentials --name $HUB_CLUSTER -g $RESOURCE_GROUP --admin --overwrite-existing -az aks get-credentials --name $MEMBER_CLUSTER_1 -g $RESOURCE_GROUP --admin --overwrite-existing -az aks get-credentials --name $MEMBER_CLUSTER_2 -g $RESOURCE_GROUP --admin --overwrite-existing +az aks get-credentials --name $HUB_AZURE_CLUSTER -g $RESOURCE_GROUP --admin --context "$HUB_CLUSTER-admin" --overwrite-existing +az aks get-credentials --name $MEMBER_1_AZURE_CLUSTER -g $RESOURCE_GROUP --admin --context "$MEMBER_CLUSTER_1-admin" --overwrite-existing +az aks get-credentials --name $MEMBER_2_AZURE_CLUSTER -g $RESOURCE_GROUP --admin --context "$MEMBER_CLUSTER_2-admin" --overwrite-existing if [ "${AZURE_NETWORK_SETTING}" == "perf-test" ] then az aks get-credentials --name $MEMBER_CLUSTER_3 -g $RESOURCE_GROUP --admin --overwrite-existing @@ -271,10 +305,10 @@ export HUB_URL # Setup hub cluster credentials. if [ "$ENABLE_TRAFFIC_MANAGER" == "false" ]; then - export CLIENT_ID_FOR_MEMBER_1=$(az identity list -g MC_"$RESOURCE_GROUP"_"$MEMBER_CLUSTER_1"_"$MEMBER_1_LOCATION" | jq --arg identity $MEMBER_CLUSTER_1-agentpool -r -c 'map(select(.name | contains($identity)))[].clientId') - export PRINCIPAL_FOR_MEMBER_1=$(az identity list -g MC_"$RESOURCE_GROUP"_"$MEMBER_CLUSTER_1"_"$MEMBER_1_LOCATION" | jq --arg identity $MEMBER_CLUSTER_1-agentpool -r -c 'map(select(.name | contains($identity)))[].principalId') - export CLIENT_ID_FOR_MEMBER_2=$(az identity list -g MC_"$RESOURCE_GROUP"_"$MEMBER_CLUSTER_2"_"$MEMBER_2_LOCATION" | jq --arg identity $MEMBER_CLUSTER_2-agentpool -r -c 'map(select(.name | contains($identity)))[].clientId') - export PRINCIPAL_FOR_MEMBER_2=$(az identity list -g MC_"$RESOURCE_GROUP"_"$MEMBER_CLUSTER_2"_"$MEMBER_2_LOCATION" | jq --arg identity $MEMBER_CLUSTER_2-agentpool -r -c 'map(select(.name | contains($identity)))[].principalId') + export CLIENT_ID_FOR_MEMBER_1=$(az identity list -g MC_"$RESOURCE_GROUP"_"$MEMBER_1_AZURE_CLUSTER"_"$MEMBER_1_LOCATION" | jq --arg identity $MEMBER_1_AZURE_CLUSTER-agentpool -r -c 'map(select(.name | contains($identity)))[].clientId') + export PRINCIPAL_FOR_MEMBER_1=$(az identity list -g MC_"$RESOURCE_GROUP"_"$MEMBER_1_AZURE_CLUSTER"_"$MEMBER_1_LOCATION" | jq --arg identity $MEMBER_1_AZURE_CLUSTER-agentpool -r -c 'map(select(.name | contains($identity)))[].principalId') + export CLIENT_ID_FOR_MEMBER_2=$(az identity list -g MC_"$RESOURCE_GROUP"_"$MEMBER_2_AZURE_CLUSTER"_"$MEMBER_2_LOCATION" | jq --arg identity $MEMBER_2_AZURE_CLUSTER-agentpool -r -c 'map(select(.name | contains($identity)))[].clientId') + export PRINCIPAL_FOR_MEMBER_2=$(az identity list -g MC_"$RESOURCE_GROUP"_"$MEMBER_2_AZURE_CLUSTER"_"$MEMBER_2_LOCATION" | jq --arg identity $MEMBER_2_AZURE_CLUSTER-agentpool -r -c 'map(select(.name | contains($identity)))[].principalId') if [ "${AZURE_NETWORK_SETTING}" == "perf-test" ] then export CLIENT_ID_FOR_MEMBER_3=$(az identity list -g MC_"$RESOURCE_GROUP"_"$MEMBER_CLUSTER_3"_"$MEMBER_LOCATION_2" | jq --arg identity $MEMBER_CLUSTER_3-agentpool -r -c 'map(select(.name | contains($identity)))[].clientId') diff --git a/test/scripts/cleanup-shared-group.sh b/test/scripts/cleanup-shared-group.sh new file mode 100644 index 00000000..022dd0f8 --- /dev/null +++ b/test/scripts/cleanup-shared-group.sh @@ -0,0 +1,310 @@ +#!/bin/bash +set -o errexit +set -o nounset +set -o pipefail + +source "$(dirname "${BASH_SOURCE[0]}")/e2e-config.sh" +if [[ "$E2E_SHARED_RESOURCE_GROUP" != true || "$RETAIN_AFD_E2E_SETUP" == true ]]; then + echo "error: shared cleanup requires shared mode and non-retained setup" >&2 + exit 1 +fi + +group_id="/subscriptions/$AZURE_SUBSCRIPTION_ID/resourceGroups/$AZURE_RESOURCE_GROUP" +group="$(az group show --subscription "$AZURE_SUBSCRIPTION_ID" --name "$AZURE_RESOURCE_GROUP" -o json)" +jq -e --arg id "$group_id" \ + '(.id | ascii_downcase) == ($id | ascii_downcase) and .tags.managedBy == "aks-rp/ci-resources" and .tags.workload == "fleet-networking-e2e"' \ + <<<"$group" >/dev/null + +resources="$(az resource list --subscription "$AZURE_SUBSCRIPTION_ID" --resource-group "$AZURE_RESOURCE_GROUP" -o json)" +if ! jq -e --arg prefix "$E2E_RESOURCE_PREFIX" --arg run "$E2E_RUN_ID" --arg group "$group_id" \ + --arg hub "$HUB_AZURE_CLUSTER" --arg member1 "$MEMBER_1_AZURE_CLUSTER" --arg member2 "$MEMBER_2_AZURE_CLUSTER" ' + all(.[]; + if (.name | ascii_downcase | startswith($prefix)) or (.tags["fleet-e2e-run"] // "") == $run then + .tags.source == "fleet-networking" and .tags["fleet-e2e-run"] == $run and + ((.id | ascii_downcase) == (($group + "/providers/" + .type + "/" + .name) | ascii_downcase)) and + (if (.type | ascii_downcase) == "microsoft.containerservice/managedclusters" then + (.name == $hub or .name == $member1 or .name == $member2) and + (.tags["fleet-e2e-atm"] == "true" or .tags["fleet-e2e-atm"] == "false") and + (.tags["fleet-e2e-afd"] == "true" or .tags["fleet-e2e-afd"] == "false") and + (.tags["fleet-e2e-auto-approval"] == "true" or .tags["fleet-e2e-auto-approval"] == "false") and + (if .tags["fleet-e2e-afd"] == "true" and .tags["fleet-e2e-auto-approval"] == "true" then + (.tags["fleet-e2e-test-principal"] | type == "string" and length > 0) + else true end) + else + (.type | ascii_downcase) as $type | + (["microsoft.network/virtualnetworks", "microsoft.network/publicipaddresses", + "microsoft.containerregistry/registries", "microsoft.managedidentity/userassignedidentities"] | index($type)) != null + end) and (.name | ascii_downcase | startswith($prefix)) + else true end) +' <<<"$resources" >/dev/null; then + echo "error: refusing cleanup because a run resource has unexpected ownership, type, name or scope" >&2 + exit 1 +fi + +owned="$(jq --arg run "$E2E_RUN_ID" '[.[] | select(.tags["fleet-e2e-run"] == $run)]' <<<"$resources")" +vnet_names="$(jq -r '.[] | select((.type | ascii_downcase) == "microsoft.network/virtualnetworks") | .name' <<<"$owned")" +read_peerings() { + local name="$1" vnet_id="$group_id/providers/Microsoft.Network/virtualNetworks/$1" peerings + peerings="$(az network vnet peering list --subscription "$AZURE_SUBSCRIPTION_ID" \ + --resource-group "$AZURE_RESOURCE_GROUP" --vnet-name "$name" -o json)" + jq -e --arg vnet "$vnet_id" --argjson owned "$owned" ' + type == "array" and all(.[]; + (.id | ascii_downcase) == (($vnet + "/virtualNetworkPeerings/" + .name) | ascii_downcase) and + (.remoteVirtualNetwork.id | ascii_downcase) as $remote | + any($owned[]; (.type | ascii_downcase) == "microsoft.network/virtualnetworks" and + (.id | ascii_downcase) == $remote and $remote != ($vnet | ascii_downcase))) + ' <<<"$peerings" >/dev/null + printf '%s\n' "$peerings" +} +while IFS= read -r name; do + [[ -n "$name" ]] || continue + read_peerings "$name" >/dev/null +done <<<"$vnet_names" + +profiles="$(jq --arg prefix "$E2E_RESOURCE_PREFIX" '[ + .[] | select( + ((.tags["networking.fleet.azure.com.trafficManagerProfile"] // "") | startswith($prefix + "-")) or + ((.tags["networking.fleet.azure.com.gateway-namespace"] // "") | startswith($prefix + "-"))) +]' <<<"$resources")" +has_hub="$(jq -r --arg hub "$HUB_AZURE_CLUSTER" \ + 'any(.[]; (.type | ascii_downcase) == "microsoft.containerservice/managedclusters" and .name == $hub)' <<<"$owned")" +if [[ "$(jq 'length' <<<"$profiles")" -gt 0 && "$has_hub" != true ]]; then + echo "error: controller profiles remain but the tagged hub cluster is absent; refusing cleanup" >&2 + exit 1 +fi +hub_uid="" +hub_has_controllers="$(jq -r --arg hub "$HUB_AZURE_CLUSTER" ' + any(.[]; (.type | ascii_downcase) == "microsoft.containerservice/managedclusters" and .name == $hub and + (.tags["fleet-e2e-atm"] == "true" or .tags["fleet-e2e-afd"] == "true")) +' <<<"$owned")" +recorded_caller="$(jq -r --arg hub "$HUB_AZURE_CLUSTER" ' + [.[] | select((.type | ascii_downcase) == "microsoft.containerservice/managedclusters" and .name == $hub and + .tags["fleet-e2e-afd"] == "true" and .tags["fleet-e2e-auto-approval"] == "true") | + .tags["fleet-e2e-test-principal"]] | first // "" +' <<<"$owned")" +if [[ -n "$recorded_caller" && "$recorded_caller" != "${E2E_TEST_PRINCIPAL_ID:-}" ]]; then + echo "error: E2E_TEST_PRINCIPAL_ID must match the principal recorded on this run" >&2 + exit 1 +fi +if [[ "$has_hub" == true && ( "$(jq 'length' <<<"$profiles")" -gt 0 || + "$hub_has_controllers" == true ) ]]; then + if [[ -z "${KUBECONFIG:-}" || "$KUBECONFIG" == *:* ]]; then + echo "error: controller cleanup requires the run-specific KUBECONFIG path" >&2 + exit 1 + fi + hub="$(az aks show --subscription "$AZURE_SUBSCRIPTION_ID" --resource-group "$AZURE_RESOURCE_GROUP" --name "$HUB_AZURE_CLUSTER" -o json)" + jq -e --arg id "$group_id/providers/Microsoft.ContainerService/managedClusters/$HUB_AZURE_CLUSTER" --arg run "$E2E_RUN_ID" \ + '(.id | ascii_downcase) == ($id | ascii_downcase) and .tags.source == "fleet-networking" and .tags["fleet-e2e-run"] == $run' \ + <<<"$hub" >/dev/null + az aks get-credentials --subscription "$AZURE_SUBSCRIPTION_ID" --resource-group "$AZURE_RESOURCE_GROUP" \ + --name "$HUB_AZURE_CLUSTER" --admin --context "$HUB_CLUSTER-admin" --overwrite-existing + hub_uid="$(kubectl --context "$HUB_CLUSTER-admin" get namespace kube-system -o jsonpath='{.metadata.uid}')" + if [[ ! "$hub_uid" =~ ^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$ ]]; then + echo "error: could not verify hub UID for controller profile cleanup" >&2 + exit 1 + fi +fi +if [[ "$(jq 'length' <<<"$profiles")" -gt 0 ]]; then + profile_lines="$(jq -c '.[]' <<<"$profiles")" + while IFS= read -r profile; do + type="$(jq -er '.type | ascii_downcase' <<<"$profile")" + name="$(jq -er '.name' <<<"$profile")" + jq -e --arg id "$group_id/providers/$(jq -r '.type' <<<"$profile")/$name" \ + '(.id | ascii_downcase) == ($id | ascii_downcase)' <<<"$profile" >/dev/null + case "$type" in + microsoft.network/trafficmanagerprofiles) + jq -e --arg prefix "$E2E_RESOURCE_PREFIX" ' + (.name | test("^fleet-[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$")) and + (.tags["networking.fleet.azure.com.trafficManagerProfile"] | + test("^" + $prefix + "-[a-z]{5}/[a-z0-9-]+$")) + ' <<<"$profile" >/dev/null + ;; + microsoft.cdn/profiles) + gateway_uid="$(jq -er '.tags["networking.fleet.azure.com.gateway-uid"]' <<<"$profile")" + if [[ ! "$gateway_uid" =~ ^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$ ]]; then + echo "error: invalid Gateway UID on Front Door profile" >&2 + exit 1 + fi + expected_name="fleet-afd-$(printf '%s:%s' "${#gateway_uid}" "$gateway_uid" | sha256sum | cut -c1-32)" + jq -e --arg prefix "$E2E_RESOURCE_PREFIX" --arg hub "$hub_uid" --arg name "$expected_name" ' + .name == $name and .tags["networking.fleet.azure.com.controller"] == "networking.fleet.azure.com/afd" and + .tags["networking.fleet.azure.com.hub-uid"] == $hub and + (.tags["networking.fleet.azure.com.gateway-namespace"] | test("^" + $prefix + "-[a-z]{5}$")) and + (.tags["networking.fleet.azure.com.gateway-name"] | type == "string" and length > 0) + ' <<<"$profile" >/dev/null + ;; + *) echo "error: refusing unrecognized controller profile type $type" >&2; exit 1 ;; + esac + done <<<"$profile_lines" +fi + +principals=() +kubelet_principals=() +node_scopes=() +node_groups=() +identity_names="$(jq -r '.[] | select((.type | ascii_downcase) == "microsoft.managedidentity/userassignedidentities") | .name' <<<"$owned")" +while IFS= read -r name; do + [[ -n "$name" ]] || continue + identity="$(az identity show --subscription "$AZURE_SUBSCRIPTION_ID" --resource-group "$AZURE_RESOURCE_GROUP" --name "$name" -o json)" + jq -e --arg id "$group_id/providers/Microsoft.ManagedIdentity/userAssignedIdentities/$name" --arg run "$E2E_RUN_ID" \ + '(.id | ascii_downcase) == ($id | ascii_downcase) and .tags.source == "fleet-networking" and .tags["fleet-e2e-run"] == $run' \ + <<<"$identity" >/dev/null + principal="$(jq -er '.principalId | select(type == "string" and length > 0)' <<<"$identity")" + principals+=("$principal") +done <<<"$identity_names" +cluster_names="$(jq -r '.[] | select((.type | ascii_downcase) == "microsoft.containerservice/managedclusters") | .name' <<<"$owned")" +while IFS= read -r name; do + [[ -n "$name" ]] || continue + cluster="$(az aks show --subscription "$AZURE_SUBSCRIPTION_ID" --resource-group "$AZURE_RESOURCE_GROUP" --name "$name" -o json)" + jq -e --arg id "$group_id/providers/Microsoft.ContainerService/managedClusters/$name" --arg run "$E2E_RUN_ID" \ + '(.id | ascii_downcase) == ($id | ascii_downcase) and .tags.source == "fleet-networking" and .tags["fleet-e2e-run"] == $run' \ + <<<"$cluster" >/dev/null + node_group="$(jq -r '.nodeResourceGroup // ""' <<<"$cluster")" + if [[ -n "$node_group" ]]; then + exists="$(az group exists --subscription "$AZURE_SUBSCRIPTION_ID" --name "$node_group" -o tsv)" + if [[ "$exists" == true ]]; then + node_group_json="$(az group show --subscription "$AZURE_SUBSCRIPTION_ID" --name "$node_group" -o json)" + node_id="/subscriptions/$AZURE_SUBSCRIPTION_ID/resourceGroups/$node_group" + jq -e --arg id "$node_id" --arg owner "$group_id/providers/Microsoft.ContainerService/managedClusters/$name" \ + '(.id | ascii_downcase) == ($id | ascii_downcase) and (.managedBy | ascii_downcase) == ($owner | ascii_downcase)' \ + <<<"$node_group_json" >/dev/null + node_scopes+=("$node_id") + node_groups+=("$node_group") + elif [[ "$exists" != false ]]; then + echo "error: unable to verify node resource group $node_group" >&2 + exit 1 + fi + fi + kubelet="$(jq -r '.identityProfile.kubeletidentity.objectId // ""' <<<"$cluster")" + if [[ -n "$kubelet" ]]; then + kubelet_principals+=("$kubelet") + fi + cluster_principals="$(jq -r '[.identity.principalId, .identityProfile.kubeletidentity.objectId, + (.identity.userAssignedIdentities // {} | .[]?.principalId)] | .[] | select(type == "string" and length > 0)' <<<"$cluster")" + while IFS= read -r principal; do + [[ -n "$principal" ]] || continue + principals+=("$principal") + done <<<"$cluster_principals" +done <<<"$cluster_names" +principal_json="$(jq -cn '$ARGS.positional' --args "${principals[@]}")" +node_scope_json="$(jq -cn '$ARGS.positional' --args "${node_scopes[@]}")" +kubelet_json="$(jq -cn '$ARGS.positional' --args "${kubelet_principals[@]}")" + +assignments="$(az role assignment list --subscription "$AZURE_SUBSCRIPTION_ID" --all --fill-principal-name false -o json)" +selected_assignments="$(jq -c --arg group "$group_id" --arg caller "$recorded_caller" \ + --argjson principals "$principal_json" --argjson kubelets "$kubelet_json" --argjson nodeScopes "$node_scope_json" ' + [.[] | + (.principalId) as $principal | (.scope | ascii_downcase) as $scope | + (.roleDefinitionId | ascii_downcase | split("/") | last) as $role | + select( + ((($principals | any(. == $principal)) and + ($scope == ($group | ascii_downcase) or ($scope | startswith(($group | ascii_downcase) + "/"))) and + (["acdd72a7-3385-48ef-bd42-f606fba81ae7", "4d97b98b-1d4f-4787-a291-c67834d212e7", + "ec156ff8-a8d1-4d15-830c-5b80698ca432", "de2b316d-7a2c-4143-b4cd-c148f6a355a1", + "f1a07417-d97a-45cb-824c-7a7467783830"] | index($role)) != null) or + (($nodeScopes | any((ascii_downcase) == $scope)) and + ((($kubelets | any(. == $principal)) and + (["acdd72a7-3385-48ef-bd42-f606fba81ae7", "4d97b98b-1d4f-4787-a291-c67834d212e7", + "de2b316d-7a2c-4143-b4cd-c148f6a355a1"] | index($role)) != null) or + ($caller != "" and $principal == $caller and $role == "4d97b98b-1d4f-4787-a291-c67834d212e7")))) + ) | {id, scope, name}] +' <<<"$assignments")" +if ! jq -e 'all(.[]; + (.name | test("^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$")) and + ((.id | ascii_downcase) == ((.scope + "/providers/Microsoft.Authorization/roleAssignments/" + .name) | ascii_downcase))) +' <<<"$selected_assignments" >/dev/null; then + echo "error: refusing role assignment with unexpected identity or scope" >&2 + exit 1 +fi +node_assignment_ids="$(jq -r --argjson scopes "$node_scope_json" \ + '.[] | select((.scope | ascii_downcase) as $scope | $scopes | any((ascii_downcase) == $scope)) | .id' <<<"$selected_assignments")" +group_assignment_ids="$(jq -r --arg group "$group_id" \ + '.[] | select((.scope | ascii_downcase) == ($group | ascii_downcase) or + (.scope | ascii_downcase | startswith(($group | ascii_downcase) + "/"))) | .id' <<<"$selected_assignments")" + +if [[ -n "$hub_uid" ]]; then + for deployment in hub-net-controller-manager hub-gateway-controller-manager; do + existing="$(kubectl --context "$HUB_CLUSTER-admin" -n fleet-system get deployment "$deployment" --ignore-not-found -o name)" + if [[ -n "$existing" ]]; then + kubectl --context "$HUB_CLUSTER-admin" -n fleet-system scale "$existing" --replicas=0 + kubectl --context "$HUB_CLUSTER-admin" -n fleet-system rollout status "$existing" --timeout=120s + fi + done + current_resources="$(az resource list --subscription "$AZURE_SUBSCRIPTION_ID" --resource-group "$AZURE_RESOURCE_GROUP" -o json)" + current_profiles="$(jq -Sc --arg prefix "$E2E_RESOURCE_PREFIX" '[ + .[] | select( + ((.tags["networking.fleet.azure.com.trafficManagerProfile"] // "") | startswith($prefix + "-")) or + ((.tags["networking.fleet.azure.com.gateway-namespace"] // "") | startswith($prefix + "-"))) + ] | sort_by(.id)' <<<"$current_resources")" + if [[ "$current_profiles" != "$(jq -Sc 'sort_by(.id)' <<<"$profiles")" ]]; then + echo "error: controller profiles changed during cleanup; retry to verify their ownership" >&2 + exit 1 + fi +fi +if [[ "$(jq 'length' <<<"$profiles")" -gt 0 ]]; then + while IFS= read -r profile; do + id="$(jq -er '.id' <<<"$profile")" + current="$(az resource show --ids "$id" -o json)" + jq -e --argjson expected "$profile" \ + '(.id | ascii_downcase) == ($expected.id | ascii_downcase) and .tags == $expected.tags' <<<"$current" >/dev/null + az resource delete --ids "$id" + done <<<"$profile_lines" +fi + +while IFS= read -r id; do + [[ -n "$id" ]] || continue + az role assignment delete --ids "$id" +done <<<"$node_assignment_ids" + +while IFS= read -r name; do + [[ -n "$name" ]] || continue + cluster="$(az aks show --subscription "$AZURE_SUBSCRIPTION_ID" --resource-group "$AZURE_RESOURCE_GROUP" --name "$name" -o json)" + jq -e --arg id "$group_id/providers/Microsoft.ContainerService/managedClusters/$name" --arg run "$E2E_RUN_ID" \ + '(.id | ascii_downcase) == ($id | ascii_downcase) and .tags.source == "fleet-networking" and .tags["fleet-e2e-run"] == $run' \ + <<<"$cluster" >/dev/null + az aks delete --subscription "$AZURE_SUBSCRIPTION_ID" --resource-group "$AZURE_RESOURCE_GROUP" --name "$name" --yes --no-wait +done <<<"$cluster_names" +while IFS= read -r name; do + [[ -n "$name" ]] || continue + az aks wait --subscription "$AZURE_SUBSCRIPTION_ID" --resource-group "$AZURE_RESOURCE_GROUP" --name "$name" --deleted --interval 15 --timeout 900 +done <<<"$cluster_names" +for node_group in "${node_groups[@]}"; do + az group wait --subscription "$AZURE_SUBSCRIPTION_ID" --name "$node_group" --deleted --interval 15 --timeout 900 +done +while IFS= read -r id; do + [[ -n "$id" ]] || continue + az role assignment delete --ids "$id" +done <<<"$group_assignment_ids" + +while IFS= read -r name; do + [[ -n "$name" ]] || continue + peerings="$(read_peerings "$name")" + peering_ids="$(jq -r '.[].id' <<<"$peerings")" + while IFS= read -r id; do + [[ -n "$id" ]] || continue + az network vnet peering delete --ids "$id" + done <<<"$peering_ids" +done <<<"$vnet_names" + +for type in Microsoft.Network/publicIPAddresses Microsoft.Network/virtualNetworks Microsoft.ContainerRegistry/registries Microsoft.ManagedIdentity/userAssignedIdentities; do + resource_ids="$(jq -r --arg type "$type" '.[] | select((.type | ascii_downcase) == ($type | ascii_downcase)) | .id' <<<"$owned")" + while IFS= read -r id; do + [[ -n "$id" ]] || continue + current="$(az resource show --ids "$id" -o json)" + jq -e --arg id "$id" --arg run "$E2E_RUN_ID" \ + '(.id | ascii_downcase) == ($id | ascii_downcase) and .tags.source == "fleet-networking" and .tags["fleet-e2e-run"] == $run' \ + <<<"$current" >/dev/null + az resource delete --ids "$id" + done <<<"$resource_ids" +done + +remaining="$(az resource list --subscription "$AZURE_SUBSCRIPTION_ID" --resource-group "$AZURE_RESOURCE_GROUP" -o json)" +if ! jq -e --arg run "$E2E_RUN_ID" --arg prefix "$E2E_RESOURCE_PREFIX" ' + all(.[]; + .tags["fleet-e2e-run"] != $run and + ((.tags["networking.fleet.azure.com.trafficManagerProfile"] // "") | startswith($prefix + "-") | not) and + ((.tags["networking.fleet.azure.com.gateway-namespace"] // "") | startswith($prefix + "-") | not)) +' <<<"$remaining" >/dev/null; then + echo "error: run-owned resources remain after cleanup" >&2 + exit 1 +fi diff --git a/test/scripts/cleanup.sh b/test/scripts/cleanup.sh index 594127be..65e4bff7 100644 --- a/test/scripts/cleanup.sh +++ b/test/scripts/cleanup.sh @@ -18,4 +18,12 @@ esac [[ -z "${AZURE_RESOURCE_GROUP}" ]] && echo "AZURE_RESOURCE_GROUP is not set" && exit 1 +if [[ "${E2E_SHARED_RESOURCE_GROUP:-false}" == true ]]; then + exec bash "$(dirname "${BASH_SOURCE[0]}")/cleanup-shared-group.sh" +fi +if [[ "${E2E_SHARED_RESOURCE_GROUP:-false}" != false ]]; then + echo "error: E2E_SHARED_RESOURCE_GROUP must be true or false" >&2 + exit 1 +fi + az group show --name "$AZURE_RESOURCE_GROUP" && az group delete --name "$AZURE_RESOURCE_GROUP" --no-wait --yes diff --git a/test/scripts/e2e-config.sh b/test/scripts/e2e-config.sh index 5394ee0a..0b1af37e 100644 --- a/test/scripts/e2e-config.sh +++ b/test/scripts/e2e-config.sh @@ -4,6 +4,57 @@ export ENABLE_TRAFFIC_MANAGER="${ENABLE_TRAFFIC_MANAGER:-false}" export ENABLE_AZURE_FRONT_DOOR="${ENABLE_AZURE_FRONT_DOOR:-false}" export RETAIN_AFD_E2E_SETUP="${RETAIN_AFD_E2E_SETUP:-false}" export AZURE_NETWORK_SETTING="${AZURE_NETWORK_SETTING:-shared-vnet}" +export E2E_SHARED_RESOURCE_GROUP="${E2E_SHARED_RESOURCE_GROUP:-false}" + +case "$E2E_SHARED_RESOURCE_GROUP" in + false) + unset E2E_RESOURCE_PREFIX HUB_AZURE_CLUSTER MEMBER_1_AZURE_CLUSTER MEMBER_2_AZURE_CLUSTER + ;; + true) + if [[ "$ENABLE_TRAFFIC_MANAGER" != true && "$ENABLE_TRAFFIC_MANAGER" != false ]]; then + echo "error: ENABLE_TRAFFIC_MANAGER must be true or false in shared mode" >&2 + return 1 + fi + if [[ -z "${AZURE_SUBSCRIPTION_ID:-}" || -z "${AZURE_RESOURCE_GROUP:-}" || + ! "${E2E_RUN_ID:-}" =~ ^[a-z0-9][a-z0-9-]{0,62}$ ]]; then + echo "error: shared resource group mode requires subscription, resource group and a lowercase alphanumeric E2E_RUN_ID" >&2 + return 1 + fi + if [[ "$AZURE_NETWORK_SETTING" == perf-test ]]; then + echo "error: shared resource group mode does not support perf-test" >&2 + return 1 + fi + if [[ "${HUB_CLUSTER:-hub}" != hub || "${MEMBER_CLUSTER_1:-member-1}" != member-1 || + "${MEMBER_CLUSTER_2:-member-2}" != member-2 ]]; then + echo "error: shared resource group mode requires default logical cluster names" >&2 + return 1 + fi + E2E_RESOURCE_PREFIX="fne$(printf '%s' "$AZURE_SUBSCRIPTION_ID/$AZURE_RESOURCE_GROUP/$E2E_RUN_ID" | sha256sum | cut -c1-16)" + export E2E_RESOURCE_PREFIX + export HUB_AZURE_CLUSTER="${E2E_RESOURCE_PREFIX}-hub" + export MEMBER_1_AZURE_CLUSTER="${E2E_RESOURCE_PREFIX}-member1" + export MEMBER_2_AZURE_CLUSTER="${E2E_RESOURCE_PREFIX}-member2" + export REGISTRY_NAME="${E2E_RESOURCE_PREFIX}acr" + export REGISTRY="${REGISTRY_NAME}.azurecr.io" + export HUB_CLUSTER_AKS_ID_NAME="${E2E_RESOURCE_PREFIX}-hub-control" + export HUB_CLUSTER_AKS_KUBELET_ID_NAME="${E2E_RESOURCE_PREFIX}-hub-kubelet" + export MEMBER_CLUSTER_1_AKS_ID_NAME="${E2E_RESOURCE_PREFIX}-member1-control" + export MEMBER_CLUSTER_1_AKS_KUBELET_ID_NAME="${E2E_RESOURCE_PREFIX}-member1-kubelet" + export MEMBER_CLUSTER_2_AKS_ID_NAME="${E2E_RESOURCE_PREFIX}-member2-control" + export MEMBER_CLUSTER_2_AKS_KUBELET_ID_NAME="${E2E_RESOURCE_PREFIX}-member2-kubelet" + ;; + *) + echo "error: E2E_SHARED_RESOURCE_GROUP must be true or false" >&2 + return 1 + ;; +esac +export HUB_CLUSTER="${HUB_CLUSTER:-hub}" +export MEMBER_CLUSTER_1="${MEMBER_CLUSTER_1:-member-1}" +export MEMBER_CLUSTER_2="${MEMBER_CLUSTER_2:-member-2}" +export HUB_AZURE_CLUSTER="${HUB_AZURE_CLUSTER:-$HUB_CLUSTER}" +export MEMBER_1_AZURE_CLUSTER="${MEMBER_1_AZURE_CLUSTER:-$MEMBER_CLUSTER_1}" +export MEMBER_2_AZURE_CLUSTER="${MEMBER_2_AZURE_CLUSTER:-$MEMBER_CLUSTER_2}" +E2E_RESOURCE_TAGS=() if [[ "$ENABLE_AZURE_FRONT_DOOR" != true && "$ENABLE_AZURE_FRONT_DOOR" != false ]]; then echo "error: ENABLE_AZURE_FRONT_DOOR must be true or false" >&2 @@ -33,6 +84,17 @@ if [[ "$ENABLE_AZURE_FRONT_DOOR" == true ]]; then echo "error: AFD requires AZURE_SUBSCRIPTION_ID and AZURE_RESOURCE_GROUP" >&2 return 1 fi + if [[ "$E2E_SHARED_RESOURCE_GROUP" == true && "$ENABLE_AFD_PRIVATE_LINK_AUTO_APPROVAL" == true && + ! "${E2E_TEST_PRINCIPAL_ID:-}" =~ ^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$ ]]; then + echo "error: shared AFD approval requires E2E_TEST_PRINCIPAL_ID" >&2 + return 1 + fi + if [[ "$E2E_SHARED_RESOURCE_GROUP" == true && + ( "${AFD_PROOF_CONTROLLER_NAMESPACE:-fleet-system}" != fleet-system || + "${AFD_PROOF_CONTROLLER_DEPLOYMENT:-hub-gateway-controller-manager}" != hub-gateway-controller-manager ) ]]; then + echo "error: shared AFD mode requires the default controller namespace and deployment" >&2 + return 1 + fi if [[ "${HUB_CLUSTER:-hub}" != hub || "${MEMBER_CLUSTER_1:-member-1}" != member-1 || "${MEMBER_CLUSTER_2:-member-2}" != member-2 ]]; then echo "error: AFD proof requires default hub/member cluster names" >&2 @@ -41,7 +103,11 @@ if [[ "$ENABLE_AZURE_FRONT_DOOR" == true ]]; then export ENABLE_GATEWAY_API=true export ENABLE_AFD_PRIVATE_HTTP_PROOF=true # Derive the same candidate in separate setup/test shells; do not rely on child exports. - export REGISTRY="${AZURE_RESOURCE_GROUP//-}.azurecr.io" + if [[ "$E2E_SHARED_RESOURCE_GROUP" == true ]]; then + export REGISTRY="${REGISTRY_NAME}.azurecr.io" + else + export REGISTRY="${AZURE_RESOURCE_GROUP//-}.azurecr.io" + fi if [[ -z "${TAG:-}" ]]; then TAG="$(git rev-parse --short=7 HEAD)" || return 1 export TAG @@ -50,3 +116,12 @@ if [[ "$ENABLE_AZURE_FRONT_DOOR" == true ]]; then export AFD_PROOF_CONTROLLER_DEPLOYMENT="${AFD_PROOF_CONTROLLER_DEPLOYMENT:-hub-gateway-controller-manager}" export AFD_PROOF_CONTROLLER_IMAGE="${REGISTRY}/${HUB_GATEWAY_CONTROLLER_MANAGER_IMAGE_NAME:-hub-gateway-controller-manager}:${HUB_GATEWAY_CONTROLLER_MANAGER_IMAGE_VERSION:-$TAG}" fi + +if [[ "$E2E_SHARED_RESOURCE_GROUP" == true ]]; then + E2E_RESOURCE_TAGS=(--tags "source=fleet-networking" "fleet-e2e-run=$E2E_RUN_ID" + "fleet-e2e-atm=$ENABLE_TRAFFIC_MANAGER" "fleet-e2e-afd=$ENABLE_AZURE_FRONT_DOOR" + "fleet-e2e-auto-approval=$ENABLE_AFD_PRIVATE_LINK_AUTO_APPROVAL") + if [[ "$ENABLE_AZURE_FRONT_DOOR" == true && "$ENABLE_AFD_PRIVATE_LINK_AUTO_APPROVAL" == true ]]; then + E2E_RESOURCE_TAGS+=("fleet-e2e-test-principal=$E2E_TEST_PRINCIPAL_ID") + fi +fi diff --git a/test/scripts/install-afd.sh b/test/scripts/install-afd.sh index 35b43101..ba9184e3 100644 --- a/test/scripts/install-afd.sh +++ b/test/scripts/install-afd.sh @@ -19,19 +19,20 @@ cloud_config() { }' } -hub="$(az aks show --subscription "$AZURE_SUBSCRIPTION_ID" --resource-group "$AZURE_RESOURCE_GROUP" --name hub)" +hub="$(az aks show --subscription "$AZURE_SUBSCRIPTION_ID" --resource-group "$AZURE_RESOURCE_GROUP" --name "$HUB_AZURE_CLUSTER")" hub_principal="$(jq -er '.identityProfile.kubeletidentity.objectId' <<<"$hub")" base="/subscriptions/$AZURE_SUBSCRIPTION_ID/resourceGroups" declare -A clusters node_groups # Validate both AKS-managed node groups before any role assignments. for member in member-1 member-2; do - cluster="$(az aks show --subscription "$AZURE_SUBSCRIPTION_ID" --resource-group "$AZURE_RESOURCE_GROUP" --name "$member")" + if [[ "$member" == member-1 ]]; then azure_cluster="$MEMBER_1_AZURE_CLUSTER"; else azure_cluster="$MEMBER_2_AZURE_CLUSTER"; fi + cluster="$(az aks show --subscription "$AZURE_SUBSCRIPTION_ID" --resource-group "$AZURE_RESOURCE_GROUP" --name "$azure_cluster")" cluster_id="$(jq -er '.id' <<<"$cluster")" node_group="$(jq -er '.nodeResourceGroup' <<<"$cluster")" group="$(az group show --subscription "$AZURE_SUBSCRIPTION_ID" --name "$node_group")" group_id="$(jq -er '.id' <<<"$group")" managed_by="$(jq -er '.managedBy' <<<"$group")" - expected_cluster="$base/$AZURE_RESOURCE_GROUP/providers/Microsoft.ContainerService/managedClusters/$member" + expected_cluster="$base/$AZURE_RESOURCE_GROUP/providers/Microsoft.ContainerService/managedClusters/$azure_cluster" expected_group="$base/$node_group" if [[ "${cluster_id,,}" != "${expected_cluster,,}" || "${managed_by,,}" != "${cluster_id,,}" || "${group_id,,}" != "${expected_group,,}" ]]; then @@ -66,6 +67,11 @@ for member in member-1 member-2; do az role assignment create --subscription "$AZURE_SUBSCRIPTION_ID" --role Reader \ --assignee-object-id "$principal" --assignee-principal-type ServicePrincipal \ --scope "/subscriptions/$AZURE_SUBSCRIPTION_ID/resourceGroups/$node_group" >/dev/null + if [[ "$E2E_SHARED_RESOURCE_GROUP" == true && "$ENABLE_AFD_PRIVATE_LINK_AUTO_APPROVAL" == true ]]; then + az role assignment create --subscription "$AZURE_SUBSCRIPTION_ID" --role "Network Contributor" \ + --assignee-object-id "$E2E_TEST_PRINCIPAL_ID" --assignee-principal-type ServicePrincipal \ + --scope "/subscriptions/$AZURE_SUBSCRIPTION_ID/resourceGroups/$node_group" >/dev/null + fi config="$(cloud_config "$client" "$node_group" "$location")" helm upgrade member-net-controller-manager ./charts/member-net-controller-manager \ --kube-context "$member-admin" --namespace default --reuse-values \ diff --git a/test/scripts/shared_group_test.go b/test/scripts/shared_group_test.go new file mode 100644 index 00000000..bdc8f7b7 --- /dev/null +++ b/test/scripts/shared_group_test.go @@ -0,0 +1,487 @@ +/* +Copyright (c) Microsoft Corporation. +Licensed under the MIT license. +*/ + +package scripts + +import ( + "crypto/sha256" + "encoding/json" + "fmt" + "os" + "path/filepath" + "strconv" + "strings" + "testing" +) + +func TestSharedGroupConfiguration(t *testing.T) { + afdTestEnvironment(t) + run := func(id string) (string, error) { + t.Helper() + t.Setenv("E2E_SHARED_RESOURCE_GROUP", "true") + t.Setenv("E2E_RUN_ID", id) + t.Setenv("AZURE_SUBSCRIPTION_ID", "test-subscription") + t.Setenv("AZURE_RESOURCE_GROUP", "fleet-networking-e2e") + t.Setenv("AZURE_NETWORK_SETTING", "shared-vnet") + return runAFDScript(t, "-ec", `source ./e2e-config.sh +printf '%s|%s|%s|%s|%s\n' "$E2E_RESOURCE_PREFIX" "$HUB_AZURE_CLUSTER" "$MEMBER_1_AZURE_CLUSTER" "$MEMBER_2_AZURE_CLUSTER" "$REGISTRY_NAME"`) + } + first, err := run("123-atm-1") + if err != nil { + t.Fatal(err) + } + repeated, err := run("123-atm-1") + if err != nil || repeated != first { + t.Fatalf("run identity must be deterministic: %q, %q, %v", first, repeated, err) + } + other, err := run("123-afd-1") + if err != nil || other == first { + t.Fatalf("concurrent scenarios must not share names: %q, %q, %v", first, other, err) + } + for _, invalid := range []string{"", "../other", "ABC", "trailing space"} { + output, err := run(invalid) + if err == nil || !strings.Contains(output, "E2E_RUN_ID") { + t.Fatalf("invalid run ID %q was accepted: %s (%v)", invalid, output, err) + } + } + t.Setenv("ENABLE_AZURE_FRONT_DOOR", "true") + t.Setenv("E2E_TEST_PRINCIPAL_ID", "") + output, err := run("123-afd-1") + if err == nil || !strings.Contains(output, "E2E_TEST_PRINCIPAL_ID") { + t.Fatalf("shared AFD must reject missing principal ID: %s (%v)", output, err) + } +} + +func TestSharedAFDInstallation(t *testing.T) { + afdTestEnvironment(t) + t.Setenv("E2E_SHARED_RESOURCE_GROUP", "true") + t.Setenv("E2E_RUN_ID", "123-afd-1") + t.Setenv("ENABLE_AZURE_FRONT_DOOR", "true") + t.Setenv("E2E_TEST_PRINCIPAL_ID", "44444444-4444-4444-4444-444444444444") + log := installAFDCommandStubs(t) + output, err := runAFDScript(t, "./install-afd.sh") + if err != nil { + t.Fatalf("shared AFD installation: %s (%v)", output, err) + } + + testTopologyNames := func(t *testing.T) { + tests := []struct { + name, script, network, atm string + }{ + {"traffic manager", "./aks-shared-vnet.sh", "shared-vnet", "true"}, + {"front door", "./aks-shared-vnet.sh", "shared-vnet", "false"}, + {"peered", "./aks-peered-vnet.sh", "peered-vnet", "false"}, + {"dynamic", "./aks-dynamic-ip-allocation.sh", "dynamic-ip-allocation", "false"}, + {"unsupported", "./aks-no-networking.sh", "unsupported", "false"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + afdTestEnvironment(t) + t.Setenv("E2E_SHARED_RESOURCE_GROUP", "true") + t.Setenv("E2E_RUN_ID", "123-"+tt.network+"-1") + t.Setenv("ENABLE_TRAFFIC_MANAGER", tt.atm) + t.Setenv("AZURE_NETWORK_SETTING", tt.network) + t.Setenv("RESOURCE_GROUP", "test-rg") + t.Setenv("NODE_COUNT", "2") + t.Setenv("MEMBER_1_LOCATION", "eastus2") + t.Setenv("MEMBER_2_LOCATION", "westus") + t.Setenv("MEMBER_CLUSTER_1_AKS_IDENTITY_ID", "/identity/member1-control") + t.Setenv("MEMBER_CLUSTER_1_AKS_KUBELET_IDENTITY_ID", "/identity/member1-kubelet") + t.Setenv("MEMBER_CLUSTER_2_AKS_IDENTITY_ID", "/identity/member2-control") + t.Setenv("MEMBER_CLUSTER_2_AKS_KUBELET_IDENTITY_ID", "/identity/member2-kubelet") + dir := t.TempDir() + t.Setenv("TEST_CALLS", filepath.Join(dir, "calls")) + t.Setenv("KUBECONFIG", filepath.Join(dir, "kubeconfig")) + writeAFDCommand(t, filepath.Join(dir, "az"), `#!/bin/bash + printf '%s\n' "$*" >> "$TEST_CALLS" + if [[ "$*" == "network vnet show "* ]]; then echo "/subscriptions/test-subscription/resourceGroups/test-rg/providers/Microsoft.Network/virtualNetworks/test"; fi + `) + t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH")) + output, err := runAFDScript(t, tt.script) + if err != nil { + t.Fatalf("topology: %s (%v)", output, err) + } + hash := sha256.Sum256([]byte("test-subscription/test-rg/123-" + tt.network + "-1")) + prefix := fmt.Sprintf("fne%x", hash[:8]) + calls := readAFDFile(t, filepath.Join(dir, "calls")) + for _, name := range []string{prefix + "-member1", prefix + "-member2"} { + if !strings.Contains(calls, "--name "+name) { + t.Errorf("missing physical cluster %s in %s", name, calls) + } + } + if strings.Count(calls, "fleet-e2e-run=123-"+tt.network+"-1") < 2 { + t.Fatalf("cluster ownership tags missing: %s", calls) + } + if tt.network != "unsupported" { + created := 0 + for _, call := range strings.Split(calls, "\n") { + if strings.HasPrefix(call, "network vnet create ") { + created++ + if !strings.Contains(call, "--name "+prefix+"-") { + t.Fatalf("VNet name is not run-specific: %s", call) + } + } + } + if created == 0 { + t.Fatalf("no VNet created: %s", calls) + } + } + }) + } + } + + testBootstrapPreflight := func(t *testing.T) { + for _, tc := range []struct { + name string + conflict, existingConfig bool + }{{"clean", false, false}, {"resource collision", true, false}, {"existing kubeconfig", false, true}} { + t.Run(tc.name, func(t *testing.T) { + afdTestEnvironment(t) + t.Setenv("E2E_SHARED_RESOURCE_GROUP", "true") + t.Setenv("E2E_RUN_ID", "123-atm-1") + t.Setenv("AZURE_RESOURCE_GROUP", "fleet-networking-e2e") + dir := t.TempDir() + t.Setenv("KUBECONFIG", filepath.Join(dir, "kubeconfig")) + t.Setenv("TEST_CALLS", filepath.Join(dir, "calls")) + if tc.existingConfig { + if err := os.WriteFile(filepath.Join(dir, "kubeconfig"), []byte("existing"), 0o600); err != nil { + t.Fatal(err) + } + } + if tc.conflict { + hash := sha256.Sum256([]byte("test-subscription/fleet-networking-e2e/123-atm-1")) + t.Setenv("TEST_RESOURCE_NAME", fmt.Sprintf("fne%x-hub", hash[:8])) + } else { + t.Setenv("TEST_RESOURCE_NAME", "") + } + writeAFDCommand(t, filepath.Join(dir, "yq"), "#!/bin/bash\nexit 0\n") + writeAFDCommand(t, filepath.Join(dir, "az"), `#!/bin/bash + set -euo pipefail + printf '%s\n' "$*" >> "$TEST_CALLS" + case "$1 $2" in + "account set") ;; + "group show") printf '%s\n' '{"id":"/subscriptions/test-subscription/resourceGroups/fleet-networking-e2e","tags":{"managedBy":"aks-rp/ci-resources","workload":"fleet-networking-e2e"}}' ;; + "resource list") if [[ -n "$TEST_RESOURCE_NAME" ]]; then jq -cn --arg name "$TEST_RESOURCE_NAME" '[{name:$name,tags:{}}]'; else echo '[]'; fi ;; + "acr create") echo "injected create failure" >&2; exit 23 ;; + *) echo "unexpected Azure operation: $*" >&2; exit 1 ;; + esac + `) + t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH")) + output, err := runAFDScript(t, "./bootstrap.sh") + if err == nil { + t.Fatal("expected a preflight conflict or injected create failure") + } + calls := readAFDFile(t, filepath.Join(dir, "calls")) + if strings.Contains(calls, "group create") || strings.Contains(calls, "group delete") { + t.Fatalf("shared setup touched the resource group: %s", calls) + } + if (tc.conflict || tc.existingConfig) && (strings.Contains(calls, "acr create") || strings.Contains(output, "##vso[task.setvariable variable=e2eResourcesStarted]true")) { + t.Fatalf("collision was not rejected before cleanup became eligible: %s, %s", calls, output) + } + if !tc.conflict && !tc.existingConfig && (!strings.Contains(calls, "acr create") || !strings.Contains(output, "##vso[task.setvariable variable=e2eResourcesStarted]true")) { + t.Fatalf("successful preflight did not enable cleanup before resource creation: %s, %s", calls, output) + } + }) + } + } + t.Run("topology names", testTopologyNames) + t.Run("bootstrap preflight", testBootstrapPreflight) + hash := sha256.Sum256([]byte("test-subscription/test-rg/123-afd-1")) + prefix := fmt.Sprintf("fne%x", hash[:8]) + calls := readAFDFile(t, log) + for _, want := range []string{ + "--name " + prefix + "-hub", + "--name " + prefix + "-member1", + "--name " + prefix + "-member2", + "--kube-context member-1-admin", + "--kube-context member-2-admin", + "--assignee-object-id 44444444-4444-4444-4444-444444444444", + "--scope /subscriptions/test-subscription/resourceGroups/MC_" + prefix + "-member1", + "--scope /subscriptions/test-subscription/resourceGroups/MC_" + prefix + "-member2", + } { + if !strings.Contains(calls, want) { + t.Errorf("missing %q in calls:\n%s", want, calls) + } + } + if strings.Count(calls, "--role Network Contributor") != 2 { + t.Fatalf("expected one test-caller Network Contributor grant per member: %s", calls) + } +} + +func TestSharedGroupCleanupOwnership(t *testing.T) { + tests := []struct { + name string + conflict bool + profile bool + wantDeletes bool + }{ + {"owned resources", false, false, true}, + {"foreign resource with colliding name", true, false, false}, + {"controller profile still present", false, true, false}, + } + + testControllerAndPeerings := func(t *testing.T) { + for _, tc := range []struct { + name string + invalidOwner, foreignPeer, lateProfile, principalMismatch, noProfiles bool + }{{"valid", false, false, false, false, false}, {"wrong hub UID", true, false, false, false, false}, + {"foreign peering", false, true, false, false, false}, {"profile changed after stop", false, false, true, false, false}, + {"different test principal", false, false, false, true, false}, {"no profiles yet", false, false, false, false, true}} { + t.Run(tc.name, func(t *testing.T) { + afdTestEnvironment(t) + t.Setenv("E2E_SHARED_RESOURCE_GROUP", "true") + t.Setenv("E2E_RUN_ID", "123-afd-1") + t.Setenv("AZURE_SUBSCRIPTION_ID", "test-subscription") + t.Setenv("AZURE_RESOURCE_GROUP", "fleet-networking-e2e") + t.Setenv("E2E_TEST_PRINCIPAL_ID", "44444444-4444-4444-4444-444444444444") + if tc.principalMismatch { + t.Setenv("E2E_TEST_PRINCIPAL_ID", "66666666-6666-6666-6666-666666666666") + } + dir := t.TempDir() + t.Setenv("KUBECONFIG", filepath.Join(dir, "kubeconfig")) + group := "/subscriptions/test-subscription/resourceGroups/fleet-networking-e2e" + hash := sha256.Sum256([]byte("test-subscription/fleet-networking-e2e/123-afd-1")) + prefix := fmt.Sprintf("fne%x", hash[:8]) + hub := prefix + "-hub" + hubID := group + "/providers/Microsoft.ContainerService/managedClusters/" + hub + nodeGroup := "MC_fleet_e2e_hub" + nodeID := "/subscriptions/test-subscription/resourceGroups/" + nodeGroup + vnet1 := group + "/providers/Microsoft.Network/virtualNetworks/" + prefix + "-member-1-vnet" + vnet2 := group + "/providers/Microsoft.Network/virtualNetworks/" + prefix + "-member-2-vnet" + tags := map[string]string{"source": "fleet-networking", "fleet-e2e-run": "123-afd-1", + "fleet-e2e-atm": "false", "fleet-e2e-afd": "true", "fleet-e2e-auto-approval": "true", + "fleet-e2e-test-principal": "44444444-4444-4444-4444-444444444444"} + uid := "11111111-1111-1111-1111-111111111111" + gatewayUID := "22222222-2222-2222-2222-222222222222" + gatewayHash := sha256.Sum256([]byte(fmt.Sprintf("%d:%s", len(gatewayUID), gatewayUID))) + profileName := fmt.Sprintf("fleet-afd-%x", gatewayHash[:16]) + profileID := group + "/providers/Microsoft.Cdn/profiles/" + profileName + trafficProfileID := group + "/providers/Microsoft.Network/trafficManagerProfiles/fleet-55555555-5555-5555-5555-555555555555" + profileTags := map[string]string{ + "networking.fleet.azure.com.controller": "networking.fleet.azure.com/afd", + "networking.fleet.azure.com.hub-uid": uid, + "networking.fleet.azure.com.gateway-namespace": prefix + "-abcde", + "networking.fleet.azure.com.gateway-name": "private-http", + "networking.fleet.azure.com.gateway-uid": gatewayUID, + } + if tc.invalidOwner { + profileTags["networking.fleet.azure.com.hub-uid"] = "33333333-3333-3333-3333-333333333333" + } + items := []map[string]interface{}{ + {"id": hubID, "name": hub, "type": "Microsoft.ContainerService/managedClusters", "tags": tags, + "nodeResourceGroup": nodeGroup, "identity": map[string]interface{}{"principalId": "hub-principal"}, + "identityProfile": map[string]interface{}{"kubeletidentity": map[string]string{"objectId": "hub-kubelet"}}}, + {"id": vnet1, "name": prefix + "-member-1-vnet", "type": "Microsoft.Network/virtualNetworks", "tags": tags}, + {"id": vnet2, "name": prefix + "-member-2-vnet", "type": "Microsoft.Network/virtualNetworks", "tags": tags}, + {"id": profileID, "name": profileName, "type": "Microsoft.Cdn/profiles", "tags": profileTags}, + {"id": trafficProfileID, "name": "fleet-55555555-5555-5555-5555-555555555555", "type": "Microsoft.Network/trafficManagerProfiles", + "tags": map[string]string{"networking.fleet.azure.com.trafficManagerProfile": prefix + "-fghij/hello-world-service"}}, + } + if tc.noProfiles { + items = items[:3] + } + peerings := []map[string]interface{}{ + {"id": vnet1 + "/virtualNetworkPeerings/to-two", "name": "to-two", "remoteVirtualNetwork": map[string]string{"id": vnet2}}, + {"id": vnet2 + "/virtualNetworkPeerings/to-one", "name": "to-one", "remoteVirtualNetwork": map[string]string{"id": vnet1}}, + } + if tc.foreignPeer { + peerings[0]["remoteVirtualNetwork"] = map[string]string{"id": group + "/providers/Microsoft.Network/virtualNetworks/foreign"} + } + assignments := []map[string]string{ + {"id": group + "/providers/Microsoft.Authorization/roleAssignments/aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa", "scope": group, "name": "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa", + "principalId": "hub-principal", "roleDefinitionId": "/providers/Microsoft.Authorization/roleDefinitions/de2b316d-7a2c-4143-b4cd-c148f6a355a1"}, + {"id": group + "/providers/Microsoft.Authorization/roleAssignments/foreign", "scope": group, + "principalId": "foreign-principal", "roleDefinitionId": "/providers/Microsoft.Authorization/roleDefinitions/de2b316d-7a2c-4143-b4cd-c148f6a355a1"}, + {"id": nodeID + "/providers/Microsoft.Authorization/roleAssignments/bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb", "scope": nodeID, "name": "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb", + "principalId": "hub-kubelet", "roleDefinitionId": "/providers/Microsoft.Authorization/roleDefinitions/acdd72a7-3385-48ef-bd42-f606fba81ae7"}, + {"id": nodeID + "/providers/Microsoft.Authorization/roleAssignments/cccccccc-cccc-cccc-cccc-cccccccccccc", "scope": nodeID, "name": "cccccccc-cccc-cccc-cccc-cccccccccccc", + "principalId": "44444444-4444-4444-4444-444444444444", "roleDefinitionId": "/providers/Microsoft.Authorization/roleDefinitions/4d97b98b-1d4f-4787-a291-c67834d212e7"}, + } + for name, value := range map[string]interface{}{"inventory": items, "peerings": peerings, "assignments": assignments} { + data, err := json.Marshal(value) + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, name), data, 0o600); err != nil { + t.Fatal(err) + } + } + t.Setenv("TEST_DIR", dir) + t.Setenv("TEST_UID", uid) + t.Setenv("TEST_HUB_ID", hubID) + t.Setenv("TEST_NODE_ID", nodeID) + t.Setenv("TEST_LATE_PROFILE", strconv.FormatBool(tc.lateProfile)) + writeAFDCommand(t, filepath.Join(dir, "az"), `#!/bin/bash + set -euo pipefail + printf 'az %s\n' "$*" >> "$TEST_DIR/calls" + option() { local key="$1"; shift; while (($#)); do if [[ "$1" == "$key" ]]; then printf '%s' "$2"; return; fi; shift; done; return 1; } + case "$1 $2 $3" in + "group show --subscription") + name="$(option --name "$@")" + if [[ "$name" == fleet-networking-e2e ]]; then + printf '%s\n' '{"id":"/subscriptions/test-subscription/resourceGroups/fleet-networking-e2e","tags":{"managedBy":"aks-rp/ci-resources","workload":"fleet-networking-e2e"}}' + else jq -cn --arg id "$TEST_NODE_ID" --arg owner "$TEST_HUB_ID" '{id:$id,managedBy:$owner}'; fi ;; + "group exists --subscription") echo true ;; + "group wait --subscription") ;; + "resource list --subscription") + count=0; if [[ -e "$TEST_DIR/listed" ]]; then count="$(cat "$TEST_DIR/listed")"; fi + count=$((count + 1)); echo "$count" > "$TEST_DIR/listed" + if ((count == 2)) && [[ "$TEST_LATE_PROFILE" == true ]]; then + jq 'map(if .type == "Microsoft.Cdn/profiles" then .tags.changed = "true" else . end)' "$TEST_DIR/inventory" + elif ((count <= 2)); then cat "$TEST_DIR/inventory"; else echo '[]'; fi ;; + "resource show --ids") jq --arg id "$4" '.[] | select(.id == $id)' "$TEST_DIR/inventory" ;; + "aks show --subscription") name="$(option --name "$@")"; jq --arg name "$name" '.[] | select(.name == $name)' "$TEST_DIR/inventory" ;; + "aks get-credentials --subscription"|"aks delete --subscription"|"aks wait --subscription"|"resource delete --ids") ;; + "network vnet peering") + if [[ "$4" == list ]]; then + name="$(option --vnet-name "$@")" + jq --arg name "$name" '[.[] | select(.id | contains("/virtualNetworks/" + $name + "/"))]' "$TEST_DIR/peerings" + elif [[ "$4" == delete ]]; then :; else exit 1; fi ;; + "role assignment list") cat "$TEST_DIR/assignments" ;; + "role assignment delete") ;; + *) echo "unexpected az command: $*" >&2; exit 1 ;; + esac + `) + writeAFDCommand(t, filepath.Join(dir, "kubectl"), `#!/bin/bash + set -euo pipefail + printf 'kubectl %s\n' "$*" >> "$TEST_DIR/calls" + case "$*" in + *"get namespace kube-system"*) printf '%s' "$TEST_UID" ;; + *"get deployment"*) echo deployment/hub-net-controller-manager ;; + *"scale"*|*"rollout status"*) ;; + *) exit 1 ;; + esac + `) + t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH")) + output, err := runAFDScript(t, "./cleanup.sh") + if (err != nil) != (tc.invalidOwner || tc.foreignPeer || tc.lateProfile || tc.principalMismatch) { + t.Fatalf("cleanup: %s (%v)", output, err) + } + calls := readAFDFile(t, filepath.Join(dir, "calls")) + if tc.invalidOwner || tc.foreignPeer || tc.lateProfile || tc.principalMismatch { + if strings.Contains(calls, " delete ") || (!tc.lateProfile && strings.Contains(calls, " scale ")) { + t.Fatalf("unsafe mutation after owner mismatch: %s", calls) + } + return + } + wants := []string{"aks delete", "aks wait", "kubectl --context hub-admin -n fleet-system scale", + "role assignment delete --ids " + group + "/providers/Microsoft.Authorization/roleAssignments/aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa", + "role assignment delete --ids " + nodeID + "/providers/Microsoft.Authorization/roleAssignments/bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb", + "role assignment delete --ids " + nodeID + "/providers/Microsoft.Authorization/roleAssignments/cccccccc-cccc-cccc-cccc-cccccccccccc", + "group wait", + "network vnet peering delete --ids " + vnet1, "network vnet peering delete --ids " + vnet2} + if !tc.noProfiles { + wants = append(wants, "resource delete --ids "+profileID, "resource delete --ids "+trafficProfileID) + } + for _, want := range wants { + if !strings.Contains(calls, want) { + t.Errorf("missing %q in calls:\n%s", want, calls) + } + } + if strings.Contains(calls, "roleAssignments/foreign") || strings.Contains(calls, "group delete") { + t.Fatalf("cleanup touched foreign resources: %s", calls) + } + if strings.Index(calls, "roleAssignments/bbbbbbbb") > strings.Index(calls, "aks delete") || + strings.Index(calls, "roleAssignments/aaaaaaaa") < strings.Index(calls, "aks wait") { + t.Fatalf("role deletion must preserve control-plane network access through AKS deletion: %s", calls) + } + }) + } + } + t.Run("controller and peerings", testControllerAndPeerings) + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + afdTestEnvironment(t) + t.Setenv("E2E_SHARED_RESOURCE_GROUP", "true") + t.Setenv("E2E_RUN_ID", "123-atm-1") + t.Setenv("AZURE_SUBSCRIPTION_ID", "test-subscription") + t.Setenv("AZURE_RESOURCE_GROUP", "fleet-networking-e2e") + dir := t.TempDir() + group := "/subscriptions/test-subscription/resourceGroups/fleet-networking-e2e" + hash := sha256.Sum256([]byte("test-subscription/fleet-networking-e2e/123-atm-1")) + prefix := fmt.Sprintf("fne%x", hash[:8]) + registry := prefix + "acr" + tags := map[string]string{"source": "fleet-networking", "fleet-e2e-run": "123-atm-1"} + if tt.conflict { + tags["fleet-e2e-run"] = "another-run" + } + items := []map[string]interface{}{ + {"id": group + "/providers/Microsoft.ContainerRegistry/registries/" + registry, + "name": registry, "type": "Microsoft.ContainerRegistry/registries", "tags": tags}, + {"id": group + "/providers/Microsoft.Network/virtualNetworks/other-run", + "name": "other-run", "type": "Microsoft.Network/virtualNetworks", + "tags": map[string]string{"fleet-e2e-run": "another-run"}}, + } + if tt.profile { + items = append(items, map[string]interface{}{ + "id": group + "/providers/Microsoft.Network/trafficManagerProfiles/fleet-123", + "name": "fleet-123", "type": "Microsoft.Network/trafficManagerProfiles", + "tags": map[string]string{"networking.fleet.azure.com.trafficManagerProfile": prefix + "-abcde/service"}, + }) + } + contents, err := json.Marshal(items) + if err != nil { + t.Fatal(err) + } + inventory := filepath.Join(dir, "inventory.json") + if err := os.WriteFile(inventory, contents, 0o600); err != nil { + t.Fatal(err) + } + t.Setenv("TEST_INVENTORY", inventory) + t.Setenv("TEST_CALLS", filepath.Join(dir, "calls")) + t.Setenv("TEST_LISTED", filepath.Join(dir, "listed")) + writeAFDCommand(t, filepath.Join(dir, "az"), `#!/bin/bash + set -euo pipefail + printf '%s\n' "$*" >> "$TEST_CALLS" + case "$1 $2" in + "group show") printf '%s\n' '{"id":"/subscriptions/test-subscription/resourceGroups/fleet-networking-e2e","tags":{"managedBy":"aks-rp/ci-resources","workload":"fleet-networking-e2e"}}' ;; + "resource list") + if [[ -e "$TEST_LISTED" ]]; then echo '[]'; else touch "$TEST_LISTED"; cat "$TEST_INVENTORY"; fi ;; + "resource show") jq --arg id "$4" '.[] | select(.id == $id)' "$TEST_INVENTORY" ;; + "role assignment") [[ "$3" == list ]] && echo '[]' ;; + "resource delete") ;; + *) echo "unexpected az command: $*" >&2; exit 1 ;; + esac + `) + t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH")) + output, err := runAFDScript(t, "./cleanup.sh") + if (err == nil) != tt.wantDeletes { + t.Fatalf("cleanup: %s (%v)", output, err) + } + calls := readAFDFile(t, filepath.Join(dir, "calls")) + if strings.Contains(calls, "group delete") || strings.Contains(calls, "other-run") { + t.Fatalf("cleanup touched foreign resources: %s", calls) + } + if strings.Contains(calls, "resource delete") != tt.wantDeletes { + t.Fatalf("unexpected resource deletion: %s", calls) + } + }) + } +} + +func TestLegacyTopologyKeepsClusterNames(t *testing.T) { + afdTestEnvironment(t) + t.Setenv("RESOURCE_GROUP", "test-rg") + t.Setenv("NODE_COUNT", "2") + t.Setenv("MEMBER_1_LOCATION", "eastus2") + t.Setenv("MEMBER_2_LOCATION", "eastus2") + dir := t.TempDir() + t.Setenv("TEST_CALLS", filepath.Join(dir, "calls")) + writeAFDCommand(t, filepath.Join(dir, "az"), "#!/bin/bash\nprintf '%s\\n' \"$*\" >> \"$TEST_CALLS\"\n") + t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH")) + output, err := runAFDScript(t, "./aks-shared-vnet.sh") + if err != nil { + t.Fatalf("legacy topology: %s (%v)", output, err) + } + calls := readAFDFile(t, filepath.Join(dir, "calls")) + for _, name := range []string{"--name fleet", "--name member-1", "--name member-2"} { + if !strings.Contains(calls, name) { + t.Errorf("missing legacy name %s in %s", name, calls) + } + } + if strings.Contains(calls, "fleet-e2e-run=") { + t.Fatalf("legacy topology unexpectedly used shared resource tags: %s", calls) + } +} From 1545e796e2afb11e05919d1972e737154b454ec7 Mon Sep 17 00:00:00 2001 From: Wei Weng Date: Tue, 24 Nov 2026 19:11:42 +0000 Subject: [PATCH 02/16] docs: record shared E2E branch delivery Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../breadcrumbs/2026-11-24-1842-shared-e2e-resource-group.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/.copilot/breadcrumbs/2026-11-24-1842-shared-e2e-resource-group.md b/.github/.copilot/breadcrumbs/2026-11-24-1842-shared-e2e-resource-group.md index 352e777e..d93a3a0f 100644 --- a/.github/.copilot/breadcrumbs/2026-11-24-1842-shared-e2e-resource-group.md +++ b/.github/.copilot/breadcrumbs/2026-11-24-1842-shared-e2e-resource-group.md @@ -13,7 +13,7 @@ 2. [x] Add offline tests for concurrent run isolation, configuration and fail-closed cleanup. 3. [x] Implement opt-in shared-group setup, naming, permissions and safe per-run cleanup; preserve existing behavior. 4. [x] Update documentation and validate targeted tests and shell checks. -5. [ ] Push branch and report unverified live behavior and remaining risks. +5. [x] Push branch and report unverified live behavior and remaining risks. ## Before From ce5a6413ae13496a8643ee92edb8c5390e3ad4c1 Mon Sep 17 00:00:00 2001 From: Wei Weng Date: Tue, 24 Nov 2026 19:25:12 +0000 Subject: [PATCH 03/16] ci: use shared resource group for all E2E runs Remove disposable resource group setup and the shared-mode flag, update both workflows, preserve the performance topology, and resolve the AFD caller identity without a separate parameter. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- ...26-11-24-1842-shared-e2e-resource-group.md | 18 ++- .github/workflows/e2e-tests.yml | 42 +++---- .pipeline/e2e-tests.yaml | 51 ++------- test/README.md | 40 ++++--- test/e2e/framework/consts.go | 3 - test/e2e/framework/workload_manager.go | 17 ++- test/e2e/framework/workload_manager_test.go | 29 +++-- test/e2e/traffic_manager_test.go | 12 +- test/perftest/README.md | 8 +- test/scripts/afd_commands_test.go | 6 +- test/scripts/afd_test.go | 76 ++++++++++--- test/scripts/aks-dynamic-ip-allocation.sh | 2 +- test/scripts/aks-peered-vnet.sh | 4 +- test/scripts/aks-shared-vnet.sh | 2 +- test/scripts/azure-principal-id.sh | 31 ++++++ test/scripts/azure_principal_id_test.go | 49 +++++++++ test/scripts/bootstrap.sh | 98 ++++++----------- test/scripts/cleanup-shared-group.sh | 9 +- test/scripts/cleanup.sh | 12 +- test/scripts/e2e-config.sh | 104 +++++++----------- test/scripts/install-afd.sh | 2 +- test/scripts/perf-test.sh | 25 +++-- test/scripts/shared_group_test.go | 60 +++++----- 23 files changed, 372 insertions(+), 328 deletions(-) create mode 100644 test/scripts/azure-principal-id.sh create mode 100644 test/scripts/azure_principal_id_test.go diff --git a/.github/.copilot/breadcrumbs/2026-11-24-1842-shared-e2e-resource-group.md b/.github/.copilot/breadcrumbs/2026-11-24-1842-shared-e2e-resource-group.md index d93a3a0f..443c3c92 100644 --- a/.github/.copilot/breadcrumbs/2026-11-24-1842-shared-e2e-resource-group.md +++ b/.github/.copilot/breadcrumbs/2026-11-24-1842-shared-e2e-resource-group.md @@ -2,7 +2,7 @@ ## Requirements and decisions -- User approved an opt-in shared resource group mode with unique run identities, safe cleanup, offline tests and documentation; existing disposable-group behavior remains the default. +- User originally approved opt-in shared resource group mode, then requested shared-group-only execution with no mode flag. - Push a new branch based on main. Do not run live Azure E2E or cleanup without separate approval. - Shared group `fleet-networking-e2e` was created in the test subscription, westus2. Proposed grants and WIF service connection are not yet deployed. - Prior work: [retry PR #459](https://github.com/Azure/fleet-networking/pull/459). @@ -29,18 +29,26 @@ Each Azure DevOps scenario creates and deletes a unique resource group. Fixed re ## Status -Shared-group mode is opt-in. The Azure DevOps pipeline supplies a unique run ID per scenario and attempt; scripts derive physical Azure names and retain the established logical Kubernetes contexts. Setup requires a new run-specific kubeconfig, verifies the group and rejects name or ownership collisions before enabling cleanup. +The shared-group-only revision: + +1. [x] Remove the legacy resource-group creation/deletion path and require per-run shared-group configuration. +2. [x] Update Azure DevOps and GitHub workflow callers and preserve safe cleanup eligibility. +3. [x] Keep performance topology working with run-specific resources and ownership-verified cleanup. +4. [x] Update tests and documentation and validate offline. +5. [ ] Push the shared-group-only revision. + +The Azure DevOps pipeline supplies a unique run ID per scenario and attempt; scripts derive physical Azure names and retain the established logical Kubernetes contexts. Setup requires a new run-specific kubeconfig, verifies the group and rejects name or ownership collisions before enabling cleanup. Cleanup verifies the group, run tags, resource IDs, AKS node-group ownership, role scopes and peering targets. It verifies Traffic Manager namespace tags and Front Door hub/Gateway identity, stops the run's hub controllers before deleting their profiles, deletes only identified roles and resources, and never deletes the shared group. It fails explicitly when ownership, controller quiescence or deletion cannot be verified. -Shared AFD requires the test principal object ID, grants it Network Contributor only on verified member node groups, and records the principal for cleanup. The pipeline service connection remains unchanged by default and can be selected explicitly after its grants are deployed. +Shared AFD requires the test principal object ID, grants it Network Contributor only on verified member node groups, and records the principal for cleanup. CI obtains the object ID from its Azure CLI access token without logging or storing the token. The pipeline service connection remains unchanged by default and can be selected explicitly after its grants are deployed. Changed files: `.pipeline/e2e-tests.yaml`, `test/README.md`, the `test/scripts` setup, topology, configuration, AFD and cleanup scripts and tests, plus E2E framework workload naming and Traffic Manager public-IP tagging. ## Validation and risks -- `GOTOOLCHAIN=go1.26.10 go test -count=1 ./test/scripts ./test/e2e/framework` passed, including mocked concurrent-run, collision, profile, peering, role, cleanup and legacy cases. +- `GOTOOLCHAIN=go1.26.10 go test -count=1 ./test/scripts ./test/e2e/framework` passed, including mocked concurrent-run, collision, profile, peering, role, cleanup, token parsing and performance topology cases. - `GOTOOLCHAIN=go1.26.10 go vet ./test/scripts ./test/e2e/framework` passed. - `GOTOOLCHAIN=go1.26.10 go test -tags=e2e -run '^$' ./test/e2e` and `go vet -tags=e2e ./test/e2e` passed without executing live E2E. -- Installed Azure CLI AFD option checks, Bash syntax, pipeline YAML parsing and `git diff --check` passed. +- Performance packages compiled and passed `go vet` without running their suites. Installed Azure CLI option checks, Bash syntax, both workflow YAML parsing and `git diff --check` passed. - No live Azure provisioning, permission, test or cleanup operation was run. The proposed grants and service connection have not been enabled. Cleanup can fail closed and leave resources; there is no stale-run sweeper. Contributor on the shared RG is not a security boundary between runs. diff --git a/.github/workflows/e2e-tests.yml b/.github/workflows/e2e-tests.yml index 0d5f102a..31a6c1bf 100644 --- a/.github/workflows/e2e-tests.yml +++ b/.github/workflows/e2e-tests.yml @@ -31,24 +31,34 @@ jobs: fail-fast: false matrix: include: - - network-setting: shared-vnet + - scenario: atm + network-setting: shared-vnet enable-traffic-manager: true enable-afd: false - - network-setting: peered-vnet + - scenario: peered + network-setting: peered-vnet enable-traffic-manager: false enable-afd: false - - network-setting: dynamic-ip-allocation + - scenario: dynamic + network-setting: dynamic-ip-allocation enable-traffic-manager: false enable-afd: false - - network-setting: unsupported + - scenario: unsupported + network-setting: unsupported enable-traffic-manager: false enable-afd: false - - network-setting: shared-vnet + - scenario: afd + network-setting: shared-vnet enable-traffic-manager: false enable-afd: true env: ENABLE_AZURE_FRONT_DOOR: ${{ matrix.enable-afd }} ENABLE_AFD_PRIVATE_LINK_AUTO_APPROVAL: ${{ matrix.enable-afd }} + ENABLE_TRAFFIC_MANAGER: ${{ matrix.enable-traffic-manager }} + AZURE_NETWORK_SETTING: ${{ matrix.network-setting }} + AZURE_SUBSCRIPTION_ID: ${{ secrets.E2E_AZURE_SUBSCRIPTION_ID }} + AZURE_RESOURCE_GROUP: fleet-networking-e2e + E2E_RUN_ID: gh-${{ github.run_id }}-${{ github.run_attempt }}-${{ matrix.scenario }} RETAIN_AFD_E2E_SETUP: "false" runs-on: ubuntu-latest needs: [ @@ -65,8 +75,7 @@ jobs: uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Prepare e2e variables - run: | - echo "AZURE_RESOURCE_GROUP=fleet-networking-e2e-$RANDOM" >> "$GITHUB_ENV" + run: echo "KUBECONFIG=$RUNNER_TEMP/fleet-e2e-kubeconfig" >> "$GITHUB_ENV" # Reference: https://docs.github.com/en/actions/deployment/security-hardening-your-deployments/configuring-openid-connect-in-azure - name: 'OIDC Login to Azure Public Cloud' @@ -99,23 +108,19 @@ jobs: done & - name: Setup e2e Environment + id: setup run: | + if [[ "$ENABLE_AZURE_FRONT_DOOR" == true && "$ENABLE_AFD_PRIVATE_LINK_AUTO_APPROVAL" == true ]]; then + E2E_TEST_PRINCIPAL_ID="$(bash test/scripts/azure-principal-id.sh)" + export E2E_TEST_PRINCIPAL_ID + echo "E2E_TEST_PRINCIPAL_ID=$E2E_TEST_PRINCIPAL_ID" >> "$GITHUB_ENV" + fi make e2e-setup - env: - AZURE_SUBSCRIPTION_ID: ${{ secrets.E2E_AZURE_SUBSCRIPTION_ID }} - AZURE_NETWORK_SETTING: ${{ matrix.network-setting }} - AZURE_RESOURCE_GROUP: ${{ env.AZURE_RESOURCE_GROUP }} - ENABLE_TRAFFIC_MANAGER: ${{ matrix.enable-traffic-manager }} - name: Wait for role assignments to be effective run: sleep 5m - name: Run e2e tests run: | make e2e-tests - env: - AZURE_SUBSCRIPTION_ID: ${{ secrets.E2E_AZURE_SUBSCRIPTION_ID }} - AZURE_NETWORK_SETTING: ${{ matrix.network-setting }} - AZURE_RESOURCE_GROUP: ${{ env.AZURE_RESOURCE_GROUP }} - ENABLE_TRAFFIC_MANAGER: ${{ matrix.enable-traffic-manager }} - name: Collect agent logs if: always() run: | @@ -131,11 +136,10 @@ jobs: if-no-files-found: warn retention-days: 3 - name: Cleanup e2e - if: always() + if: always() && steps.setup.outputs.resources_started == 'true' run: | make e2e-cleanup env: AZURE_CLIENT_ID: ${{ secrets.E2E_AZURE_CLIENT_ID}} AZURE_CLIENT_SECRET: ${{ secrets.E2E_AZURE_CLIENT_SECRET }} AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }} - AZURE_RESOURCE_GROUP: ${{ env.AZURE_RESOURCE_GROUP }} diff --git a/.pipeline/e2e-tests.yaml b/.pipeline/e2e-tests.yaml index 596482aa..f7943d92 100644 --- a/.pipeline/e2e-tests.yaml +++ b/.pipeline/e2e-tests.yaml @@ -8,15 +8,9 @@ trigger: pr: none parameters: - - name: sharedResourceGroup - type: boolean - default: false - name: serviceConnection type: string default: 'aks fleetnetworking' - - name: testPrincipalId - type: string - default: 'none' - name: scenarios type: object default: @@ -70,13 +64,8 @@ jobs: AZURE_NETWORK_SETTING: ${{ scenario.value.AZURE_NETWORK_SETTING }} ENABLE_TRAFFIC_MANAGER: ${{ lower(scenario.value.ENABLE_TRAFFIC_MANAGER) }} ENABLE_AZURE_FRONT_DOOR: ${{ lower(scenario.value.ENABLE_AZURE_FRONT_DOOR) }} - ${{ if eq(parameters.sharedResourceGroup, true) }}: - AZURE_RESOURCE_GROUP: 'fleet-networking-e2e' - ${{ else }}: - AZURE_RESOURCE_GROUP: 'fleet-ado-$(Build.BuildId)-$(SCENARIO)-$(System.JobAttempt)' - E2E_SHARED_RESOURCE_GROUP: ${{ lower(parameters.sharedResourceGroup) }} + AZURE_RESOURCE_GROUP: 'fleet-networking-e2e' E2E_RUN_ID: '$(Build.BuildId)-$(SCENARIO)-$(System.JobAttempt)' - E2E_TEST_PRINCIPAL_ID: ${{ parameters.testPrincipalId }} ENABLE_AFD_PRIVATE_LINK_AUTO_APPROVAL: '$(ENABLE_AZURE_FRONT_DOOR)' RETAIN_AFD_E2E_SETUP: 'false' BUILDX_BUILDER_NAME: 'fleet-e2e-$(Build.BuildId)-$(SCENARIO)-$(System.JobAttempt)' @@ -110,7 +99,7 @@ jobs: - bash: | set -euo pipefail : "${AZURE_SUBSCRIPTION_ID:?Set AZURE_SUBSCRIPTION_ID as a non-secret ADO pipeline variable}" - for tool in az docker helm kubectl jq yq make timeout sha256sum; do + for tool in az docker helm kubectl jq yq make timeout sha256sum python3; do command -v "$tool" done go version @@ -144,15 +133,14 @@ jobs: exit 1 fi exists=$(az group exists --subscription "$AZURE_SUBSCRIPTION_ID" -n "$AZURE_RESOURCE_GROUP") - if [[ "$E2E_SHARED_RESOURCE_GROUP" == true && "$exists" != true ]]; then + if [[ "$exists" != true ]]; then echo "error: shared resource group $AZURE_RESOURCE_GROUP does not exist" >&2 exit 1 - elif [[ "$E2E_SHARED_RESOURCE_GROUP" != true && "$exists" != false ]]; then - echo "error: refusing to reuse resource group $AZURE_RESOURCE_GROUP" >&2 - exit 1 fi - if [[ "$E2E_SHARED_RESOURCE_GROUP" != true ]]; then - echo "##vso[task.setvariable variable=e2eResourcesStarted]true" + if [[ "$ENABLE_AZURE_FRONT_DOOR" == true && "$ENABLE_AFD_PRIVATE_LINK_AUTO_APPROVAL" == true ]]; then + E2E_TEST_PRINCIPAL_ID="$(bash test/scripts/azure-principal-id.sh)" + export E2E_TEST_PRINCIPAL_ID + echo "##vso[task.setvariable variable=E2E_TEST_PRINCIPAL_ID]$E2E_TEST_PRINCIPAL_ID" fi make e2e-setup @@ -205,9 +193,9 @@ jobs: artifact: 'e2e-$(SCENARIO)-$(System.JobAttempt)' - task: AzureCLI@2 - displayName: Clean up this run's resource group + displayName: Clean up this run's resources condition: and(always(), eq(variables['e2eResourcesStarted'], 'true')) - timeoutInMinutes: ${{ iif(parameters.sharedResourceGroup, 90, 20) }} + timeoutInMinutes: 90 inputs: azureSubscription: ${{ parameters.serviceConnection }} scriptType: bash @@ -217,25 +205,4 @@ jobs: keepAzSessionActive: true inlineScript: | set -euo pipefail - if [[ "$E2E_SHARED_RESOURCE_GROUP" == true ]]; then - make e2e-cleanup - exit 0 - fi - expected="fleet-ado-$BUILD_BUILDID-$SCENARIO-$SYSTEM_JOBATTEMPT" - if [[ "$AZURE_RESOURCE_GROUP" != "$expected" ]]; then - echo "error: refusing cleanup outside this run's resource group" >&2 - exit 1 - fi - az account set --subscription "$AZURE_SUBSCRIPTION_ID" - exists=$(az group exists --subscription "$AZURE_SUBSCRIPTION_ID" -n "$expected") - if [[ "$exists" == false ]]; then - echo "Resource group $expected is already absent." - exit 0 - fi - group=$(az group show --subscription "$AZURE_SUBSCRIPTION_ID" -n "$expected" -o json) - jq -e --arg id "/subscriptions/$AZURE_SUBSCRIPTION_ID/resourceGroups/$expected" \ - '(.id | ascii_downcase) == ($id | ascii_downcase) and .tags.source == "fleet-networking"' \ - <<<"$group" > /dev/null make e2e-cleanup - az group wait --subscription "$AZURE_SUBSCRIPTION_ID" -n "$expected" \ - --deleted --interval 15 --timeout 900 diff --git a/test/README.md b/test/README.md index 71f74ff7..b1953bee 100644 --- a/test/README.md +++ b/test/README.md @@ -12,6 +12,7 @@ networking components, and runs the Ginkgo tests under `test/e2e`. - [kubectl](https://kubernetes.io/docs/tasks/tools/) - [`jq`](https://jqlang.github.io/jq/download/) - [`yq`](https://github.com/mikefarah/yq#install) +- Python 3 and `sha256sum` - Bash and GNU Make - An Azure subscription in which the signed-in identity can provision the test resources and create the required role assignments @@ -27,35 +28,35 @@ az account set --subscription "${AZURE_SUBSCRIPTION_ID}" The setup builds and pushes test images, creates an Azure Container Registry and AKS clusters, and assigns Azure roles. Use a test subscription rather than a production subscription. -### Opt-in shared resource group +### Shared resource group -The Azure DevOps E2E pipeline can use the pre-created `fleet-networking-e2e` resource group by -setting the `sharedResourceGroup` pipeline parameter to `true`. The default remains a disposable -resource group per job. Before opting in, an administrator must deploy the scoped permissions -and authorize the intended service connection; choose it with the `serviceConnection` parameter. -For automated AFD Private Link approval, `testPrincipalId` must be that connection's service -principal **object ID**. +The E2E workflows use the pre-created `fleet-networking-e2e` resource group. An administrator +must deploy the scoped permissions and authorize the intended service connection; Azure DevOps +can select it with the `serviceConnection` parameter. CI obtains the service principal object ID +from its Azure CLI access token for automated AFD Private Link approval. For a local run, set the following in addition to the scenario variables: ```bash export AZURE_RESOURCE_GROUP=fleet-networking-e2e -export E2E_SHARED_RESOURCE_GROUP=true export E2E_RUN_ID= export KUBECONFIG= # Required only when AFD automatic approval is enabled: export E2E_TEST_PRINCIPAL_ID= ``` +For local AFD auto-approval, sign in as that service principal. An interactive user can instead +disable auto-approval and arrange manual approval by an authorized PLS owner. + Use a unique `E2E_RUN_ID` for every concurrent run and retry; never reuse an ID while a prior run -or its cleanup is active. The pipeline derives it from the build ID, scenario and job attempt. +or its cleanup is active. Use at most 63 lowercase letters, digits and hyphens, beginning with a +letter or digit. CI derives it from the build ID, scenario and job attempt. Setup checks the shared group's expected management tags and refuses existing run resources. Physical Azure cluster names, VNets, identities and the registry are run-specific, while the isolated kubeconfig retains the `hub-admin` and `member-*-admin` context names. -Shared-group mode does not support the separate `perf-test` topology. AFD shared mode requires -the default Gateway controller namespace and deployment name. +AFD requires the default Gateway controller namespace and deployment name. -`make e2e-cleanup` in shared mode **never deletes the resource group**. It verifies run tags, +`make e2e-cleanup` **never deletes the resource group**. It verifies run tags, resource IDs, controller profile ownership and AKS-managed node groups before removing the run's resources and relevant role assignments. If ownership cannot be established, the hub is unavailable when controller cleanup is needed, or Azure cleanup fails, the command stops with an @@ -516,8 +517,8 @@ The existing post-setup CI propagation window applies to these assignments. The setup operator needs role-assignment write/read permission on those scopes. The installer does not approve connections. **Approval remains asynchronous.** The standard AFD opt-in defaults its test-only exact-request approval helper on; -the runner must already have approval permission on the verified fixture PLS -resources. Set `ENABLE_AFD_PRIVATE_LINK_AUTO_APPROVAL=false` for an authorized +setup grants the test caller Network Contributor on the verified member node +resource groups. Set `ENABLE_AFD_PRIVATE_LINK_AUTO_APPROVAL=false` for an authorized PLS owner to perform manual approval at the correlated checkpoint below. Production controller approval integration with the AFD/PLS teams remains an action item. @@ -634,6 +635,7 @@ export ENABLE_AFD_PRIVATE_HTTP_PROOF=true export AFD_PROOF_CONTROLLER_NAMESPACE= export AFD_PROOF_CONTROLLER_DEPLOYMENT= export AFD_PROOF_CONTROLLER_IMAGE= +source test/scripts/e2e-config.sh AFD_PROOF_REPORT="${TMPDIR:-/tmp}/afd-private-http-proof-$(date -u +%Y%m%dT%H%M%SZ).json" go test -v -count=1 -tags=e2e -run '^TestE2E$' -timeout=10h ./test/e2e \ -args -ginkgo.v -ginkgo.timeout=9h30m -ginkgo.label-filter=afd-private-http-proof \ @@ -738,8 +740,8 @@ Azure drift/deletion recovery, backend/member/weight changes and Kubernetes plus Azure resource absence during cleanup. The [E2E workflow](../.github/workflows/e2e-tests.yml) enables ATM for the shared-VNet -matrix entry, uses the existing setup/test targets, and collects logs/cleans up -with `if: always()`. These are implemented test/CI paths, not evidence that a +matrix entry, uses the existing setup/test targets, and collects logs even after a failure. +Cleanup runs after ownership preflight has succeeded. These are implemented test/CI paths, not evidence that a particular live run passed. The reviewed ATM scenario has no application HTTP request, observed health-probe @@ -786,6 +788,7 @@ The environment can be reused for repeated test runs. To run only the current Ga scenario: ```bash +source test/scripts/e2e-config.sh go test -timeout 50m -tags=e2e -v ./test/e2e \ -args -ginkgo.v -ginkgo.focus='Gateway API contract' ``` @@ -801,10 +804,11 @@ make e2e-collect-logs ## Clean up -Delete the Azure resource group created for the E2E environment: +Delete only this run's verified resources; the shared resource group remains: ```bash make e2e-cleanup ``` -Cleanup requires `AZURE_RESOURCE_GROUP` to still identify the test resource group. +Cleanup requires the same `AZURE_RESOURCE_GROUP`, `E2E_RUN_ID`, `KUBECONFIG` and, for AFD +auto-approval, `E2E_TEST_PRINCIPAL_ID` used by setup. diff --git a/test/e2e/framework/consts.go b/test/e2e/framework/consts.go index 64ab0d52..11fa69eb 100644 --- a/test/e2e/framework/consts.go +++ b/test/e2e/framework/consts.go @@ -23,9 +23,6 @@ const ( // MCSLBPollTimeout defines the time to wait a MCS to be assigned with LoadBalancer IP address. // As MCS depending on handling service related to cloud provider, more time is required. MCSLBPollTimeout = 10 * time.Minute - - // TestNamespacePrefix defines the prefix of test namespaces. - TestNamespacePrefix = "my-ns" ) var ( diff --git a/test/e2e/framework/workload_manager.go b/test/e2e/framework/workload_manager.go index fba6392b..85fef6e9 100644 --- a/test/e2e/framework/workload_manager.go +++ b/test/e2e/framework/workload_manager.go @@ -9,7 +9,6 @@ import ( "context" "fmt" "os" - "strings" "time" "github.com/google/go-cmp/cmp" @@ -430,18 +429,18 @@ func defaultBackOff() wait.Backoff { // TODO(mainred): Before the app image is publicly available, we use the one built from e2e bootstrap. // The app image construction must be aligned with the steps in test/scripts/bootstrap.sh. func appImage() string { - if registry := os.Getenv("REGISTRY"); registry != "" { - return fmt.Sprintf("%s/app", registry) + registry := os.Getenv("REGISTRY") + if registry == "" { + panic("REGISTRY is required for E2E workload images") } - resourceGroupName := os.Getenv("AZURE_RESOURCE_GROUP") - registryName := strings.ReplaceAll(resourceGroupName, "-", "") - return fmt.Sprintf("%s.azurecr.io/app", registryName) + return fmt.Sprintf("%s/app", registry) } // UniqueTestNamespace gives a unique namespace name. func UniqueTestNamespace() string { - if prefix := os.Getenv("E2E_RESOURCE_PREFIX"); os.Getenv("E2E_SHARED_RESOURCE_GROUP") == "true" && prefix != "" { - return fmt.Sprintf("%s-%s", prefix, uniquename.RandomLowerCaseAlphabeticString(5)) + prefix := os.Getenv("E2E_RESOURCE_PREFIX") + if prefix == "" { + panic("E2E_RESOURCE_PREFIX is required for E2E namespaces") } - return fmt.Sprintf("%s-%s", TestNamespacePrefix, uniquename.RandomLowerCaseAlphabeticString(5)) + return fmt.Sprintf("%s-%s", prefix, uniquename.RandomLowerCaseAlphabeticString(5)) } diff --git a/test/e2e/framework/workload_manager_test.go b/test/e2e/framework/workload_manager_test.go index 5bbd892b..ed3497d2 100644 --- a/test/e2e/framework/workload_manager_test.go +++ b/test/e2e/framework/workload_manager_test.go @@ -15,7 +15,6 @@ import ( ) func TestSharedRunWorkloadNames(t *testing.T) { - t.Setenv("E2E_SHARED_RESOURCE_GROUP", "true") t.Setenv("E2E_RESOURCE_PREFIX", "fne0123456789abcdef") t.Setenv("REGISTRY", "fne0123456789abcdefacr.azurecr.io") if got := appImage(); got != "fne0123456789abcdefacr.azurecr.io/app" { @@ -34,13 +33,25 @@ func TestSharedRunWorkloadNames(t *testing.T) { t.Fatalf("shared run DNS label %q is invalid: %v", label, problems) } - t.Setenv("E2E_SHARED_RESOURCE_GROUP", "false") - t.Setenv("REGISTRY", "") - t.Setenv("AZURE_RESOURCE_GROUP", "fleet-legacy-123") - if got := appImage(); got != "fleetlegacy123.azurecr.io/app" { - t.Fatalf("legacy registry naming changed: %s", got) - } - if got := UniqueTestNamespace(); !strings.HasPrefix(got, "my-ns-") { - t.Fatalf("legacy namespace naming changed: %s", got) +} + +func TestMissingSharedRunConfiguration(t *testing.T) { + for _, tt := range []struct { + name string + key string + call func() + }{ + {"registry", "REGISTRY", func() { appImage() }}, + {"run prefix", "E2E_RESOURCE_PREFIX", func() { UniqueTestNamespace() }}, + } { + t.Run(tt.name, func(t *testing.T) { + t.Setenv(tt.key, "") + defer func() { + if recover() == nil { + t.Fatal("missing run configuration must fail explicitly") + } + }() + tt.call() + }) } } diff --git a/test/e2e/traffic_manager_test.go b/test/e2e/traffic_manager_test.go index 8ca7a0b4..fc2d861b 100644 --- a/test/e2e/traffic_manager_test.go +++ b/test/e2e/traffic_manager_test.go @@ -618,10 +618,7 @@ var _ = Describe("Test exporting service via Azure traffic manager", Ordered, fu It("Creating extra Azure traffic manager endpoint directly and then updating trafficManagerBackend", func() { By("Creating a public IP address") - publicIPAddressName := fmt.Sprintf("e2e-test-public-ip-%s", uniquename.RandomLowerCaseAlphabeticString(5)) - if os.Getenv("E2E_SHARED_RESOURCE_GROUP") == "true" { - publicIPAddressName = fmt.Sprintf("%s-ip-%s", os.Getenv("E2E_RESOURCE_PREFIX"), uniquename.RandomLowerCaseAlphabeticString(5)) - } + publicIPAddressName := fmt.Sprintf("%s-ip-%s", os.Getenv("E2E_RESOURCE_PREFIX"), uniquename.RandomLowerCaseAlphabeticString(5)) publicIPReq := armnetwork.PublicIPAddress{ Name: ptr.To(publicIPAddressName), Location: ptr.To(clusterLocation), @@ -635,10 +632,9 @@ var _ = Describe("Test exporting service via Azure traffic manager", Ordered, fu Name: ptr.To(armnetwork.PublicIPAddressSKUNameStandard), }, } - if runID := os.Getenv("E2E_RUN_ID"); os.Getenv("E2E_SHARED_RESOURCE_GROUP") == "true" { - Expect(runID).ShouldNot(BeEmpty()) - publicIPReq.Tags = map[string]*string{"source": ptr.To("fleet-networking"), "fleet-e2e-run": ptr.To(runID)} - } + runID := os.Getenv("E2E_RUN_ID") + Expect(runID).ShouldNot(BeEmpty()) + publicIPReq.Tags = map[string]*string{"source": ptr.To("fleet-networking"), "fleet-e2e-run": ptr.To(runID)} publicIPResp, err := pipClient.CreateOrUpdate(ctx, atmValidator.ResourceGroup, publicIPAddressName, publicIPReq) Expect(err).Should(Succeed(), "Failed to create public IP address") diff --git a/test/perftest/README.md b/test/perftest/README.md index 15ccfabf..dae6bd64 100644 --- a/test/perftest/README.md +++ b/test/perftest/README.md @@ -9,9 +9,12 @@ To run this test: ```sh # Replace YOUR-SUBSCRIPTION-ID with a value of your own. export AZURE_SUBSCRIPTION_ID=YOUR-SUBSCRIPTION-ID + export AZURE_RESOURCE_GROUP=fleet-networking-e2e + export E2E_RUN_ID= + export KUBECONFIG= export AZURE_NETWORK_SETTING=perf-test - . ./test/scripts/bootstrap.sh + make e2e-setup ``` It should take approximately 40 minutes to complete the setup. @@ -32,6 +35,9 @@ To run this test: It is strongly recommended that **each test suite runs in its own environment**. +After testing, run `make e2e-cleanup` with the same variables to remove only that run's +resources. The shared resource group is retained. + After finishing the suite, find the results, e.g., service export latencies and `endpointSlice` export/import latencies in the output and/or the log file. To collect other metrics for further analysis: diff --git a/test/scripts/afd_commands_test.go b/test/scripts/afd_commands_test.go index b58699f3..5c39dba9 100644 --- a/test/scripts/afd_commands_test.go +++ b/test/scripts/afd_commands_test.go @@ -206,7 +206,7 @@ func TestAFDRenderedInstallation(t *testing.T) { t.Fatal("Gateway chart must consume the prepared Secret rather than generate different configuration") } container := deployment.Spec.Template.Spec.Containers[0] - if container.Image != "testrg.azurecr.io/hub-gateway-controller-manager:candidate" || + if container.Image != afdRegistry()+"/hub-gateway-controller-manager:candidate" || deployment.Spec.Template.Spec.ServiceAccountName != "hub-gateway-controller-manager" || !slices.Contains(container.Args, "--enable-afd=true") || !slices.Contains(container.Args, "--afd-resource-group=test-rg") { @@ -354,13 +354,13 @@ func decodeAFDRender(t *testing.T, contents string) (appsv1.Deployment, map[stri func assertAFDCloudConfig(t *testing.T, got map[string]interface{}, cluster string) { t.Helper() - group := "MC_" + cluster + group := "MC_" + afdCluster(cluster) if cluster == "hub" { group = "test-rg" } want := map[string]interface{}{ "cloud": "AzurePublicCloud", "subscriptionId": "test-subscription", "tenantId": "test-tenant", - "useManagedIdentityExtension": true, "userAssignedIdentityID": cluster + "-client", + "useManagedIdentityExtension": true, "userAssignedIdentityID": afdCluster(cluster) + "-client", "resourceGroup": group, "location": "test-location", } for name, value := range want { diff --git a/test/scripts/afd_test.go b/test/scripts/afd_test.go index 427f69f5..2ab28f6c 100644 --- a/test/scripts/afd_test.go +++ b/test/scripts/afd_test.go @@ -7,6 +7,8 @@ package scripts import ( "context" + "crypto/sha256" + "fmt" "os" "os/exec" "path/filepath" @@ -25,14 +27,18 @@ func TestAFDSharedVNetWorkflow(t *testing.T) { Strategy struct { Matrix struct { Include []struct { - Network string `json:"network-setting"` - ATM bool `json:"enable-traffic-manager"` - AFD bool `json:"enable-afd"` + Scenario string `json:"scenario"` + Network string `json:"network-setting"` + ATM bool `json:"enable-traffic-manager"` + AFD bool `json:"enable-afd"` } } } Steps []struct { Name string + ID string + If string + Run string Env map[string]string With map[string]string } @@ -45,11 +51,18 @@ func TestAFDSharedVNetWorkflow(t *testing.T) { job := workflow.Jobs["e2e-tests"] if job.Env["ENABLE_AZURE_FRONT_DOOR"] != "${{ matrix.enable-afd }}" || job.Env["ENABLE_AFD_PRIVATE_LINK_AUTO_APPROVAL"] != "${{ matrix.enable-afd }}" || - job.Env["RETAIN_AFD_E2E_SETUP"] != "false" { + job.Env["RETAIN_AFD_E2E_SETUP"] != "false" || + job.Env["AZURE_RESOURCE_GROUP"] != "fleet-networking-e2e" || + job.Env["E2E_RUN_ID"] != "gh-${{ github.run_id }}-${{ github.run_attempt }}-${{ matrix.scenario }}" { t.Fatal("AFD selection, exact test approvals and ordinary cleanup must reach the entire job") } scenarios := make(map[string]bool) + ids := make(map[string]bool) for _, row := range job.Strategy.Matrix.Include { + if row.Scenario == "" || ids[row.Scenario] { + t.Fatalf("scenario ID must be unique and nonempty: %q", row.Scenario) + } + ids[row.Scenario] = true scenario := row.Network switch { case row.AFD: @@ -73,6 +86,7 @@ func TestAFDSharedVNetWorkflow(t *testing.T) { t.Errorf("missing CI scenario %s", scenario) } } + foundSetup, foundCleanup, foundKubeconfig := false, false, false for _, step := range job.Steps { for _, variable := range []string{"ENABLE_AZURE_FRONT_DOOR", "ENABLE_AFD_PRIVATE_LINK_AUTO_APPROVAL", "RETAIN_AFD_E2E_SETUP"} { if value, ok := step.Env[variable]; ok && value != job.Env[variable] { @@ -80,6 +94,21 @@ func TestAFDSharedVNetWorkflow(t *testing.T) { } } switch step.Name { + case "Prepare e2e variables": + foundKubeconfig = true + if !strings.Contains(step.Run, "KUBECONFIG=$RUNNER_TEMP/fleet-e2e-kubeconfig") { + t.Error("each job must prepare its own kubeconfig") + } + case "Setup e2e Environment": + foundSetup = true + if step.ID != "setup" || !strings.Contains(step.Run, "azure-principal-id.sh") { + t.Error("setup output must be addressable by cleanup") + } + case "Cleanup e2e": + foundCleanup = true + if step.If != "always() && steps.setup.outputs.resources_started == 'true'" { + t.Error("cleanup must require successful ownership preflight") + } case "Collect agent logs": if !strings.Contains(step.Env["LOG_DIR"], "${{ matrix.enable-afd }}") { t.Error("collected logs must distinguish the two shared-VNet fixtures") @@ -92,6 +121,9 @@ func TestAFDSharedVNetWorkflow(t *testing.T) { } } } + if !foundSetup || !foundCleanup || !foundKubeconfig { + t.Fatal("shared E2E workflow is missing setup, cleanup or kubeconfig preparation") + } } func TestAFDConfiguration(t *testing.T) { @@ -159,7 +191,7 @@ func TestAFDStandardTestCommand(t *testing.T) { } if enabled == "true" { for _, want := range []string{ - "testrg.azurecr.io/hub-gateway-controller-manager:candidate", + afdRegistry() + "/hub-gateway-controller-manager:candidate", "-count=1", "10h", "-ginkgo.timeout=9h30m", } { if !strings.Contains(output, want) { @@ -181,8 +213,6 @@ func TestAFDRetainedDiagnostic(t *testing.T) { name, retention, enabled, script, want string fails bool }{ - {"default cleanup", "", "false", "./cleanup.sh", "az group delete", false}, - {"explicit ordinary cleanup", "false", "true", "./cleanup.sh", "az group delete", false}, {"retained cleanup refused", "true", "true", "./cleanup.sh", "retained", true}, {"invalid cleanup flag", "yes", "true", "./cleanup.sh", "true or false", true}, {"retained focused runner", "true", "true", "./run-e2e.sh", "-ginkgo.label-filter=afd-private-http-proof", false}, @@ -245,7 +275,7 @@ func TestAFDSetupReaderScope(t *testing.T) { } if !tt.fails { for _, member := range []string{"member-1", "member-2"} { - want := "--assignee-object-id hub-principal --assignee-principal-type ServicePrincipal --scope /subscriptions/test-subscription/resourceGroups/MC_" + member + want := "--assignee-object-id " + afdCluster("hub") + "-principal --assignee-principal-type ServicePrincipal --scope /subscriptions/test-subscription/resourceGroups/MC_" + afdCluster(member) if !strings.Contains(string(commands), want) { t.Errorf("missing hub Reader grant on verified %s node group", member) } @@ -315,12 +345,12 @@ case "$kind" in printf 'test-tenant\n' ;; "aks show") cluster_id="$base/$name" - if [[ "$name" == member-2 && -n "${AFD_TEST_SECOND_CLUSTER_ID:-}" ]]; then cluster_id="$AFD_TEST_SECOND_CLUSTER_ID"; fi + if [[ "$name" == "$MEMBER_2_AZURE_CLUSTER" && -n "${AFD_TEST_SECOND_CLUSTER_ID:-}" ]]; then cluster_id="$AFD_TEST_SECOND_CLUSTER_ID"; fi printf '{"id":"%s","nodeResourceGroup":"MC_%s","location":"test-location","identityProfile":{"kubeletidentity":{"objectId":"%s-principal","clientId":"%s-client"}}}\n' "$cluster_id" "$name" "$name" "$name" ;; "group show") member="${name#MC_}" - if [[ "$member" == member-1 ]]; then member="$AFD_TEST_MANAGED_BY"; fi - if [[ "$member" == member-2 ]]; then member="${AFD_TEST_SECOND_MANAGED_BY:-member-2}"; fi + if [[ "$member" == "$MEMBER_1_AZURE_CLUSTER" && "$AFD_TEST_MANAGED_BY" != member-1 ]]; then member="$AFD_TEST_MANAGED_BY"; fi + if [[ "$member" == "$MEMBER_2_AZURE_CLUSTER" && "${AFD_TEST_SECOND_MANAGED_BY:-member-2}" != member-2 ]]; then member="$AFD_TEST_SECOND_MANAGED_BY"; fi printf '{"id":"/subscriptions/test-subscription/resourceGroups/%s","managedBy":"%s/%s"}\n' "$name" "$base" "$member" ;; "network private-link-service show") printf '{"id":"%s","provisioningState":"Succeeded"}\n' "$id" ;; @@ -344,13 +374,13 @@ func TestAFDInstallationWithoutATM(t *testing.T) { } for _, want := range []string{ "--role CDN Profile Contributor", "--role Reader", - "--scope /subscriptions/test-subscription/resourceGroups/MC_member-1", - "--scope /subscriptions/test-subscription/resourceGroups/MC_member-2", + "--scope /subscriptions/test-subscription/resourceGroups/MC_" + afdCluster("member-1"), + "--scope /subscriptions/test-subscription/resourceGroups/MC_" + afdCluster("member-2"), "helm install hub-gateway-controller-manager", "--set afd.enabled=true", "--set-string fleetSystemNamespace=fleet-system", "--set enablePrivateLinkOriginDiscovery=true", "--kube-context member-1-admin", - "--kube-context member-2-admin", "testrg.azurecr.io/hub-gateway-controller-manager", - "--assignee-object-id member-1-principal", "--assignee-object-id member-2-principal", + "--kube-context member-2-admin", afdRegistry() + "/hub-gateway-controller-manager", + "--assignee-object-id " + afdCluster("member-1") + "-principal", "--assignee-object-id " + afdCluster("member-2") + "-principal", } { if !strings.Contains(string(commands), want) { t.Errorf("missing installation prerequisite %q in %s", want, commands) @@ -373,22 +403,36 @@ func afdTestEnvironment(t *testing.T) { "ENABLE_AFD_PRIVATE_LINK_AUTO_APPROVAL", "RETAIN_AFD_E2E_SETUP", "HUB_CLUSTER", "MEMBER_CLUSTER_1", "MEMBER_CLUSTER_2", - "E2E_SHARED_RESOURCE_GROUP", "E2E_RUN_ID", "E2E_RESOURCE_PREFIX", "E2E_TEST_PRINCIPAL_ID", + "E2E_RUN_ID", "E2E_RESOURCE_PREFIX", "E2E_TEST_PRINCIPAL_ID", "HUB_AZURE_CLUSTER", "MEMBER_1_AZURE_CLUSTER", "MEMBER_2_AZURE_CLUSTER", "REGISTRY_NAME", "HUB_GATEWAY_CONTROLLER_MANAGER_IMAGE_NAME", "HUB_GATEWAY_CONTROLLER_MANAGER_IMAGE_VERSION", "AFD_PROOF_CONTROLLER_NAMESPACE", "AFD_PROOF_CONTROLLER_DEPLOYMENT", "AFD_TEST_FAIL_COMMAND", "AFD_TEST_EMPTY_BINDINGS", "AFD_TEST_REAL_HELM", "AFD_TEST_SECOND_MANAGED_BY", "AFD_TEST_SECOND_CLUSTER_ID", "AFD_TEST_RENDERED", + "GITHUB_OUTPUT", } { t.Setenv(name, "") } t.Setenv("AZURE_SUBSCRIPTION_ID", "test-subscription") t.Setenv("AZURE_RESOURCE_GROUP", "test-rg") t.Setenv("AZURE_NETWORK_SETTING", "shared-vnet") + t.Setenv("E2E_RUN_ID", "unit-afd-1") + t.Setenv("E2E_TEST_PRINCIPAL_ID", "44444444-4444-4444-4444-444444444444") + t.Setenv("ENABLE_AFD_PRIVATE_LINK_AUTO_APPROVAL", "false") t.Setenv("TAG", "candidate") } +func afdCluster(name string) string { + hash := sha256.Sum256([]byte("test-subscription/test-rg/unit-afd-1")) + return fmt.Sprintf("fne%x-%s", hash[:8], strings.ReplaceAll(name, "-", "")) +} + +func afdRegistry() string { + hash := sha256.Sum256([]byte("test-subscription/test-rg/unit-afd-1")) + return fmt.Sprintf("fne%xacr.azurecr.io", hash[:8]) +} + func runAFDScript(t *testing.T, args ...string) (string, error) { t.Helper() if _, err := exec.LookPath("bash"); err != nil { diff --git a/test/scripts/aks-dynamic-ip-allocation.sh b/test/scripts/aks-dynamic-ip-allocation.sh index c22c974d..f06c8687 100644 --- a/test/scripts/aks-dynamic-ip-allocation.sh +++ b/test/scripts/aks-dynamic-ip-allocation.sh @@ -16,7 +16,7 @@ source "$(dirname "${BASH_SOURCE[0]}")/e2e-config.sh" # https://docs.microsoft.com/en-us/azure/aks/configure-azure-cni#configure-networking---cli-with-dynamic-allocation-of-ips-and-enhanced-subnet-support # Create virutal network and podsubnet and nodesubnet for both member clusters. -export VNET="${E2E_RESOURCE_PREFIX:+${E2E_RESOURCE_PREFIX}-}fleet" +export VNET="${E2E_RESOURCE_PREFIX}-fleet" export MEMBER_1_NODE_SUBNET=member-1-node export MEMBER_1_POD_SUBNET=member-1-pod export MEMBER_2_NODE_SUBNET=member-2-node diff --git a/test/scripts/aks-peered-vnet.sh b/test/scripts/aks-peered-vnet.sh index 29199f67..e1f6caae 100644 --- a/test/scripts/aks-peered-vnet.sh +++ b/test/scripts/aks-peered-vnet.sh @@ -21,9 +21,9 @@ source "$(dirname "${BASH_SOURCE[0]}")/e2e-config.sh" # Create virutal network and subnet for both member clusters. export MEMBER_1_TO_MEMBER_2=member-1-to-member-2 export MEMBER_2_TO_MEMBER_1=member-2-to-member-1 -export MEMBER_1_VNET="${E2E_RESOURCE_PREFIX:+${E2E_RESOURCE_PREFIX}-}member-1-vnet" +export MEMBER_1_VNET="${E2E_RESOURCE_PREFIX}-member-1-vnet" export MEMBER_1_SUBNET=member-1-subnet -export MEMBER_2_VNET="${E2E_RESOURCE_PREFIX:+${E2E_RESOURCE_PREFIX}-}member-2-vnet" +export MEMBER_2_VNET="${E2E_RESOURCE_PREFIX}-member-2-vnet" export MEMBER_2_SUBNET=member-2-subnet az network vnet create \ diff --git a/test/scripts/aks-shared-vnet.sh b/test/scripts/aks-shared-vnet.sh index 17f02038..d899be35 100644 --- a/test/scripts/aks-shared-vnet.sh +++ b/test/scripts/aks-shared-vnet.sh @@ -16,7 +16,7 @@ source "$(dirname "${BASH_SOURCE[0]}")/e2e-config.sh" # https://docs.microsoft.com/en-us/azure/virtual-network/tutorial-connect-virtual-networks-cli # Create virutal network and subnet for both member clusters. -export VNET="${E2E_RESOURCE_PREFIX:+${E2E_RESOURCE_PREFIX}-}fleet" +export VNET="${E2E_RESOURCE_PREFIX}-fleet" export MEMBER_1_SUBNET=member-1 export MEMBER_2_SUBNET=member-2 diff --git a/test/scripts/azure-principal-id.sh b/test/scripts/azure-principal-id.sh new file mode 100644 index 00000000..f23c993c --- /dev/null +++ b/test/scripts/azure-principal-id.sh @@ -0,0 +1,31 @@ +#!/bin/bash +set -o errexit +set -o nounset +set -o pipefail +set +x + +: "${AZURE_SUBSCRIPTION_ID:?AZURE_SUBSCRIPTION_ID is required}" + +az account get-access-token --subscription "$AZURE_SUBSCRIPTION_ID" \ + --resource https://management.azure.com/ --query accessToken -o tsv | + python3 -c ' +import base64 +import binascii +import json +import re +import sys + +try: + parts = sys.stdin.read().strip().split(".") + if len(parts) != 3: + raise ValueError("invalid token") + payload = parts[1] + "=" * (-len(parts[1]) % 4) + principal = json.loads(base64.urlsafe_b64decode(payload))["oid"] + if not isinstance(principal, str) or not re.fullmatch( + r"[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}", principal + ): + raise ValueError("invalid object ID") +except (binascii.Error, ValueError, UnicodeError, KeyError, TypeError): + sys.exit("error: Azure CLI token does not contain a valid principal object ID") +print(principal.lower()) +' diff --git a/test/scripts/azure_principal_id_test.go b/test/scripts/azure_principal_id_test.go new file mode 100644 index 00000000..0c03ee73 --- /dev/null +++ b/test/scripts/azure_principal_id_test.go @@ -0,0 +1,49 @@ +/* +Copyright (c) Microsoft Corporation. +Licensed under the MIT license. +*/ + +package scripts + +import ( + "encoding/base64" + "os" + "path/filepath" + "strings" + "testing" +) + +func TestAzurePrincipalID(t *testing.T) { + const id = "01234567-89ab-cdef-0123-456789abcdef" + payload := base64.RawURLEncoding.EncodeToString([]byte(`{"oid":"` + id + `"}`)) + for _, tt := range []struct { + name, token string + fails bool + }{ + {"valid", "header." + payload + ".signature", false}, + {"malformed", "not-a-token", true}, + {"missing object ID", "header.e30.signature", true}, + } { + t.Run(tt.name, func(t *testing.T) { + afdTestEnvironment(t) + dir := t.TempDir() + writeAFDCommand(t, filepath.Join(dir, "az"), `#!/bin/bash +set -euo pipefail +[[ "$*" == "account get-access-token --subscription test-subscription --resource https://management.azure.com/ --query accessToken -o tsv" ]] +printf '%s\n' "$TEST_TOKEN" +`) + t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH")) + t.Setenv("TEST_TOKEN", tt.token) + output, err := runAFDScript(t, "-x", "./azure-principal-id.sh") + if (err != nil) != tt.fails || strings.Contains(output, tt.token) { + t.Fatalf("principal extraction: %s (%v)", output, err) + } + if !tt.fails && !strings.Contains(output, id) { + t.Fatalf("principal ID missing: %s", output) + } + if tt.fails && !strings.Contains(output, "error:") { + t.Fatalf("invalid token was not reported: %s", output) + } + }) + } +} diff --git a/test/scripts/bootstrap.sh b/test/scripts/bootstrap.sh index 8eeed431..08183aef 100644 --- a/test/scripts/bootstrap.sh +++ b/test/scripts/bootstrap.sh @@ -36,62 +36,44 @@ fi az account set -s ${AZURE_SUBSCRIPTION_ID} -# Create resource group to host hub and member clusters. -# RANDOM ID promises workflow runs don't interface one another. -export RESOURCE_GROUP="${AZURE_RESOURCE_GROUP:-fleet-networking-e2e-$RANDOM}" +export RESOURCE_GROUP="$AZURE_RESOURCE_GROUP" export LOCATION="${LOCATION:-eastus2}" -if [[ "$E2E_SHARED_RESOURCE_GROUP" == true ]]; then - if [[ -z "${KUBECONFIG:-}" || "$KUBECONFIG" == *:* || -e "$KUBECONFIG" || -L "$KUBECONFIG" ]]; then - echo "error: shared setup requires a new, run-specific KUBECONFIG path" >&2 - exit 1 - fi - group="$(az group show --subscription "$AZURE_SUBSCRIPTION_ID" --name "$RESOURCE_GROUP" -o json)" - jq -e --arg id "/subscriptions/$AZURE_SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP" \ - '(.id | ascii_downcase) == ($id | ascii_downcase) and .tags.managedBy == "aks-rp/ci-resources" and .tags.workload == "fleet-networking-e2e"' \ - <<<"$group" > /dev/null - resources="$(az resource list --subscription "$AZURE_SUBSCRIPTION_ID" --resource-group "$RESOURCE_GROUP" -o json)" - if ! jq -e --arg prefix "$E2E_RESOURCE_PREFIX" --arg run "$E2E_RUN_ID" ' - all(.[]; - ((.name | ascii_downcase | startswith($prefix)) | not) and - .tags["fleet-e2e-run"] != $run and - ((.tags["networking.fleet.azure.com.trafficManagerProfile"] // "") | startswith($prefix + "-") | not) and - ((.tags["networking.fleet.azure.com.gateway-namespace"] // "") | startswith($prefix + "-") | not)) - ' <<<"$resources" >/dev/null; then - echo "error: refusing to reuse resources for run $E2E_RUN_ID" >&2 - exit 1 - fi - echo "##vso[task.setvariable variable=e2eResourcesStarted]true" -else - az group create --name $RESOURCE_GROUP --location $LOCATION --tags "source=fleet-networking" +if [[ -z "${KUBECONFIG:-}" || "$KUBECONFIG" == *:* || -e "$KUBECONFIG" || -L "$KUBECONFIG" ]]; then + echo "error: shared setup requires a new, run-specific KUBECONFIG path" >&2 + exit 1 +fi +group="$(az group show --subscription "$AZURE_SUBSCRIPTION_ID" --name "$RESOURCE_GROUP" -o json)" +jq -e --arg id "/subscriptions/$AZURE_SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP" \ + '(.id | ascii_downcase) == ($id | ascii_downcase) and .tags.managedBy == "aks-rp/ci-resources" and .tags.workload == "fleet-networking-e2e"' \ + <<<"$group" > /dev/null +resources="$(az resource list --subscription "$AZURE_SUBSCRIPTION_ID" --resource-group "$RESOURCE_GROUP" -o json)" +if ! jq -e --arg prefix "$E2E_RESOURCE_PREFIX" --arg run "$E2E_RUN_ID" ' + all(.[]; + ((.name | ascii_downcase | startswith($prefix)) | not) and + .tags["fleet-e2e-run"] != $run and + ((.tags["networking.fleet.azure.com.trafficManagerProfile"] // "") | startswith($prefix + "-") | not) and + ((.tags["networking.fleet.azure.com.gateway-namespace"] // "") | startswith($prefix + "-") | not)) +' <<<"$resources" >/dev/null; then + echo "error: refusing to reuse resources for run $E2E_RUN_ID" >&2 + exit 1 +fi +echo "##vso[task.setvariable variable=e2eResourcesStarted]true" +if [[ -n "${GITHUB_OUTPUT:-}" ]]; then + echo "resources_started=true" >>"$GITHUB_OUTPUT" fi -# Defer function to recycle created Azure resource. -function cleanup { - if [[ "$E2E_SHARED_RESOURCE_GROUP" == true ]]; then - echo "shared resource group setup interrupted; run explicit per-run cleanup" >&2 - else - az group delete -n $RESOURCE_GROUP --no-wait --yes - fi -} if [[ "$RETAIN_AFD_E2E_SETUP" == true ]]; then trap 'echo "AFD setup interrupted; retaining resources for explicit later cleanup" >&2; exit 130' INT trap 'echo "AFD setup interrupted; retaining resources for explicit later cleanup" >&2; exit 143' TERM -elif [[ "$E2E_SHARED_RESOURCE_GROUP" == true ]]; then +else trap 'echo "Shared setup interrupted; run explicit per-run cleanup" >&2; exit 130' INT trap 'echo "Shared setup interrupted; run explicit per-run cleanup" >&2; exit 143' TERM -else - trap cleanup INT TERM fi # Pubilsh fleet networking agent images. # TODO(mainred): Once we have a specific Azure sub for fleet networking e2e test, we can reuse that registry. # Registry name must conform to the following pattern: '^[a-zA-Z0-9]*$'. -if [[ "$E2E_SHARED_RESOURCE_GROUP" == true ]]; then - az acr create -g "$RESOURCE_GROUP" -n "$REGISTRY_NAME" --sku standard "${E2E_RESOURCE_TAGS[@]}" -else - export REGISTRY_NAME="${RESOURCE_GROUP//-}" - az acr create -g "$RESOURCE_GROUP" -n "$REGISTRY_NAME" --sku standard --tags "source=fleet-networking" -fi +az acr create -g "$RESOURCE_GROUP" -n "$REGISTRY_NAME" --sku standard "${E2E_RESOURCE_TAGS[@]}" # Enable anonymous to not wait for the long-running AKS creation. # When attach-acr and `--enable-managed-identity` are both specified, AKS requires us to wait until the whole operation # succeeds, and as AuthN and AuthZ for member cluster agents to hub cluster in our test requires managed identity, @@ -103,20 +85,8 @@ export TAG="${TAG:-$(git rev-parse --short=7 HEAD)}" make push # Create hub and member clusters and wait until all clusters are ready. -export HUB_CLUSTER=${HUB_CLUSTER:-"hub"} -export MEMBER_CLUSTER_1=${MEMBER_CLUSTER_1:-"member-1"} -export MEMBER_CLUSTER_2=${MEMBER_CLUSTER_2:-"member-2"} export NODE_COUNT=2 -export HUB_CLUSTER_AKS_ID_NAME=${HUB_CLUSTER_AKS_ID_NAME:-"fleet-net-hub-aks-id"} -export HUB_CLUSTER_AKS_KUBELET_ID_NAME=${HUB_CLUSTER_AKS_KUBELET_ID_NAME:-"fleet-net-hub-aks-kubelet-id"} -export MEMBER_CLUSTER_1_AKS_ID_NAME=${MEMBER_CLUSTER_1_AKS_ID_NAME:-"fleet-net-member-1-aks-id"} -export MEMBER_CLUSTER_1_AKS_KUBELET_ID_NAME=${MEMBER_CLUSTER_1_AKS_KUBELET_ID_NAME:-"fleet-net-member-1-aks-kubelet-id"} -export MEMBER_CLUSTER_2_AKS_ID_NAME=${MEMBER_CLUSTER_2_AKS_ID_NAME:-"fleet-net-member-2-aks-id"} -export MEMBER_CLUSTER_2_AKS_KUBELET_ID_NAME=${MEMBER_CLUSTER_2_AKS_KUBELET_ID_NAME:-"fleet-net-member-2-aks-kubelet-id"} - - - if [ "$ENABLE_TRAFFIC_MANAGER" == "false" ]; then # Create aks hub cluster, specifying amd64 VM size to ensure linux/amd64 docker images can be consumed. echo "Creating aks cluster: ${HUB_CLUSTER}" @@ -204,8 +174,6 @@ case $AZURE_NETWORK_SETTING in bash test/scripts/aks-no-networking.sh ;; perf-test) - export MEMBER_CLUSTER_3=member-3 - export MEMBER_CLUSTER_4=member-4 export MEMBER_LOCATION_1="${MEMBER_LOCATION_1:-eastus2}" export MEMBER_1_LOCATION=$MEMBER_LOCATION_1 export MEMBER_2_LOCATION=$MEMBER_LOCATION_1 @@ -223,8 +191,8 @@ az aks wait --created --interval 10 --name $MEMBER_1_AZURE_CLUSTER --resource-gr az aks wait --created --interval 10 --name $MEMBER_2_AZURE_CLUSTER --resource-group $RESOURCE_GROUP --timeout 1800 if [ "${AZURE_NETWORK_SETTING}" == "perf-test" ] then - az aks wait --created --interval 10 --name $MEMBER_CLUSTER_3 --resource-group $RESOURCE_GROUP --timeout 1800 - az aks wait --created --interval 10 --name $MEMBER_CLUSTER_4 --resource-group $RESOURCE_GROUP --timeout 1800 + az aks wait --created --interval 10 --name $MEMBER_3_AZURE_CLUSTER --resource-group $RESOURCE_GROUP --timeout 1800 + az aks wait --created --interval 10 --name $MEMBER_4_AZURE_CLUSTER --resource-group $RESOURCE_GROUP --timeout 1800 fi # hack: add role assignments to kubelet identity @@ -297,8 +265,8 @@ az aks get-credentials --name $MEMBER_1_AZURE_CLUSTER -g $RESOURCE_GROUP --admin az aks get-credentials --name $MEMBER_2_AZURE_CLUSTER -g $RESOURCE_GROUP --admin --context "$MEMBER_CLUSTER_2-admin" --overwrite-existing if [ "${AZURE_NETWORK_SETTING}" == "perf-test" ] then - az aks get-credentials --name $MEMBER_CLUSTER_3 -g $RESOURCE_GROUP --admin --overwrite-existing - az aks get-credentials --name $MEMBER_CLUSTER_4 -g $RESOURCE_GROUP --admin --overwrite-existing + az aks get-credentials --name $MEMBER_3_AZURE_CLUSTER -g $RESOURCE_GROUP --admin --context "$MEMBER_CLUSTER_3-admin" --overwrite-existing + az aks get-credentials --name $MEMBER_4_AZURE_CLUSTER -g $RESOURCE_GROUP --admin --context "$MEMBER_CLUSTER_4-admin" --overwrite-existing fi HUB_URL="$(kubectl --context "$HUB_CLUSTER-admin" config view --minify -o jsonpath='{.clusters[0].cluster.server}')" export HUB_URL @@ -311,10 +279,10 @@ if [ "$ENABLE_TRAFFIC_MANAGER" == "false" ]; then export PRINCIPAL_FOR_MEMBER_2=$(az identity list -g MC_"$RESOURCE_GROUP"_"$MEMBER_2_AZURE_CLUSTER"_"$MEMBER_2_LOCATION" | jq --arg identity $MEMBER_2_AZURE_CLUSTER-agentpool -r -c 'map(select(.name | contains($identity)))[].principalId') if [ "${AZURE_NETWORK_SETTING}" == "perf-test" ] then - export CLIENT_ID_FOR_MEMBER_3=$(az identity list -g MC_"$RESOURCE_GROUP"_"$MEMBER_CLUSTER_3"_"$MEMBER_LOCATION_2" | jq --arg identity $MEMBER_CLUSTER_3-agentpool -r -c 'map(select(.name | contains($identity)))[].clientId') - export PRINCIPAL_FOR_MEMBER_3=$(az identity list -g MC_"$RESOURCE_GROUP"_"$MEMBER_CLUSTER_3"_"$MEMBER_LOCATION_2" | jq --arg identity $MEMBER_CLUSTER_3-agentpool -r -c 'map(select(.name | contains($identity)))[].principalId') - export CLIENT_ID_FOR_MEMBER_4=$(az identity list -g MC_"$RESOURCE_GROUP"_"$MEMBER_CLUSTER_4"_"$MEMBER_LOCATION_2" | jq --arg identity $MEMBER_CLUSTER_4-agentpool -r -c 'map(select(.name | contains($identity)))[].clientId') - export PRINCIPAL_FOR_MEMBER_4=$(az identity list -g MC_"$RESOURCE_GROUP"_"$MEMBER_CLUSTER_4"_"$MEMBER_LOCATION_2" | jq --arg identity $MEMBER_CLUSTER_4-agentpool -r -c 'map(select(.name | contains($identity)))[].principalId') + export CLIENT_ID_FOR_MEMBER_3=$(az identity list -g MC_"$RESOURCE_GROUP"_"$MEMBER_3_AZURE_CLUSTER"_"$MEMBER_LOCATION_2" | jq --arg identity $MEMBER_3_AZURE_CLUSTER-agentpool -r -c 'map(select(.name | contains($identity)))[].clientId') + export PRINCIPAL_FOR_MEMBER_3=$(az identity list -g MC_"$RESOURCE_GROUP"_"$MEMBER_3_AZURE_CLUSTER"_"$MEMBER_LOCATION_2" | jq --arg identity $MEMBER_3_AZURE_CLUSTER-agentpool -r -c 'map(select(.name | contains($identity)))[].principalId') + export CLIENT_ID_FOR_MEMBER_4=$(az identity list -g MC_"$RESOURCE_GROUP"_"$MEMBER_4_AZURE_CLUSTER"_"$MEMBER_LOCATION_2" | jq --arg identity $MEMBER_4_AZURE_CLUSTER-agentpool -r -c 'map(select(.name | contains($identity)))[].clientId') + export PRINCIPAL_FOR_MEMBER_4=$(az identity list -g MC_"$RESOURCE_GROUP"_"$MEMBER_4_AZURE_CLUSTER"_"$MEMBER_LOCATION_2" | jq --arg identity $MEMBER_4_AZURE_CLUSTER-agentpool -r -c 'map(select(.name | contains($identity)))[].principalId') fi else export CLIENT_ID_FOR_MEMBER_1=$MEMBER_CLUSTER_1_KUBELET_CLIENT_ID diff --git a/test/scripts/cleanup-shared-group.sh b/test/scripts/cleanup-shared-group.sh index 022dd0f8..f0748175 100644 --- a/test/scripts/cleanup-shared-group.sh +++ b/test/scripts/cleanup-shared-group.sh @@ -4,8 +4,8 @@ set -o nounset set -o pipefail source "$(dirname "${BASH_SOURCE[0]}")/e2e-config.sh" -if [[ "$E2E_SHARED_RESOURCE_GROUP" != true || "$RETAIN_AFD_E2E_SETUP" == true ]]; then - echo "error: shared cleanup requires shared mode and non-retained setup" >&2 +if [[ "$RETAIN_AFD_E2E_SETUP" == true ]]; then + echo "error: shared cleanup requires non-retained setup" >&2 exit 1 fi @@ -17,13 +17,14 @@ jq -e --arg id "$group_id" \ resources="$(az resource list --subscription "$AZURE_SUBSCRIPTION_ID" --resource-group "$AZURE_RESOURCE_GROUP" -o json)" if ! jq -e --arg prefix "$E2E_RESOURCE_PREFIX" --arg run "$E2E_RUN_ID" --arg group "$group_id" \ - --arg hub "$HUB_AZURE_CLUSTER" --arg member1 "$MEMBER_1_AZURE_CLUSTER" --arg member2 "$MEMBER_2_AZURE_CLUSTER" ' + --arg hub "$HUB_AZURE_CLUSTER" --arg member1 "$MEMBER_1_AZURE_CLUSTER" --arg member2 "$MEMBER_2_AZURE_CLUSTER" \ + --arg member3 "$MEMBER_3_AZURE_CLUSTER" --arg member4 "$MEMBER_4_AZURE_CLUSTER" ' all(.[]; if (.name | ascii_downcase | startswith($prefix)) or (.tags["fleet-e2e-run"] // "") == $run then .tags.source == "fleet-networking" and .tags["fleet-e2e-run"] == $run and ((.id | ascii_downcase) == (($group + "/providers/" + .type + "/" + .name) | ascii_downcase)) and (if (.type | ascii_downcase) == "microsoft.containerservice/managedclusters" then - (.name == $hub or .name == $member1 or .name == $member2) and + (.name == $hub or .name == $member1 or .name == $member2 or .name == $member3 or .name == $member4) and (.tags["fleet-e2e-atm"] == "true" or .tags["fleet-e2e-atm"] == "false") and (.tags["fleet-e2e-afd"] == "true" or .tags["fleet-e2e-afd"] == "false") and (.tags["fleet-e2e-auto-approval"] == "true" or .tags["fleet-e2e-auto-approval"] == "false") and diff --git a/test/scripts/cleanup.sh b/test/scripts/cleanup.sh index 65e4bff7..0e13c2c0 100644 --- a/test/scripts/cleanup.sh +++ b/test/scripts/cleanup.sh @@ -16,14 +16,4 @@ case "${RETAIN_AFD_E2E_SETUP:-false}" in ;; esac -[[ -z "${AZURE_RESOURCE_GROUP}" ]] && echo "AZURE_RESOURCE_GROUP is not set" && exit 1 - -if [[ "${E2E_SHARED_RESOURCE_GROUP:-false}" == true ]]; then - exec bash "$(dirname "${BASH_SOURCE[0]}")/cleanup-shared-group.sh" -fi -if [[ "${E2E_SHARED_RESOURCE_GROUP:-false}" != false ]]; then - echo "error: E2E_SHARED_RESOURCE_GROUP must be true or false" >&2 - exit 1 -fi - -az group show --name "$AZURE_RESOURCE_GROUP" && az group delete --name "$AZURE_RESOURCE_GROUP" --no-wait --yes +exec bash "$(dirname "${BASH_SOURCE[0]}")/cleanup-shared-group.sh" diff --git a/test/scripts/e2e-config.sh b/test/scripts/e2e-config.sh index 0b1af37e..23266bcf 100644 --- a/test/scripts/e2e-config.sh +++ b/test/scripts/e2e-config.sh @@ -4,57 +4,42 @@ export ENABLE_TRAFFIC_MANAGER="${ENABLE_TRAFFIC_MANAGER:-false}" export ENABLE_AZURE_FRONT_DOOR="${ENABLE_AZURE_FRONT_DOOR:-false}" export RETAIN_AFD_E2E_SETUP="${RETAIN_AFD_E2E_SETUP:-false}" export AZURE_NETWORK_SETTING="${AZURE_NETWORK_SETTING:-shared-vnet}" -export E2E_SHARED_RESOURCE_GROUP="${E2E_SHARED_RESOURCE_GROUP:-false}" -case "$E2E_SHARED_RESOURCE_GROUP" in - false) - unset E2E_RESOURCE_PREFIX HUB_AZURE_CLUSTER MEMBER_1_AZURE_CLUSTER MEMBER_2_AZURE_CLUSTER - ;; - true) - if [[ "$ENABLE_TRAFFIC_MANAGER" != true && "$ENABLE_TRAFFIC_MANAGER" != false ]]; then - echo "error: ENABLE_TRAFFIC_MANAGER must be true or false in shared mode" >&2 - return 1 - fi - if [[ -z "${AZURE_SUBSCRIPTION_ID:-}" || -z "${AZURE_RESOURCE_GROUP:-}" || - ! "${E2E_RUN_ID:-}" =~ ^[a-z0-9][a-z0-9-]{0,62}$ ]]; then - echo "error: shared resource group mode requires subscription, resource group and a lowercase alphanumeric E2E_RUN_ID" >&2 - return 1 - fi - if [[ "$AZURE_NETWORK_SETTING" == perf-test ]]; then - echo "error: shared resource group mode does not support perf-test" >&2 - return 1 - fi - if [[ "${HUB_CLUSTER:-hub}" != hub || "${MEMBER_CLUSTER_1:-member-1}" != member-1 || - "${MEMBER_CLUSTER_2:-member-2}" != member-2 ]]; then - echo "error: shared resource group mode requires default logical cluster names" >&2 - return 1 - fi - E2E_RESOURCE_PREFIX="fne$(printf '%s' "$AZURE_SUBSCRIPTION_ID/$AZURE_RESOURCE_GROUP/$E2E_RUN_ID" | sha256sum | cut -c1-16)" - export E2E_RESOURCE_PREFIX - export HUB_AZURE_CLUSTER="${E2E_RESOURCE_PREFIX}-hub" - export MEMBER_1_AZURE_CLUSTER="${E2E_RESOURCE_PREFIX}-member1" - export MEMBER_2_AZURE_CLUSTER="${E2E_RESOURCE_PREFIX}-member2" - export REGISTRY_NAME="${E2E_RESOURCE_PREFIX}acr" - export REGISTRY="${REGISTRY_NAME}.azurecr.io" - export HUB_CLUSTER_AKS_ID_NAME="${E2E_RESOURCE_PREFIX}-hub-control" - export HUB_CLUSTER_AKS_KUBELET_ID_NAME="${E2E_RESOURCE_PREFIX}-hub-kubelet" - export MEMBER_CLUSTER_1_AKS_ID_NAME="${E2E_RESOURCE_PREFIX}-member1-control" - export MEMBER_CLUSTER_1_AKS_KUBELET_ID_NAME="${E2E_RESOURCE_PREFIX}-member1-kubelet" - export MEMBER_CLUSTER_2_AKS_ID_NAME="${E2E_RESOURCE_PREFIX}-member2-control" - export MEMBER_CLUSTER_2_AKS_KUBELET_ID_NAME="${E2E_RESOURCE_PREFIX}-member2-kubelet" - ;; - *) - echo "error: E2E_SHARED_RESOURCE_GROUP must be true or false" >&2 - return 1 - ;; -esac +if [[ "$ENABLE_TRAFFIC_MANAGER" != true && "$ENABLE_TRAFFIC_MANAGER" != false ]]; then + echo "error: ENABLE_TRAFFIC_MANAGER must be true or false" >&2 + return 1 +fi +if [[ -z "${AZURE_SUBSCRIPTION_ID:-}" || -z "${AZURE_RESOURCE_GROUP:-}" || + ! "${E2E_RUN_ID:-}" =~ ^[a-z0-9][a-z0-9-]{0,62}$ ]]; then + echo "error: shared resource group requires AZURE_SUBSCRIPTION_ID, AZURE_RESOURCE_GROUP and a lowercase alphanumeric E2E_RUN_ID" >&2 + return 1 +fi +if [[ "${HUB_CLUSTER:-hub}" != hub || "${MEMBER_CLUSTER_1:-member-1}" != member-1 || + "${MEMBER_CLUSTER_2:-member-2}" != member-2 || "${MEMBER_CLUSTER_3:-member-3}" != member-3 || + "${MEMBER_CLUSTER_4:-member-4}" != member-4 ]]; then + echo "error: shared resource group requires default logical cluster names" >&2 + return 1 +fi +E2E_RESOURCE_PREFIX="fne$(printf '%s' "$AZURE_SUBSCRIPTION_ID/$AZURE_RESOURCE_GROUP/$E2E_RUN_ID" | sha256sum | cut -c1-16)" +export E2E_RESOURCE_PREFIX +export HUB_AZURE_CLUSTER="${E2E_RESOURCE_PREFIX}-hub" +export MEMBER_1_AZURE_CLUSTER="${E2E_RESOURCE_PREFIX}-member1" +export MEMBER_2_AZURE_CLUSTER="${E2E_RESOURCE_PREFIX}-member2" +export MEMBER_3_AZURE_CLUSTER="${E2E_RESOURCE_PREFIX}-member3" +export MEMBER_4_AZURE_CLUSTER="${E2E_RESOURCE_PREFIX}-member4" +export REGISTRY_NAME="${E2E_RESOURCE_PREFIX}acr" +export REGISTRY="${REGISTRY_NAME}.azurecr.io" +export HUB_CLUSTER_AKS_ID_NAME="${E2E_RESOURCE_PREFIX}-hub-control" +export HUB_CLUSTER_AKS_KUBELET_ID_NAME="${E2E_RESOURCE_PREFIX}-hub-kubelet" +export MEMBER_CLUSTER_1_AKS_ID_NAME="${E2E_RESOURCE_PREFIX}-member1-control" +export MEMBER_CLUSTER_1_AKS_KUBELET_ID_NAME="${E2E_RESOURCE_PREFIX}-member1-kubelet" +export MEMBER_CLUSTER_2_AKS_ID_NAME="${E2E_RESOURCE_PREFIX}-member2-control" +export MEMBER_CLUSTER_2_AKS_KUBELET_ID_NAME="${E2E_RESOURCE_PREFIX}-member2-kubelet" export HUB_CLUSTER="${HUB_CLUSTER:-hub}" export MEMBER_CLUSTER_1="${MEMBER_CLUSTER_1:-member-1}" export MEMBER_CLUSTER_2="${MEMBER_CLUSTER_2:-member-2}" -export HUB_AZURE_CLUSTER="${HUB_AZURE_CLUSTER:-$HUB_CLUSTER}" -export MEMBER_1_AZURE_CLUSTER="${MEMBER_1_AZURE_CLUSTER:-$MEMBER_CLUSTER_1}" -export MEMBER_2_AZURE_CLUSTER="${MEMBER_2_AZURE_CLUSTER:-$MEMBER_CLUSTER_2}" -E2E_RESOURCE_TAGS=() +export MEMBER_CLUSTER_3="${MEMBER_CLUSTER_3:-member-3}" +export MEMBER_CLUSTER_4="${MEMBER_CLUSTER_4:-member-4}" if [[ "$ENABLE_AZURE_FRONT_DOOR" != true && "$ENABLE_AZURE_FRONT_DOOR" != false ]]; then echo "error: ENABLE_AZURE_FRONT_DOOR must be true or false" >&2 @@ -84,14 +69,13 @@ if [[ "$ENABLE_AZURE_FRONT_DOOR" == true ]]; then echo "error: AFD requires AZURE_SUBSCRIPTION_ID and AZURE_RESOURCE_GROUP" >&2 return 1 fi - if [[ "$E2E_SHARED_RESOURCE_GROUP" == true && "$ENABLE_AFD_PRIVATE_LINK_AUTO_APPROVAL" == true && + if [[ "$ENABLE_AFD_PRIVATE_LINK_AUTO_APPROVAL" == true && ! "${E2E_TEST_PRINCIPAL_ID:-}" =~ ^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$ ]]; then echo "error: shared AFD approval requires E2E_TEST_PRINCIPAL_ID" >&2 return 1 fi - if [[ "$E2E_SHARED_RESOURCE_GROUP" == true && - ( "${AFD_PROOF_CONTROLLER_NAMESPACE:-fleet-system}" != fleet-system || - "${AFD_PROOF_CONTROLLER_DEPLOYMENT:-hub-gateway-controller-manager}" != hub-gateway-controller-manager ) ]]; then + if [[ "${AFD_PROOF_CONTROLLER_NAMESPACE:-fleet-system}" != fleet-system || + "${AFD_PROOF_CONTROLLER_DEPLOYMENT:-hub-gateway-controller-manager}" != hub-gateway-controller-manager ]]; then echo "error: shared AFD mode requires the default controller namespace and deployment" >&2 return 1 fi @@ -102,12 +86,6 @@ if [[ "$ENABLE_AZURE_FRONT_DOOR" == true ]]; then fi export ENABLE_GATEWAY_API=true export ENABLE_AFD_PRIVATE_HTTP_PROOF=true - # Derive the same candidate in separate setup/test shells; do not rely on child exports. - if [[ "$E2E_SHARED_RESOURCE_GROUP" == true ]]; then - export REGISTRY="${REGISTRY_NAME}.azurecr.io" - else - export REGISTRY="${AZURE_RESOURCE_GROUP//-}.azurecr.io" - fi if [[ -z "${TAG:-}" ]]; then TAG="$(git rev-parse --short=7 HEAD)" || return 1 export TAG @@ -117,11 +95,9 @@ if [[ "$ENABLE_AZURE_FRONT_DOOR" == true ]]; then export AFD_PROOF_CONTROLLER_IMAGE="${REGISTRY}/${HUB_GATEWAY_CONTROLLER_MANAGER_IMAGE_NAME:-hub-gateway-controller-manager}:${HUB_GATEWAY_CONTROLLER_MANAGER_IMAGE_VERSION:-$TAG}" fi -if [[ "$E2E_SHARED_RESOURCE_GROUP" == true ]]; then - E2E_RESOURCE_TAGS=(--tags "source=fleet-networking" "fleet-e2e-run=$E2E_RUN_ID" - "fleet-e2e-atm=$ENABLE_TRAFFIC_MANAGER" "fleet-e2e-afd=$ENABLE_AZURE_FRONT_DOOR" - "fleet-e2e-auto-approval=$ENABLE_AFD_PRIVATE_LINK_AUTO_APPROVAL") - if [[ "$ENABLE_AZURE_FRONT_DOOR" == true && "$ENABLE_AFD_PRIVATE_LINK_AUTO_APPROVAL" == true ]]; then - E2E_RESOURCE_TAGS+=("fleet-e2e-test-principal=$E2E_TEST_PRINCIPAL_ID") - fi +E2E_RESOURCE_TAGS=(--tags "source=fleet-networking" "fleet-e2e-run=$E2E_RUN_ID" + "fleet-e2e-atm=$ENABLE_TRAFFIC_MANAGER" "fleet-e2e-afd=$ENABLE_AZURE_FRONT_DOOR" + "fleet-e2e-auto-approval=$ENABLE_AFD_PRIVATE_LINK_AUTO_APPROVAL") +if [[ "$ENABLE_AZURE_FRONT_DOOR" == true && "$ENABLE_AFD_PRIVATE_LINK_AUTO_APPROVAL" == true ]]; then + E2E_RESOURCE_TAGS+=("fleet-e2e-test-principal=$E2E_TEST_PRINCIPAL_ID") fi diff --git a/test/scripts/install-afd.sh b/test/scripts/install-afd.sh index ba9184e3..c02e00fe 100644 --- a/test/scripts/install-afd.sh +++ b/test/scripts/install-afd.sh @@ -67,7 +67,7 @@ for member in member-1 member-2; do az role assignment create --subscription "$AZURE_SUBSCRIPTION_ID" --role Reader \ --assignee-object-id "$principal" --assignee-principal-type ServicePrincipal \ --scope "/subscriptions/$AZURE_SUBSCRIPTION_ID/resourceGroups/$node_group" >/dev/null - if [[ "$E2E_SHARED_RESOURCE_GROUP" == true && "$ENABLE_AFD_PRIVATE_LINK_AUTO_APPROVAL" == true ]]; then + if [[ "$ENABLE_AFD_PRIVATE_LINK_AUTO_APPROVAL" == true ]]; then az role assignment create --subscription "$AZURE_SUBSCRIPTION_ID" --role "Network Contributor" \ --assignee-object-id "$E2E_TEST_PRINCIPAL_ID" --assignee-principal-type ServicePrincipal \ --scope "/subscriptions/$AZURE_SUBSCRIPTION_ID/resourceGroups/$node_group" >/dev/null diff --git a/test/scripts/perf-test.sh b/test/scripts/perf-test.sh index 06a14cce..12236024 100644 --- a/test/scripts/perf-test.sh +++ b/test/scripts/perf-test.sh @@ -3,14 +3,15 @@ set -o errexit set -o nounset set -o pipefail set -x +source "$(dirname "${BASH_SOURCE[0]}")/e2e-config.sh" # This script creates 4 member clusters in 2 separate groups; each group has its own # virtual network. The two virtual networks are peer-linked, so as to allow connectivity # between clusters in different groups. # Create the two virtual networks; each has two subnets for two member clusters. -export VNET_1=vnet-1 -export VNET_2=vnet-2 +export VNET_1="${E2E_RESOURCE_PREFIX}-vnet-1" +export VNET_2="${E2E_RESOURCE_PREFIX}-vnet-2" export MEMBER_SUBNET_1=subnet-1 export MEMBER_SUBNET_2=subnet-2 @@ -18,7 +19,7 @@ az network vnet create \ --name $VNET_1 \ --location $MEMBER_LOCATION_1 \ -g $RESOURCE_GROUP \ - --address-prefixes 10.1.0.0/16 + --address-prefixes 10.1.0.0/16 "${E2E_RESOURCE_TAGS[@]}" az network vnet subnet create \ --vnet-name $VNET_1 \ --name $MEMBER_SUBNET_1 \ @@ -34,7 +35,7 @@ az network vnet create \ --name $VNET_2 \ --location $MEMBER_LOCATION_2 \ -g $RESOURCE_GROUP \ - --address-prefixes 10.2.0.0/16 + --address-prefixes 10.2.0.0/16 "${E2E_RESOURCE_TAGS[@]}" az network vnet subnet create \ --vnet-name $VNET_2 \ --name $MEMBER_SUBNET_1 \ @@ -73,7 +74,7 @@ az network vnet peering create \ az aks create \ --location $MEMBER_LOCATION_1 \ --resource-group $RESOURCE_GROUP \ - --name $MEMBER_CLUSTER_1 \ + --name $MEMBER_1_AZURE_CLUSTER \ --node-count $NODE_COUNT \ --node-vm-size Standard_A2_v2 \ --generate-ssh-keys \ @@ -81,12 +82,12 @@ az aks create \ --enable-azure-rbac \ --network-plugin azure \ --vnet-subnet-id "/subscriptions/$AZURE_SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP/providers/Microsoft.Network/virtualNetworks/$VNET_1/subnets/$MEMBER_SUBNET_1" \ - --no-wait + --no-wait "${E2E_RESOURCE_TAGS[@]}" az aks create \ --location $MEMBER_LOCATION_1 \ --resource-group $RESOURCE_GROUP \ - --name $MEMBER_CLUSTER_2 \ + --name $MEMBER_2_AZURE_CLUSTER \ --node-count $NODE_COUNT \ --node-vm-size Standard_A2_v2 \ --generate-ssh-keys \ @@ -94,12 +95,12 @@ az aks create \ --enable-azure-rbac \ --network-plugin azure \ --vnet-subnet-id "/subscriptions/$AZURE_SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP/providers/Microsoft.Network/virtualNetworks/$VNET_1/subnets/$MEMBER_SUBNET_2" \ - --no-wait + --no-wait "${E2E_RESOURCE_TAGS[@]}" az aks create \ --location $MEMBER_LOCATION_2 \ --resource-group $RESOURCE_GROUP \ - --name $MEMBER_CLUSTER_3 \ + --name $MEMBER_3_AZURE_CLUSTER \ --node-count $NODE_COUNT \ --node-vm-size Standard_A2_v2 \ --generate-ssh-keys \ @@ -107,12 +108,12 @@ az aks create \ --enable-azure-rbac \ --network-plugin azure \ --vnet-subnet-id "/subscriptions/$AZURE_SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP/providers/Microsoft.Network/virtualNetworks/$VNET_2/subnets/$MEMBER_SUBNET_1" \ - --no-wait + --no-wait "${E2E_RESOURCE_TAGS[@]}" az aks create \ --location $MEMBER_LOCATION_2 \ --resource-group $RESOURCE_GROUP \ - --name $MEMBER_CLUSTER_4 \ + --name $MEMBER_4_AZURE_CLUSTER \ --node-count $NODE_COUNT \ --node-vm-size Standard_A2_v2 \ --generate-ssh-keys \ @@ -120,4 +121,4 @@ az aks create \ --enable-azure-rbac \ --network-plugin azure \ --vnet-subnet-id "/subscriptions/$AZURE_SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP/providers/Microsoft.Network/virtualNetworks/$VNET_2/subnets/$MEMBER_SUBNET_2" \ - --no-wait + --no-wait "${E2E_RESOURCE_TAGS[@]}" diff --git a/test/scripts/shared_group_test.go b/test/scripts/shared_group_test.go index bdc8f7b7..c5483d80 100644 --- a/test/scripts/shared_group_test.go +++ b/test/scripts/shared_group_test.go @@ -20,7 +20,6 @@ func TestSharedGroupConfiguration(t *testing.T) { afdTestEnvironment(t) run := func(id string) (string, error) { t.Helper() - t.Setenv("E2E_SHARED_RESOURCE_GROUP", "true") t.Setenv("E2E_RUN_ID", id) t.Setenv("AZURE_SUBSCRIPTION_ID", "test-subscription") t.Setenv("AZURE_RESOURCE_GROUP", "fleet-networking-e2e") @@ -47,6 +46,7 @@ printf '%s|%s|%s|%s|%s\n' "$E2E_RESOURCE_PREFIX" "$HUB_AZURE_CLUSTER" "$MEMBER_1 } } t.Setenv("ENABLE_AZURE_FRONT_DOOR", "true") + t.Setenv("ENABLE_AFD_PRIVATE_LINK_AUTO_APPROVAL", "true") t.Setenv("E2E_TEST_PRINCIPAL_ID", "") output, err := run("123-afd-1") if err == nil || !strings.Contains(output, "E2E_TEST_PRINCIPAL_ID") { @@ -56,9 +56,9 @@ printf '%s|%s|%s|%s|%s\n' "$E2E_RESOURCE_PREFIX" "$HUB_AZURE_CLUSTER" "$MEMBER_1 func TestSharedAFDInstallation(t *testing.T) { afdTestEnvironment(t) - t.Setenv("E2E_SHARED_RESOURCE_GROUP", "true") t.Setenv("E2E_RUN_ID", "123-afd-1") t.Setenv("ENABLE_AZURE_FRONT_DOOR", "true") + t.Setenv("ENABLE_AFD_PRIVATE_LINK_AUTO_APPROVAL", "true") t.Setenv("E2E_TEST_PRINCIPAL_ID", "44444444-4444-4444-4444-444444444444") log := installAFDCommandStubs(t) output, err := runAFDScript(t, "./install-afd.sh") @@ -75,11 +75,11 @@ func TestSharedAFDInstallation(t *testing.T) { {"peered", "./aks-peered-vnet.sh", "peered-vnet", "false"}, {"dynamic", "./aks-dynamic-ip-allocation.sh", "dynamic-ip-allocation", "false"}, {"unsupported", "./aks-no-networking.sh", "unsupported", "false"}, + {"performance", "./perf-test.sh", "perf-test", "false"}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { afdTestEnvironment(t) - t.Setenv("E2E_SHARED_RESOURCE_GROUP", "true") t.Setenv("E2E_RUN_ID", "123-"+tt.network+"-1") t.Setenv("ENABLE_TRAFFIC_MANAGER", tt.atm) t.Setenv("AZURE_NETWORK_SETTING", tt.network) @@ -87,6 +87,8 @@ func TestSharedAFDInstallation(t *testing.T) { t.Setenv("NODE_COUNT", "2") t.Setenv("MEMBER_1_LOCATION", "eastus2") t.Setenv("MEMBER_2_LOCATION", "westus") + t.Setenv("MEMBER_LOCATION_1", "eastus2") + t.Setenv("MEMBER_LOCATION_2", "westus") t.Setenv("MEMBER_CLUSTER_1_AKS_IDENTITY_ID", "/identity/member1-control") t.Setenv("MEMBER_CLUSTER_1_AKS_KUBELET_IDENTITY_ID", "/identity/member1-kubelet") t.Setenv("MEMBER_CLUSTER_2_AKS_IDENTITY_ID", "/identity/member2-control") @@ -106,12 +108,16 @@ func TestSharedAFDInstallation(t *testing.T) { hash := sha256.Sum256([]byte("test-subscription/test-rg/123-" + tt.network + "-1")) prefix := fmt.Sprintf("fne%x", hash[:8]) calls := readAFDFile(t, filepath.Join(dir, "calls")) - for _, name := range []string{prefix + "-member1", prefix + "-member2"} { + clusterNames := []string{prefix + "-member1", prefix + "-member2"} + if tt.network == "perf-test" { + clusterNames = append(clusterNames, prefix+"-member3", prefix+"-member4") + } + for _, name := range clusterNames { if !strings.Contains(calls, "--name "+name) { t.Errorf("missing physical cluster %s in %s", name, calls) } } - if strings.Count(calls, "fleet-e2e-run=123-"+tt.network+"-1") < 2 { + if strings.Count(calls, "fleet-e2e-run=123-"+tt.network+"-1") < len(clusterNames) { t.Fatalf("cluster ownership tags missing: %s", calls) } if tt.network != "unsupported" { @@ -139,12 +145,12 @@ func TestSharedAFDInstallation(t *testing.T) { }{{"clean", false, false}, {"resource collision", true, false}, {"existing kubeconfig", false, true}} { t.Run(tc.name, func(t *testing.T) { afdTestEnvironment(t) - t.Setenv("E2E_SHARED_RESOURCE_GROUP", "true") t.Setenv("E2E_RUN_ID", "123-atm-1") t.Setenv("AZURE_RESOURCE_GROUP", "fleet-networking-e2e") dir := t.TempDir() t.Setenv("KUBECONFIG", filepath.Join(dir, "kubeconfig")) t.Setenv("TEST_CALLS", filepath.Join(dir, "calls")) + t.Setenv("GITHUB_OUTPUT", filepath.Join(dir, "github-output")) if tc.existingConfig { if err := os.WriteFile(filepath.Join(dir, "kubeconfig"), []byte("existing"), 0o600); err != nil { t.Fatal(err) @@ -183,6 +189,14 @@ func TestSharedAFDInstallation(t *testing.T) { if !tc.conflict && !tc.existingConfig && (!strings.Contains(calls, "acr create") || !strings.Contains(output, "##vso[task.setvariable variable=e2eResourcesStarted]true")) { t.Fatalf("successful preflight did not enable cleanup before resource creation: %s, %s", calls, output) } + marker, markerErr := os.ReadFile(filepath.Join(dir, "github-output")) + if tc.conflict || tc.existingConfig { + if !os.IsNotExist(markerErr) { + t.Fatalf("failed preflight enabled GitHub cleanup: %q, %v", marker, markerErr) + } + } else if markerErr != nil || string(marker) != "resources_started=true\n" { + t.Fatalf("successful preflight did not enable GitHub cleanup: %q, %v", marker, markerErr) + } }) } } @@ -231,7 +245,6 @@ func TestSharedGroupCleanupOwnership(t *testing.T) { {"different test principal", false, false, false, true, false}, {"no profiles yet", false, false, false, false, true}} { t.Run(tc.name, func(t *testing.T) { afdTestEnvironment(t) - t.Setenv("E2E_SHARED_RESOURCE_GROUP", "true") t.Setenv("E2E_RUN_ID", "123-afd-1") t.Setenv("AZURE_SUBSCRIPTION_ID", "test-subscription") t.Setenv("AZURE_RESOURCE_GROUP", "fleet-networking-e2e") @@ -275,12 +288,16 @@ func TestSharedGroupCleanupOwnership(t *testing.T) { "identityProfile": map[string]interface{}{"kubeletidentity": map[string]string{"objectId": "hub-kubelet"}}}, {"id": vnet1, "name": prefix + "-member-1-vnet", "type": "Microsoft.Network/virtualNetworks", "tags": tags}, {"id": vnet2, "name": prefix + "-member-2-vnet", "type": "Microsoft.Network/virtualNetworks", "tags": tags}, + {"id": group + "/providers/Microsoft.ContainerService/managedClusters/" + prefix + "-member3", + "name": prefix + "-member3", "type": "Microsoft.ContainerService/managedClusters", "tags": tags}, + {"id": group + "/providers/Microsoft.ContainerService/managedClusters/" + prefix + "-member4", + "name": prefix + "-member4", "type": "Microsoft.ContainerService/managedClusters", "tags": tags}, {"id": profileID, "name": profileName, "type": "Microsoft.Cdn/profiles", "tags": profileTags}, {"id": trafficProfileID, "name": "fleet-55555555-5555-5555-5555-555555555555", "type": "Microsoft.Network/trafficManagerProfiles", "tags": map[string]string{"networking.fleet.azure.com.trafficManagerProfile": prefix + "-fghij/hello-world-service"}}, } if tc.noProfiles { - items = items[:3] + items = items[:5] } peerings := []map[string]interface{}{ {"id": vnet1 + "/virtualNetworkPeerings/to-two", "name": "to-two", "remoteVirtualNetwork": map[string]string{"id": vnet2}}, @@ -367,6 +384,7 @@ func TestSharedGroupCleanupOwnership(t *testing.T) { return } wants := []string{"aks delete", "aks wait", "kubectl --context hub-admin -n fleet-system scale", + "--name " + prefix + "-member3", "--name " + prefix + "-member4", "role assignment delete --ids " + group + "/providers/Microsoft.Authorization/roleAssignments/aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa", "role assignment delete --ids " + nodeID + "/providers/Microsoft.Authorization/roleAssignments/bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb", "role assignment delete --ids " + nodeID + "/providers/Microsoft.Authorization/roleAssignments/cccccccc-cccc-cccc-cccc-cccccccccccc", @@ -394,7 +412,6 @@ func TestSharedGroupCleanupOwnership(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { afdTestEnvironment(t) - t.Setenv("E2E_SHARED_RESOURCE_GROUP", "true") t.Setenv("E2E_RUN_ID", "123-atm-1") t.Setenv("AZURE_SUBSCRIPTION_ID", "test-subscription") t.Setenv("AZURE_RESOURCE_GROUP", "fleet-networking-e2e") @@ -460,28 +477,3 @@ func TestSharedGroupCleanupOwnership(t *testing.T) { }) } } - -func TestLegacyTopologyKeepsClusterNames(t *testing.T) { - afdTestEnvironment(t) - t.Setenv("RESOURCE_GROUP", "test-rg") - t.Setenv("NODE_COUNT", "2") - t.Setenv("MEMBER_1_LOCATION", "eastus2") - t.Setenv("MEMBER_2_LOCATION", "eastus2") - dir := t.TempDir() - t.Setenv("TEST_CALLS", filepath.Join(dir, "calls")) - writeAFDCommand(t, filepath.Join(dir, "az"), "#!/bin/bash\nprintf '%s\\n' \"$*\" >> \"$TEST_CALLS\"\n") - t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH")) - output, err := runAFDScript(t, "./aks-shared-vnet.sh") - if err != nil { - t.Fatalf("legacy topology: %s (%v)", output, err) - } - calls := readAFDFile(t, filepath.Join(dir, "calls")) - for _, name := range []string{"--name fleet", "--name member-1", "--name member-2"} { - if !strings.Contains(calls, name) { - t.Errorf("missing legacy name %s in %s", name, calls) - } - } - if strings.Contains(calls, "fleet-e2e-run=") { - t.Fatalf("legacy topology unexpectedly used shared resource tags: %s", calls) - } -} From d5cde27886bdccceff74dcca325a0c2e193a167d Mon Sep 17 00:00:00 2001 From: Wei Weng Date: Tue, 24 Nov 2026 19:25:23 +0000 Subject: [PATCH 04/16] docs: record shared-only E2E delivery Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../breadcrumbs/2026-11-24-1842-shared-e2e-resource-group.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/.copilot/breadcrumbs/2026-11-24-1842-shared-e2e-resource-group.md b/.github/.copilot/breadcrumbs/2026-11-24-1842-shared-e2e-resource-group.md index 443c3c92..35048d66 100644 --- a/.github/.copilot/breadcrumbs/2026-11-24-1842-shared-e2e-resource-group.md +++ b/.github/.copilot/breadcrumbs/2026-11-24-1842-shared-e2e-resource-group.md @@ -35,7 +35,7 @@ The shared-group-only revision: 2. [x] Update Azure DevOps and GitHub workflow callers and preserve safe cleanup eligibility. 3. [x] Keep performance topology working with run-specific resources and ownership-verified cleanup. 4. [x] Update tests and documentation and validate offline. -5. [ ] Push the shared-group-only revision. +5. [x] Push the shared-group-only revision. The Azure DevOps pipeline supplies a unique run ID per scenario and attempt; scripts derive physical Azure names and retain the established logical Kubernetes contexts. Setup requires a new run-specific kubeconfig, verifies the group and rejects name or ownership collisions before enabling cleanup. From 6a84fe9f19ab710bb4a3912dce90feef3e6de34f Mon Sep 17 00:00:00 2001 From: Wei Weng Date: Tue, 24 Nov 2026 19:50:55 +0000 Subject: [PATCH 05/16] test: focus E2E workload helper tests Keep separate tests for appImage and UniqueTestNamespace, including their missing-configuration behavior. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- test/e2e/framework/workload_manager_test.go | 76 ++++++++++----------- 1 file changed, 36 insertions(+), 40 deletions(-) diff --git a/test/e2e/framework/workload_manager_test.go b/test/e2e/framework/workload_manager_test.go index ed3497d2..1d5b1dfe 100644 --- a/test/e2e/framework/workload_manager_test.go +++ b/test/e2e/framework/workload_manager_test.go @@ -9,49 +9,45 @@ import ( "strings" "testing" - corev1 "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/util/validation" ) -func TestSharedRunWorkloadNames(t *testing.T) { - t.Setenv("E2E_RESOURCE_PREFIX", "fne0123456789abcdef") - t.Setenv("REGISTRY", "fne0123456789abcdefacr.azurecr.io") - if got := appImage(); got != "fne0123456789abcdefacr.azurecr.io/app" { - t.Fatalf("app image uses the wrong run registry: %s", got) - } - namespace := UniqueTestNamespace() - if !strings.HasPrefix(namespace, "fne0123456789abcdef-") { - t.Fatalf("namespace does not identify this run: %s", namespace) - } - workload := WorkloadManager{ - namespace: namespace, - service: corev1.Service{ObjectMeta: metav1.ObjectMeta{Name: "hello-world-service"}}, - } - label := workload.BuildServiceDNSLabelName(&Cluster{name: "member-1"}) - if problems := validation.IsDNS1123Label(label); len(problems) != 0 { - t.Fatalf("shared run DNS label %q is invalid: %v", label, problems) - } - +func TestAppImage(t *testing.T) { + t.Run("run registry", func(t *testing.T) { + t.Setenv("REGISTRY", "fne0123456789abcdefacr.azurecr.io") + if got := appImage(); got != "fne0123456789abcdefacr.azurecr.io/app" { + t.Fatalf("app image uses the wrong run registry: %s", got) + } + }) + t.Run("missing registry", func(t *testing.T) { + t.Setenv("REGISTRY", "") + defer func() { + if recover() == nil { + t.Fatal("missing registry must fail explicitly") + } + }() + appImage() + }) } -func TestMissingSharedRunConfiguration(t *testing.T) { - for _, tt := range []struct { - name string - key string - call func() - }{ - {"registry", "REGISTRY", func() { appImage() }}, - {"run prefix", "E2E_RESOURCE_PREFIX", func() { UniqueTestNamespace() }}, - } { - t.Run(tt.name, func(t *testing.T) { - t.Setenv(tt.key, "") - defer func() { - if recover() == nil { - t.Fatal("missing run configuration must fail explicitly") - } - }() - tt.call() - }) - } +func TestUniqueTestNamespace(t *testing.T) { + t.Run("run prefix", func(t *testing.T) { + t.Setenv("E2E_RESOURCE_PREFIX", "fne0123456789abcdef") + namespace := UniqueTestNamespace() + if !strings.HasPrefix(namespace, "fne0123456789abcdef-") { + t.Fatalf("namespace does not identify this run: %s", namespace) + } + if problems := validation.IsDNS1123Label(namespace); len(problems) != 0 { + t.Fatalf("namespace %q is invalid: %v", namespace, problems) + } + }) + t.Run("missing prefix", func(t *testing.T) { + t.Setenv("E2E_RESOURCE_PREFIX", "") + defer func() { + if recover() == nil { + t.Fatal("missing run prefix must fail explicitly") + } + }() + UniqueTestNamespace() + }) } From 6148b07bd00b9b169b2252bf39202dd93be62918 Mon Sep 17 00:00:00 2001 From: Wei Weng Date: Tue, 24 Nov 2026 19:57:13 +0000 Subject: [PATCH 06/16] docs: clarify configurable E2E resource group Describe the required group tags without requiring a specific resource group name. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- ...26-11-24-1842-shared-e2e-resource-group.md | 3 ++ test/README.md | 44 +++++++------------ 2 files changed, 19 insertions(+), 28 deletions(-) diff --git a/.github/.copilot/breadcrumbs/2026-11-24-1842-shared-e2e-resource-group.md b/.github/.copilot/breadcrumbs/2026-11-24-1842-shared-e2e-resource-group.md index 35048d66..0ba788fc 100644 --- a/.github/.copilot/breadcrumbs/2026-11-24-1842-shared-e2e-resource-group.md +++ b/.github/.copilot/breadcrumbs/2026-11-24-1842-shared-e2e-resource-group.md @@ -43,6 +43,8 @@ Cleanup verifies the group, run tags, resource IDs, AKS node-group ownership, ro Shared AFD requires the test principal object ID, grants it Network Contributor only on verified member node groups, and records the principal for cleanup. CI obtains the object ID from its Azure CLI access token without logging or storing the token. The pipeline service connection remains unchanged by default and can be selected explicitly after its grants are deployed. +The user requested a generic local E2E guide and chose to retain both existing resource-group tag checks. The guide now uses a caller-selected group name and explains the required tag values; setup and cleanup behavior is unchanged. + Changed files: `.pipeline/e2e-tests.yaml`, `test/README.md`, the `test/scripts` setup, topology, configuration, AFD and cleanup scripts and tests, plus E2E framework workload naming and Traffic Manager public-IP tagging. ## Validation and risks @@ -51,4 +53,5 @@ Changed files: `.pipeline/e2e-tests.yaml`, `test/README.md`, the `test/scripts` - `GOTOOLCHAIN=go1.26.10 go vet ./test/scripts ./test/e2e/framework` passed. - `GOTOOLCHAIN=go1.26.10 go test -tags=e2e -run '^$' ./test/e2e` and `go vet -tags=e2e ./test/e2e` passed without executing live E2E. - Performance packages compiled and passed `go vet` without running their suites. Installed Azure CLI option checks, Bash syntax, both workflow YAML parsing and `git diff --check` passed. +- The generic guide's Markdown fences are balanced and its local links resolve. - No live Azure provisioning, permission, test or cleanup operation was run. The proposed grants and service connection have not been enabled. Cleanup can fail closed and leave resources; there is no stale-run sweeper. Contributor on the shared RG is not a security boundary between runs. diff --git a/test/README.md b/test/README.md index b1953bee..c4738205 100644 --- a/test/README.md +++ b/test/README.md @@ -30,46 +30,34 @@ assigns Azure roles. Use a test subscription rather than a production subscripti ### Shared resource group -The E2E workflows use the pre-created `fleet-networking-e2e` resource group. An administrator -must deploy the scoped permissions and authorize the intended service connection; Azure DevOps -can select it with the `serviceConnection` parameter. CI obtains the service principal object ID -from its Azure CLI access token for automated AFD Private Link approval. - -For a local run, set the following in addition to the scenario variables: +Use a pre-created test resource group of your choice. Setup and cleanup require these group tags: +`managedBy=aks-rp/ci-resources` and `workload=fleet-networking-e2e`; the latter is a tag value, +not the required group name. The identity must be able to manage test resources and assign the +necessary roles, including on AKS node resource groups. +For local runs, set the following in addition to the scenario variables: ```bash -export AZURE_RESOURCE_GROUP=fleet-networking-e2e +export AZURE_RESOURCE_GROUP= export E2E_RUN_ID= export KUBECONFIG= # Required only when AFD automatic approval is enabled: export E2E_TEST_PRINCIPAL_ID= ``` -For local AFD auto-approval, sign in as that service principal. An interactive user can instead -disable auto-approval and arrange manual approval by an authorized PLS owner. - Use a unique `E2E_RUN_ID` for every concurrent run and retry; never reuse an ID while a prior run or its cleanup is active. Use at most 63 lowercase letters, digits and hyphens, beginning with a -letter or digit. CI derives it from the build ID, scenario and job attempt. -Setup checks the shared group's expected management tags and refuses existing run resources. -Physical Azure cluster names, VNets, identities and the registry are run-specific, while the -isolated kubeconfig retains the `hub-admin` and `member-*-admin` context names. -AFD requires the default Gateway controller namespace and deployment name. - -`make e2e-cleanup` **never deletes the resource group**. It verifies run tags, -resource IDs, controller profile ownership and AKS-managed node groups before removing the -run's resources and relevant role assignments. If ownership cannot be established, the hub is -unavailable when controller cleanup is needed, or Azure cleanup fails, the command stops with an -error and resources may remain. Keep the run ID and inspect leftovers before retrying; do not -delete the shared group. For AFD auto-approval, supply the same `E2E_TEST_PRINCIPAL_ID` during -cleanup. There is no automatic stale-run sweeper. +letter or digit. Setup refuses existing run resources and requires a new kubeconfig path. +For local AFD auto-approval, sign in as the specified service principal; otherwise disable +auto-approval and arrange manual approval by an authorized PLS owner. -Run-specific names and cleanup checks prevent accidental cross-run deletion; they are not an Azure -security boundary. An identity with Contributor on the shared group can modify other runs' resources -and delete the group. Node groups still need their own permissions outside the shared group. +`make e2e-cleanup` removes only verified run-owned resources and **never deletes the resource +group**. Keep the same run ID, kubeconfig and, for AFD auto-approval, principal ID for cleanup. +If cleanup fails, inspect remaining resources before retrying; there is no automatic stale-run +sweeper. -These shared-group permissions and cleanup paths require a separately approved live Azure run -before production use. Offline tests do not establish Azure provisioning or deletion behavior. +Run-specific names and cleanup checks prevent accidental cross-run deletion; they are not an Azure +security boundary: an identity with Contributor on the group can modify other runs' resources and +delete the group. ## Choose an E2E scenario From 44e32395a55b006c8891ed8a0d295c85f4a521f1 Mon Sep 17 00:00:00 2001 From: Wei Weng Date: Tue, 24 Nov 2026 20:00:09 +0000 Subject: [PATCH 07/16] test: remove shared E2E script tests Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- ...26-11-24-1842-shared-e2e-resource-group.md | 4 +- test/scripts/azure_principal_id_test.go | 49 -- test/scripts/shared_group_test.go | 479 ------------------ 3 files changed, 3 insertions(+), 529 deletions(-) delete mode 100644 test/scripts/azure_principal_id_test.go delete mode 100644 test/scripts/shared_group_test.go diff --git a/.github/.copilot/breadcrumbs/2026-11-24-1842-shared-e2e-resource-group.md b/.github/.copilot/breadcrumbs/2026-11-24-1842-shared-e2e-resource-group.md index 0ba788fc..35613c9e 100644 --- a/.github/.copilot/breadcrumbs/2026-11-24-1842-shared-e2e-resource-group.md +++ b/.github/.copilot/breadcrumbs/2026-11-24-1842-shared-e2e-resource-group.md @@ -45,11 +45,13 @@ Shared AFD requires the test principal object ID, grants it Network Contributor The user requested a generic local E2E guide and chose to retain both existing resource-group tag checks. The guide now uses a caller-selected group name and explains the required tag values; setup and cleanup behavior is unchanged. +The user subsequently requested removal of `shared_group_test.go` and `azure_principal_id_test.go`. Dedicated mocked cleanup and principal-token regression coverage is no longer retained. + Changed files: `.pipeline/e2e-tests.yaml`, `test/README.md`, the `test/scripts` setup, topology, configuration, AFD and cleanup scripts and tests, plus E2E framework workload naming and Traffic Manager public-IP tagging. ## Validation and risks -- `GOTOOLCHAIN=go1.26.10 go test -count=1 ./test/scripts ./test/e2e/framework` passed, including mocked concurrent-run, collision, profile, peering, role, cleanup, token parsing and performance topology cases. +- `GOTOOLCHAIN=go1.26.10 go test -count=1 ./test/scripts` passed after the requested test removal. Earlier runs also covered the now-removed mocked cleanup, token parsing and performance topology cases. - `GOTOOLCHAIN=go1.26.10 go vet ./test/scripts ./test/e2e/framework` passed. - `GOTOOLCHAIN=go1.26.10 go test -tags=e2e -run '^$' ./test/e2e` and `go vet -tags=e2e ./test/e2e` passed without executing live E2E. - Performance packages compiled and passed `go vet` without running their suites. Installed Azure CLI option checks, Bash syntax, both workflow YAML parsing and `git diff --check` passed. diff --git a/test/scripts/azure_principal_id_test.go b/test/scripts/azure_principal_id_test.go deleted file mode 100644 index 0c03ee73..00000000 --- a/test/scripts/azure_principal_id_test.go +++ /dev/null @@ -1,49 +0,0 @@ -/* -Copyright (c) Microsoft Corporation. -Licensed under the MIT license. -*/ - -package scripts - -import ( - "encoding/base64" - "os" - "path/filepath" - "strings" - "testing" -) - -func TestAzurePrincipalID(t *testing.T) { - const id = "01234567-89ab-cdef-0123-456789abcdef" - payload := base64.RawURLEncoding.EncodeToString([]byte(`{"oid":"` + id + `"}`)) - for _, tt := range []struct { - name, token string - fails bool - }{ - {"valid", "header." + payload + ".signature", false}, - {"malformed", "not-a-token", true}, - {"missing object ID", "header.e30.signature", true}, - } { - t.Run(tt.name, func(t *testing.T) { - afdTestEnvironment(t) - dir := t.TempDir() - writeAFDCommand(t, filepath.Join(dir, "az"), `#!/bin/bash -set -euo pipefail -[[ "$*" == "account get-access-token --subscription test-subscription --resource https://management.azure.com/ --query accessToken -o tsv" ]] -printf '%s\n' "$TEST_TOKEN" -`) - t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH")) - t.Setenv("TEST_TOKEN", tt.token) - output, err := runAFDScript(t, "-x", "./azure-principal-id.sh") - if (err != nil) != tt.fails || strings.Contains(output, tt.token) { - t.Fatalf("principal extraction: %s (%v)", output, err) - } - if !tt.fails && !strings.Contains(output, id) { - t.Fatalf("principal ID missing: %s", output) - } - if tt.fails && !strings.Contains(output, "error:") { - t.Fatalf("invalid token was not reported: %s", output) - } - }) - } -} diff --git a/test/scripts/shared_group_test.go b/test/scripts/shared_group_test.go deleted file mode 100644 index c5483d80..00000000 --- a/test/scripts/shared_group_test.go +++ /dev/null @@ -1,479 +0,0 @@ -/* -Copyright (c) Microsoft Corporation. -Licensed under the MIT license. -*/ - -package scripts - -import ( - "crypto/sha256" - "encoding/json" - "fmt" - "os" - "path/filepath" - "strconv" - "strings" - "testing" -) - -func TestSharedGroupConfiguration(t *testing.T) { - afdTestEnvironment(t) - run := func(id string) (string, error) { - t.Helper() - t.Setenv("E2E_RUN_ID", id) - t.Setenv("AZURE_SUBSCRIPTION_ID", "test-subscription") - t.Setenv("AZURE_RESOURCE_GROUP", "fleet-networking-e2e") - t.Setenv("AZURE_NETWORK_SETTING", "shared-vnet") - return runAFDScript(t, "-ec", `source ./e2e-config.sh -printf '%s|%s|%s|%s|%s\n' "$E2E_RESOURCE_PREFIX" "$HUB_AZURE_CLUSTER" "$MEMBER_1_AZURE_CLUSTER" "$MEMBER_2_AZURE_CLUSTER" "$REGISTRY_NAME"`) - } - first, err := run("123-atm-1") - if err != nil { - t.Fatal(err) - } - repeated, err := run("123-atm-1") - if err != nil || repeated != first { - t.Fatalf("run identity must be deterministic: %q, %q, %v", first, repeated, err) - } - other, err := run("123-afd-1") - if err != nil || other == first { - t.Fatalf("concurrent scenarios must not share names: %q, %q, %v", first, other, err) - } - for _, invalid := range []string{"", "../other", "ABC", "trailing space"} { - output, err := run(invalid) - if err == nil || !strings.Contains(output, "E2E_RUN_ID") { - t.Fatalf("invalid run ID %q was accepted: %s (%v)", invalid, output, err) - } - } - t.Setenv("ENABLE_AZURE_FRONT_DOOR", "true") - t.Setenv("ENABLE_AFD_PRIVATE_LINK_AUTO_APPROVAL", "true") - t.Setenv("E2E_TEST_PRINCIPAL_ID", "") - output, err := run("123-afd-1") - if err == nil || !strings.Contains(output, "E2E_TEST_PRINCIPAL_ID") { - t.Fatalf("shared AFD must reject missing principal ID: %s (%v)", output, err) - } -} - -func TestSharedAFDInstallation(t *testing.T) { - afdTestEnvironment(t) - t.Setenv("E2E_RUN_ID", "123-afd-1") - t.Setenv("ENABLE_AZURE_FRONT_DOOR", "true") - t.Setenv("ENABLE_AFD_PRIVATE_LINK_AUTO_APPROVAL", "true") - t.Setenv("E2E_TEST_PRINCIPAL_ID", "44444444-4444-4444-4444-444444444444") - log := installAFDCommandStubs(t) - output, err := runAFDScript(t, "./install-afd.sh") - if err != nil { - t.Fatalf("shared AFD installation: %s (%v)", output, err) - } - - testTopologyNames := func(t *testing.T) { - tests := []struct { - name, script, network, atm string - }{ - {"traffic manager", "./aks-shared-vnet.sh", "shared-vnet", "true"}, - {"front door", "./aks-shared-vnet.sh", "shared-vnet", "false"}, - {"peered", "./aks-peered-vnet.sh", "peered-vnet", "false"}, - {"dynamic", "./aks-dynamic-ip-allocation.sh", "dynamic-ip-allocation", "false"}, - {"unsupported", "./aks-no-networking.sh", "unsupported", "false"}, - {"performance", "./perf-test.sh", "perf-test", "false"}, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - afdTestEnvironment(t) - t.Setenv("E2E_RUN_ID", "123-"+tt.network+"-1") - t.Setenv("ENABLE_TRAFFIC_MANAGER", tt.atm) - t.Setenv("AZURE_NETWORK_SETTING", tt.network) - t.Setenv("RESOURCE_GROUP", "test-rg") - t.Setenv("NODE_COUNT", "2") - t.Setenv("MEMBER_1_LOCATION", "eastus2") - t.Setenv("MEMBER_2_LOCATION", "westus") - t.Setenv("MEMBER_LOCATION_1", "eastus2") - t.Setenv("MEMBER_LOCATION_2", "westus") - t.Setenv("MEMBER_CLUSTER_1_AKS_IDENTITY_ID", "/identity/member1-control") - t.Setenv("MEMBER_CLUSTER_1_AKS_KUBELET_IDENTITY_ID", "/identity/member1-kubelet") - t.Setenv("MEMBER_CLUSTER_2_AKS_IDENTITY_ID", "/identity/member2-control") - t.Setenv("MEMBER_CLUSTER_2_AKS_KUBELET_IDENTITY_ID", "/identity/member2-kubelet") - dir := t.TempDir() - t.Setenv("TEST_CALLS", filepath.Join(dir, "calls")) - t.Setenv("KUBECONFIG", filepath.Join(dir, "kubeconfig")) - writeAFDCommand(t, filepath.Join(dir, "az"), `#!/bin/bash - printf '%s\n' "$*" >> "$TEST_CALLS" - if [[ "$*" == "network vnet show "* ]]; then echo "/subscriptions/test-subscription/resourceGroups/test-rg/providers/Microsoft.Network/virtualNetworks/test"; fi - `) - t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH")) - output, err := runAFDScript(t, tt.script) - if err != nil { - t.Fatalf("topology: %s (%v)", output, err) - } - hash := sha256.Sum256([]byte("test-subscription/test-rg/123-" + tt.network + "-1")) - prefix := fmt.Sprintf("fne%x", hash[:8]) - calls := readAFDFile(t, filepath.Join(dir, "calls")) - clusterNames := []string{prefix + "-member1", prefix + "-member2"} - if tt.network == "perf-test" { - clusterNames = append(clusterNames, prefix+"-member3", prefix+"-member4") - } - for _, name := range clusterNames { - if !strings.Contains(calls, "--name "+name) { - t.Errorf("missing physical cluster %s in %s", name, calls) - } - } - if strings.Count(calls, "fleet-e2e-run=123-"+tt.network+"-1") < len(clusterNames) { - t.Fatalf("cluster ownership tags missing: %s", calls) - } - if tt.network != "unsupported" { - created := 0 - for _, call := range strings.Split(calls, "\n") { - if strings.HasPrefix(call, "network vnet create ") { - created++ - if !strings.Contains(call, "--name "+prefix+"-") { - t.Fatalf("VNet name is not run-specific: %s", call) - } - } - } - if created == 0 { - t.Fatalf("no VNet created: %s", calls) - } - } - }) - } - } - - testBootstrapPreflight := func(t *testing.T) { - for _, tc := range []struct { - name string - conflict, existingConfig bool - }{{"clean", false, false}, {"resource collision", true, false}, {"existing kubeconfig", false, true}} { - t.Run(tc.name, func(t *testing.T) { - afdTestEnvironment(t) - t.Setenv("E2E_RUN_ID", "123-atm-1") - t.Setenv("AZURE_RESOURCE_GROUP", "fleet-networking-e2e") - dir := t.TempDir() - t.Setenv("KUBECONFIG", filepath.Join(dir, "kubeconfig")) - t.Setenv("TEST_CALLS", filepath.Join(dir, "calls")) - t.Setenv("GITHUB_OUTPUT", filepath.Join(dir, "github-output")) - if tc.existingConfig { - if err := os.WriteFile(filepath.Join(dir, "kubeconfig"), []byte("existing"), 0o600); err != nil { - t.Fatal(err) - } - } - if tc.conflict { - hash := sha256.Sum256([]byte("test-subscription/fleet-networking-e2e/123-atm-1")) - t.Setenv("TEST_RESOURCE_NAME", fmt.Sprintf("fne%x-hub", hash[:8])) - } else { - t.Setenv("TEST_RESOURCE_NAME", "") - } - writeAFDCommand(t, filepath.Join(dir, "yq"), "#!/bin/bash\nexit 0\n") - writeAFDCommand(t, filepath.Join(dir, "az"), `#!/bin/bash - set -euo pipefail - printf '%s\n' "$*" >> "$TEST_CALLS" - case "$1 $2" in - "account set") ;; - "group show") printf '%s\n' '{"id":"/subscriptions/test-subscription/resourceGroups/fleet-networking-e2e","tags":{"managedBy":"aks-rp/ci-resources","workload":"fleet-networking-e2e"}}' ;; - "resource list") if [[ -n "$TEST_RESOURCE_NAME" ]]; then jq -cn --arg name "$TEST_RESOURCE_NAME" '[{name:$name,tags:{}}]'; else echo '[]'; fi ;; - "acr create") echo "injected create failure" >&2; exit 23 ;; - *) echo "unexpected Azure operation: $*" >&2; exit 1 ;; - esac - `) - t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH")) - output, err := runAFDScript(t, "./bootstrap.sh") - if err == nil { - t.Fatal("expected a preflight conflict or injected create failure") - } - calls := readAFDFile(t, filepath.Join(dir, "calls")) - if strings.Contains(calls, "group create") || strings.Contains(calls, "group delete") { - t.Fatalf("shared setup touched the resource group: %s", calls) - } - if (tc.conflict || tc.existingConfig) && (strings.Contains(calls, "acr create") || strings.Contains(output, "##vso[task.setvariable variable=e2eResourcesStarted]true")) { - t.Fatalf("collision was not rejected before cleanup became eligible: %s, %s", calls, output) - } - if !tc.conflict && !tc.existingConfig && (!strings.Contains(calls, "acr create") || !strings.Contains(output, "##vso[task.setvariable variable=e2eResourcesStarted]true")) { - t.Fatalf("successful preflight did not enable cleanup before resource creation: %s, %s", calls, output) - } - marker, markerErr := os.ReadFile(filepath.Join(dir, "github-output")) - if tc.conflict || tc.existingConfig { - if !os.IsNotExist(markerErr) { - t.Fatalf("failed preflight enabled GitHub cleanup: %q, %v", marker, markerErr) - } - } else if markerErr != nil || string(marker) != "resources_started=true\n" { - t.Fatalf("successful preflight did not enable GitHub cleanup: %q, %v", marker, markerErr) - } - }) - } - } - t.Run("topology names", testTopologyNames) - t.Run("bootstrap preflight", testBootstrapPreflight) - hash := sha256.Sum256([]byte("test-subscription/test-rg/123-afd-1")) - prefix := fmt.Sprintf("fne%x", hash[:8]) - calls := readAFDFile(t, log) - for _, want := range []string{ - "--name " + prefix + "-hub", - "--name " + prefix + "-member1", - "--name " + prefix + "-member2", - "--kube-context member-1-admin", - "--kube-context member-2-admin", - "--assignee-object-id 44444444-4444-4444-4444-444444444444", - "--scope /subscriptions/test-subscription/resourceGroups/MC_" + prefix + "-member1", - "--scope /subscriptions/test-subscription/resourceGroups/MC_" + prefix + "-member2", - } { - if !strings.Contains(calls, want) { - t.Errorf("missing %q in calls:\n%s", want, calls) - } - } - if strings.Count(calls, "--role Network Contributor") != 2 { - t.Fatalf("expected one test-caller Network Contributor grant per member: %s", calls) - } -} - -func TestSharedGroupCleanupOwnership(t *testing.T) { - tests := []struct { - name string - conflict bool - profile bool - wantDeletes bool - }{ - {"owned resources", false, false, true}, - {"foreign resource with colliding name", true, false, false}, - {"controller profile still present", false, true, false}, - } - - testControllerAndPeerings := func(t *testing.T) { - for _, tc := range []struct { - name string - invalidOwner, foreignPeer, lateProfile, principalMismatch, noProfiles bool - }{{"valid", false, false, false, false, false}, {"wrong hub UID", true, false, false, false, false}, - {"foreign peering", false, true, false, false, false}, {"profile changed after stop", false, false, true, false, false}, - {"different test principal", false, false, false, true, false}, {"no profiles yet", false, false, false, false, true}} { - t.Run(tc.name, func(t *testing.T) { - afdTestEnvironment(t) - t.Setenv("E2E_RUN_ID", "123-afd-1") - t.Setenv("AZURE_SUBSCRIPTION_ID", "test-subscription") - t.Setenv("AZURE_RESOURCE_GROUP", "fleet-networking-e2e") - t.Setenv("E2E_TEST_PRINCIPAL_ID", "44444444-4444-4444-4444-444444444444") - if tc.principalMismatch { - t.Setenv("E2E_TEST_PRINCIPAL_ID", "66666666-6666-6666-6666-666666666666") - } - dir := t.TempDir() - t.Setenv("KUBECONFIG", filepath.Join(dir, "kubeconfig")) - group := "/subscriptions/test-subscription/resourceGroups/fleet-networking-e2e" - hash := sha256.Sum256([]byte("test-subscription/fleet-networking-e2e/123-afd-1")) - prefix := fmt.Sprintf("fne%x", hash[:8]) - hub := prefix + "-hub" - hubID := group + "/providers/Microsoft.ContainerService/managedClusters/" + hub - nodeGroup := "MC_fleet_e2e_hub" - nodeID := "/subscriptions/test-subscription/resourceGroups/" + nodeGroup - vnet1 := group + "/providers/Microsoft.Network/virtualNetworks/" + prefix + "-member-1-vnet" - vnet2 := group + "/providers/Microsoft.Network/virtualNetworks/" + prefix + "-member-2-vnet" - tags := map[string]string{"source": "fleet-networking", "fleet-e2e-run": "123-afd-1", - "fleet-e2e-atm": "false", "fleet-e2e-afd": "true", "fleet-e2e-auto-approval": "true", - "fleet-e2e-test-principal": "44444444-4444-4444-4444-444444444444"} - uid := "11111111-1111-1111-1111-111111111111" - gatewayUID := "22222222-2222-2222-2222-222222222222" - gatewayHash := sha256.Sum256([]byte(fmt.Sprintf("%d:%s", len(gatewayUID), gatewayUID))) - profileName := fmt.Sprintf("fleet-afd-%x", gatewayHash[:16]) - profileID := group + "/providers/Microsoft.Cdn/profiles/" + profileName - trafficProfileID := group + "/providers/Microsoft.Network/trafficManagerProfiles/fleet-55555555-5555-5555-5555-555555555555" - profileTags := map[string]string{ - "networking.fleet.azure.com.controller": "networking.fleet.azure.com/afd", - "networking.fleet.azure.com.hub-uid": uid, - "networking.fleet.azure.com.gateway-namespace": prefix + "-abcde", - "networking.fleet.azure.com.gateway-name": "private-http", - "networking.fleet.azure.com.gateway-uid": gatewayUID, - } - if tc.invalidOwner { - profileTags["networking.fleet.azure.com.hub-uid"] = "33333333-3333-3333-3333-333333333333" - } - items := []map[string]interface{}{ - {"id": hubID, "name": hub, "type": "Microsoft.ContainerService/managedClusters", "tags": tags, - "nodeResourceGroup": nodeGroup, "identity": map[string]interface{}{"principalId": "hub-principal"}, - "identityProfile": map[string]interface{}{"kubeletidentity": map[string]string{"objectId": "hub-kubelet"}}}, - {"id": vnet1, "name": prefix + "-member-1-vnet", "type": "Microsoft.Network/virtualNetworks", "tags": tags}, - {"id": vnet2, "name": prefix + "-member-2-vnet", "type": "Microsoft.Network/virtualNetworks", "tags": tags}, - {"id": group + "/providers/Microsoft.ContainerService/managedClusters/" + prefix + "-member3", - "name": prefix + "-member3", "type": "Microsoft.ContainerService/managedClusters", "tags": tags}, - {"id": group + "/providers/Microsoft.ContainerService/managedClusters/" + prefix + "-member4", - "name": prefix + "-member4", "type": "Microsoft.ContainerService/managedClusters", "tags": tags}, - {"id": profileID, "name": profileName, "type": "Microsoft.Cdn/profiles", "tags": profileTags}, - {"id": trafficProfileID, "name": "fleet-55555555-5555-5555-5555-555555555555", "type": "Microsoft.Network/trafficManagerProfiles", - "tags": map[string]string{"networking.fleet.azure.com.trafficManagerProfile": prefix + "-fghij/hello-world-service"}}, - } - if tc.noProfiles { - items = items[:5] - } - peerings := []map[string]interface{}{ - {"id": vnet1 + "/virtualNetworkPeerings/to-two", "name": "to-two", "remoteVirtualNetwork": map[string]string{"id": vnet2}}, - {"id": vnet2 + "/virtualNetworkPeerings/to-one", "name": "to-one", "remoteVirtualNetwork": map[string]string{"id": vnet1}}, - } - if tc.foreignPeer { - peerings[0]["remoteVirtualNetwork"] = map[string]string{"id": group + "/providers/Microsoft.Network/virtualNetworks/foreign"} - } - assignments := []map[string]string{ - {"id": group + "/providers/Microsoft.Authorization/roleAssignments/aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa", "scope": group, "name": "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa", - "principalId": "hub-principal", "roleDefinitionId": "/providers/Microsoft.Authorization/roleDefinitions/de2b316d-7a2c-4143-b4cd-c148f6a355a1"}, - {"id": group + "/providers/Microsoft.Authorization/roleAssignments/foreign", "scope": group, - "principalId": "foreign-principal", "roleDefinitionId": "/providers/Microsoft.Authorization/roleDefinitions/de2b316d-7a2c-4143-b4cd-c148f6a355a1"}, - {"id": nodeID + "/providers/Microsoft.Authorization/roleAssignments/bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb", "scope": nodeID, "name": "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb", - "principalId": "hub-kubelet", "roleDefinitionId": "/providers/Microsoft.Authorization/roleDefinitions/acdd72a7-3385-48ef-bd42-f606fba81ae7"}, - {"id": nodeID + "/providers/Microsoft.Authorization/roleAssignments/cccccccc-cccc-cccc-cccc-cccccccccccc", "scope": nodeID, "name": "cccccccc-cccc-cccc-cccc-cccccccccccc", - "principalId": "44444444-4444-4444-4444-444444444444", "roleDefinitionId": "/providers/Microsoft.Authorization/roleDefinitions/4d97b98b-1d4f-4787-a291-c67834d212e7"}, - } - for name, value := range map[string]interface{}{"inventory": items, "peerings": peerings, "assignments": assignments} { - data, err := json.Marshal(value) - if err != nil { - t.Fatal(err) - } - if err := os.WriteFile(filepath.Join(dir, name), data, 0o600); err != nil { - t.Fatal(err) - } - } - t.Setenv("TEST_DIR", dir) - t.Setenv("TEST_UID", uid) - t.Setenv("TEST_HUB_ID", hubID) - t.Setenv("TEST_NODE_ID", nodeID) - t.Setenv("TEST_LATE_PROFILE", strconv.FormatBool(tc.lateProfile)) - writeAFDCommand(t, filepath.Join(dir, "az"), `#!/bin/bash - set -euo pipefail - printf 'az %s\n' "$*" >> "$TEST_DIR/calls" - option() { local key="$1"; shift; while (($#)); do if [[ "$1" == "$key" ]]; then printf '%s' "$2"; return; fi; shift; done; return 1; } - case "$1 $2 $3" in - "group show --subscription") - name="$(option --name "$@")" - if [[ "$name" == fleet-networking-e2e ]]; then - printf '%s\n' '{"id":"/subscriptions/test-subscription/resourceGroups/fleet-networking-e2e","tags":{"managedBy":"aks-rp/ci-resources","workload":"fleet-networking-e2e"}}' - else jq -cn --arg id "$TEST_NODE_ID" --arg owner "$TEST_HUB_ID" '{id:$id,managedBy:$owner}'; fi ;; - "group exists --subscription") echo true ;; - "group wait --subscription") ;; - "resource list --subscription") - count=0; if [[ -e "$TEST_DIR/listed" ]]; then count="$(cat "$TEST_DIR/listed")"; fi - count=$((count + 1)); echo "$count" > "$TEST_DIR/listed" - if ((count == 2)) && [[ "$TEST_LATE_PROFILE" == true ]]; then - jq 'map(if .type == "Microsoft.Cdn/profiles" then .tags.changed = "true" else . end)' "$TEST_DIR/inventory" - elif ((count <= 2)); then cat "$TEST_DIR/inventory"; else echo '[]'; fi ;; - "resource show --ids") jq --arg id "$4" '.[] | select(.id == $id)' "$TEST_DIR/inventory" ;; - "aks show --subscription") name="$(option --name "$@")"; jq --arg name "$name" '.[] | select(.name == $name)' "$TEST_DIR/inventory" ;; - "aks get-credentials --subscription"|"aks delete --subscription"|"aks wait --subscription"|"resource delete --ids") ;; - "network vnet peering") - if [[ "$4" == list ]]; then - name="$(option --vnet-name "$@")" - jq --arg name "$name" '[.[] | select(.id | contains("/virtualNetworks/" + $name + "/"))]' "$TEST_DIR/peerings" - elif [[ "$4" == delete ]]; then :; else exit 1; fi ;; - "role assignment list") cat "$TEST_DIR/assignments" ;; - "role assignment delete") ;; - *) echo "unexpected az command: $*" >&2; exit 1 ;; - esac - `) - writeAFDCommand(t, filepath.Join(dir, "kubectl"), `#!/bin/bash - set -euo pipefail - printf 'kubectl %s\n' "$*" >> "$TEST_DIR/calls" - case "$*" in - *"get namespace kube-system"*) printf '%s' "$TEST_UID" ;; - *"get deployment"*) echo deployment/hub-net-controller-manager ;; - *"scale"*|*"rollout status"*) ;; - *) exit 1 ;; - esac - `) - t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH")) - output, err := runAFDScript(t, "./cleanup.sh") - if (err != nil) != (tc.invalidOwner || tc.foreignPeer || tc.lateProfile || tc.principalMismatch) { - t.Fatalf("cleanup: %s (%v)", output, err) - } - calls := readAFDFile(t, filepath.Join(dir, "calls")) - if tc.invalidOwner || tc.foreignPeer || tc.lateProfile || tc.principalMismatch { - if strings.Contains(calls, " delete ") || (!tc.lateProfile && strings.Contains(calls, " scale ")) { - t.Fatalf("unsafe mutation after owner mismatch: %s", calls) - } - return - } - wants := []string{"aks delete", "aks wait", "kubectl --context hub-admin -n fleet-system scale", - "--name " + prefix + "-member3", "--name " + prefix + "-member4", - "role assignment delete --ids " + group + "/providers/Microsoft.Authorization/roleAssignments/aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa", - "role assignment delete --ids " + nodeID + "/providers/Microsoft.Authorization/roleAssignments/bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb", - "role assignment delete --ids " + nodeID + "/providers/Microsoft.Authorization/roleAssignments/cccccccc-cccc-cccc-cccc-cccccccccccc", - "group wait", - "network vnet peering delete --ids " + vnet1, "network vnet peering delete --ids " + vnet2} - if !tc.noProfiles { - wants = append(wants, "resource delete --ids "+profileID, "resource delete --ids "+trafficProfileID) - } - for _, want := range wants { - if !strings.Contains(calls, want) { - t.Errorf("missing %q in calls:\n%s", want, calls) - } - } - if strings.Contains(calls, "roleAssignments/foreign") || strings.Contains(calls, "group delete") { - t.Fatalf("cleanup touched foreign resources: %s", calls) - } - if strings.Index(calls, "roleAssignments/bbbbbbbb") > strings.Index(calls, "aks delete") || - strings.Index(calls, "roleAssignments/aaaaaaaa") < strings.Index(calls, "aks wait") { - t.Fatalf("role deletion must preserve control-plane network access through AKS deletion: %s", calls) - } - }) - } - } - t.Run("controller and peerings", testControllerAndPeerings) - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - afdTestEnvironment(t) - t.Setenv("E2E_RUN_ID", "123-atm-1") - t.Setenv("AZURE_SUBSCRIPTION_ID", "test-subscription") - t.Setenv("AZURE_RESOURCE_GROUP", "fleet-networking-e2e") - dir := t.TempDir() - group := "/subscriptions/test-subscription/resourceGroups/fleet-networking-e2e" - hash := sha256.Sum256([]byte("test-subscription/fleet-networking-e2e/123-atm-1")) - prefix := fmt.Sprintf("fne%x", hash[:8]) - registry := prefix + "acr" - tags := map[string]string{"source": "fleet-networking", "fleet-e2e-run": "123-atm-1"} - if tt.conflict { - tags["fleet-e2e-run"] = "another-run" - } - items := []map[string]interface{}{ - {"id": group + "/providers/Microsoft.ContainerRegistry/registries/" + registry, - "name": registry, "type": "Microsoft.ContainerRegistry/registries", "tags": tags}, - {"id": group + "/providers/Microsoft.Network/virtualNetworks/other-run", - "name": "other-run", "type": "Microsoft.Network/virtualNetworks", - "tags": map[string]string{"fleet-e2e-run": "another-run"}}, - } - if tt.profile { - items = append(items, map[string]interface{}{ - "id": group + "/providers/Microsoft.Network/trafficManagerProfiles/fleet-123", - "name": "fleet-123", "type": "Microsoft.Network/trafficManagerProfiles", - "tags": map[string]string{"networking.fleet.azure.com.trafficManagerProfile": prefix + "-abcde/service"}, - }) - } - contents, err := json.Marshal(items) - if err != nil { - t.Fatal(err) - } - inventory := filepath.Join(dir, "inventory.json") - if err := os.WriteFile(inventory, contents, 0o600); err != nil { - t.Fatal(err) - } - t.Setenv("TEST_INVENTORY", inventory) - t.Setenv("TEST_CALLS", filepath.Join(dir, "calls")) - t.Setenv("TEST_LISTED", filepath.Join(dir, "listed")) - writeAFDCommand(t, filepath.Join(dir, "az"), `#!/bin/bash - set -euo pipefail - printf '%s\n' "$*" >> "$TEST_CALLS" - case "$1 $2" in - "group show") printf '%s\n' '{"id":"/subscriptions/test-subscription/resourceGroups/fleet-networking-e2e","tags":{"managedBy":"aks-rp/ci-resources","workload":"fleet-networking-e2e"}}' ;; - "resource list") - if [[ -e "$TEST_LISTED" ]]; then echo '[]'; else touch "$TEST_LISTED"; cat "$TEST_INVENTORY"; fi ;; - "resource show") jq --arg id "$4" '.[] | select(.id == $id)' "$TEST_INVENTORY" ;; - "role assignment") [[ "$3" == list ]] && echo '[]' ;; - "resource delete") ;; - *) echo "unexpected az command: $*" >&2; exit 1 ;; - esac - `) - t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH")) - output, err := runAFDScript(t, "./cleanup.sh") - if (err == nil) != tt.wantDeletes { - t.Fatalf("cleanup: %s (%v)", output, err) - } - calls := readAFDFile(t, filepath.Join(dir, "calls")) - if strings.Contains(calls, "group delete") || strings.Contains(calls, "other-run") { - t.Fatalf("cleanup touched foreign resources: %s", calls) - } - if strings.Contains(calls, "resource delete") != tt.wantDeletes { - t.Fatalf("unexpected resource deletion: %s", calls) - } - }) - } -} From 6099f2a6051e8c91dade038b764c35be6e328f45 Mon Sep 17 00:00:00 2001 From: Wei Weng Date: Tue, 24 Nov 2026 20:01:47 +0000 Subject: [PATCH 08/16] ci: remove GitHub Actions E2E workflow Keep Azure DevOps as the E2E pipeline and remove the workflow-specific test and setup output. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- ...26-11-24-1842-shared-e2e-resource-group.md | 2 + .github/workflows/e2e-tests.yml | 145 ------------------ test/README.md | 2 +- test/scripts/afd_test.go | 109 ------------- test/scripts/bootstrap.sh | 3 - 5 files changed, 3 insertions(+), 258 deletions(-) delete mode 100644 .github/workflows/e2e-tests.yml diff --git a/.github/.copilot/breadcrumbs/2026-11-24-1842-shared-e2e-resource-group.md b/.github/.copilot/breadcrumbs/2026-11-24-1842-shared-e2e-resource-group.md index 35613c9e..3d03c2c1 100644 --- a/.github/.copilot/breadcrumbs/2026-11-24-1842-shared-e2e-resource-group.md +++ b/.github/.copilot/breadcrumbs/2026-11-24-1842-shared-e2e-resource-group.md @@ -47,6 +47,8 @@ The user requested a generic local E2E guide and chose to retain both existing r The user subsequently requested removal of `shared_group_test.go` and `azure_principal_id_test.go`. Dedicated mocked cleanup and principal-token regression coverage is no longer retained. +The user requested removal of the GitHub Actions E2E workflow. Azure DevOps remains the E2E pipeline; its setup and cleanup behavior is unchanged. + Changed files: `.pipeline/e2e-tests.yaml`, `test/README.md`, the `test/scripts` setup, topology, configuration, AFD and cleanup scripts and tests, plus E2E framework workload naming and Traffic Manager public-IP tagging. ## Validation and risks diff --git a/.github/workflows/e2e-tests.yml b/.github/workflows/e2e-tests.yml deleted file mode 100644 index 31a6c1bf..00000000 --- a/.github/workflows/e2e-tests.yml +++ /dev/null @@ -1,145 +0,0 @@ -name: E2E Tests - -on: - workflow_dispatch: {} - -permissions: - id-token: write - contents: read - -env: - GO_VERSION: '1.26.10' - -jobs: - detect-noop: - runs-on: ubuntu-latest - outputs: - noop: ${{ steps.noop.outputs.should_skip }} - steps: - - name: Detect No-op Changes - id: noop - uses: fkirc/skip-duplicate-actions@b974a9395958c231af965b70070979a577efa578 # v5.3.2 - with: - github_token: ${{ secrets.GITHUB_TOKEN }} - do_not_skip: '["workflow_dispatch", "schedule", "push"]' - concurrent_skipping: false - - e2e-tests: - strategy: - # disable fail-fast to continue the in-progress pipeline when one failed job is detected to - # get test results for all scenarios. - fail-fast: false - matrix: - include: - - scenario: atm - network-setting: shared-vnet - enable-traffic-manager: true - enable-afd: false - - scenario: peered - network-setting: peered-vnet - enable-traffic-manager: false - enable-afd: false - - scenario: dynamic - network-setting: dynamic-ip-allocation - enable-traffic-manager: false - enable-afd: false - - scenario: unsupported - network-setting: unsupported - enable-traffic-manager: false - enable-afd: false - - scenario: afd - network-setting: shared-vnet - enable-traffic-manager: false - enable-afd: true - env: - ENABLE_AZURE_FRONT_DOOR: ${{ matrix.enable-afd }} - ENABLE_AFD_PRIVATE_LINK_AUTO_APPROVAL: ${{ matrix.enable-afd }} - ENABLE_TRAFFIC_MANAGER: ${{ matrix.enable-traffic-manager }} - AZURE_NETWORK_SETTING: ${{ matrix.network-setting }} - AZURE_SUBSCRIPTION_ID: ${{ secrets.E2E_AZURE_SUBSCRIPTION_ID }} - AZURE_RESOURCE_GROUP: fleet-networking-e2e - E2E_RUN_ID: gh-${{ github.run_id }}-${{ github.run_attempt }}-${{ matrix.scenario }} - RETAIN_AFD_E2E_SETUP: "false" - runs-on: ubuntu-latest - needs: [ - detect-noop, - ] - if: needs.detect-noop.outputs.noop != 'true' - steps: - - name: Set up Go - uses: actions/setup-go@d8cbb8045d7f43706b9177cceb36c1f91a6644d5 # v7.1.0 - with: - go-version: ${{ env.GO_VERSION }} - - - name: Check out code into the Go module directory - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - - - name: Prepare e2e variables - run: echo "KUBECONFIG=$RUNNER_TEMP/fleet-e2e-kubeconfig" >> "$GITHUB_ENV" - - # Reference: https://docs.github.com/en/actions/deployment/security-hardening-your-deployments/configuring-openid-connect-in-azure - - name: 'OIDC Login to Azure Public Cloud' - uses: azure/login@a641126d1b8aa4d1fa005f4f92df94a3a4c4c906 # v3.1.0 - with: - client-id: ${{ secrets.E2E_AZURE_CLIENT_ID }} - tenant-id: ${{ secrets.AZURE_TENANT_ID }} - subscription-id: ${{ secrets.E2E_AZURE_SUBSCRIPTION_ID }} - - # Note (chenyu1): - # - # After a recent update, GitHub Actions has set the GitHub ID token expiration time - # to 5 minutes for security reasons; as most of our E2E steps cannot finish within - # the time range, expiration errors will occur. - # - # As a temporary mitigation, we will add a step to fetch token periodically (every - # 4 minutes) to be exact. - # - # This should no longer be necessary after the Azure CLI supports ID token refresh. - - name: Fetch token every 4 minutes - run: | - while true; do - # $ACTIONS_ID_TOKEN_REQUEST_TOKEN and $ACTIONS_ID_TOKEN_REQUEST_URL env vars are provided by - # GitHub Actions automatically. - REQUEST_TOKEN=$ACTIONS_ID_TOKEN_REQUEST_TOKEN - REQUEST_URI=$ACTIONS_ID_TOKEN_REQUEST_URL - FED_TOKEN=$(curl -H "Authorization: bearer $REQUEST_TOKEN" "${REQUEST_URI}&audience=api://AzureADTokenExchange" | jq .value -r) - az login --service-principal -u ${{ secrets.E2E_AZURE_CLIENT_ID }} -t ${{ secrets.AZURE_TENANT_ID }} --federated-token "$FED_TOKEN" --output none - sleep 240 - done & - - - name: Setup e2e Environment - id: setup - run: | - if [[ "$ENABLE_AZURE_FRONT_DOOR" == true && "$ENABLE_AFD_PRIVATE_LINK_AUTO_APPROVAL" == true ]]; then - E2E_TEST_PRINCIPAL_ID="$(bash test/scripts/azure-principal-id.sh)" - export E2E_TEST_PRINCIPAL_ID - echo "E2E_TEST_PRINCIPAL_ID=$E2E_TEST_PRINCIPAL_ID" >> "$GITHUB_ENV" - fi - make e2e-setup - - name: Wait for role assignments to be effective - run: sleep 5m - - name: Run e2e tests - run: | - make e2e-tests - - name: Collect agent logs - if: always() - run: | - make e2e-collect-logs - env: - LOG_DIR: agent-logs-${{ matrix.network-setting }}-enable-atm-${{ matrix.enable-traffic-manager }}-enable-afd-${{ matrix.enable-afd }} - - name: Upload agent logs - if: always() - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 - with: - name: agent-logs-${{ matrix.network-setting }}-enable-atm-${{ matrix.enable-traffic-manager }}-enable-afd-${{ matrix.enable-afd }} - path: agent-logs-${{ matrix.network-setting }}-enable-atm-${{ matrix.enable-traffic-manager }}-enable-afd-${{ matrix.enable-afd }} - if-no-files-found: warn - retention-days: 3 - - name: Cleanup e2e - if: always() && steps.setup.outputs.resources_started == 'true' - run: | - make e2e-cleanup - env: - AZURE_CLIENT_ID: ${{ secrets.E2E_AZURE_CLIENT_ID}} - AZURE_CLIENT_SECRET: ${{ secrets.E2E_AZURE_CLIENT_SECRET }} - AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }} diff --git a/test/README.md b/test/README.md index c4738205..ac615ebf 100644 --- a/test/README.md +++ b/test/README.md @@ -727,7 +727,7 @@ resource IDs, and compares actual Azure SDK profile/endpoints. It also exercises Azure drift/deletion recovery, backend/member/weight changes and Kubernetes plus Azure resource absence during cleanup. -The [E2E workflow](../.github/workflows/e2e-tests.yml) enables ATM for the shared-VNet +The [E2E pipeline](../.pipeline/e2e-tests.yaml) enables ATM for the shared-VNet matrix entry, uses the existing setup/test targets, and collects logs even after a failure. Cleanup runs after ownership preflight has succeeded. These are implemented test/CI paths, not evidence that a particular live run passed. diff --git a/test/scripts/afd_test.go b/test/scripts/afd_test.go index 2ab28f6c..fa6f9b45 100644 --- a/test/scripts/afd_test.go +++ b/test/scripts/afd_test.go @@ -16,116 +16,8 @@ import ( "strings" "testing" "time" - - "k8s.io/apimachinery/pkg/util/yaml" ) -func TestAFDSharedVNetWorkflow(t *testing.T) { - var workflow struct { - Jobs map[string]struct { - Env map[string]string - Strategy struct { - Matrix struct { - Include []struct { - Scenario string `json:"scenario"` - Network string `json:"network-setting"` - ATM bool `json:"enable-traffic-manager"` - AFD bool `json:"enable-afd"` - } - } - } - Steps []struct { - Name string - ID string - If string - Run string - Env map[string]string - With map[string]string - } - } - } - contents := readAFDFile(t, filepath.Join("..", "..", ".github", "workflows", "e2e-tests.yml")) - if err := yaml.NewYAMLOrJSONDecoder(strings.NewReader(contents), 4096).Decode(&workflow); err != nil { - t.Fatal(err) - } - job := workflow.Jobs["e2e-tests"] - if job.Env["ENABLE_AZURE_FRONT_DOOR"] != "${{ matrix.enable-afd }}" || - job.Env["ENABLE_AFD_PRIVATE_LINK_AUTO_APPROVAL"] != "${{ matrix.enable-afd }}" || - job.Env["RETAIN_AFD_E2E_SETUP"] != "false" || - job.Env["AZURE_RESOURCE_GROUP"] != "fleet-networking-e2e" || - job.Env["E2E_RUN_ID"] != "gh-${{ github.run_id }}-${{ github.run_attempt }}-${{ matrix.scenario }}" { - t.Fatal("AFD selection, exact test approvals and ordinary cleanup must reach the entire job") - } - scenarios := make(map[string]bool) - ids := make(map[string]bool) - for _, row := range job.Strategy.Matrix.Include { - if row.Scenario == "" || ids[row.Scenario] { - t.Fatalf("scenario ID must be unique and nonempty: %q", row.Scenario) - } - ids[row.Scenario] = true - scenario := row.Network - switch { - case row.AFD: - if row.Network != "shared-vnet" || row.ATM { - t.Fatal("AFD must use an independent shared-VNet fixture") - } - scenario += "-afd" - case row.ATM: - if row.Network != "shared-vnet" { - t.Fatal("ATM requires shared-VNet") - } - scenario += "-atm" - } - if scenarios[scenario] { - t.Fatalf("duplicate CI scenario %s", scenario) - } - scenarios[scenario] = true - } - for _, scenario := range []string{"shared-vnet-atm", "shared-vnet-afd", "peered-vnet", "dynamic-ip-allocation", "unsupported"} { - if !scenarios[scenario] { - t.Errorf("missing CI scenario %s", scenario) - } - } - foundSetup, foundCleanup, foundKubeconfig := false, false, false - for _, step := range job.Steps { - for _, variable := range []string{"ENABLE_AZURE_FRONT_DOOR", "ENABLE_AFD_PRIVATE_LINK_AUTO_APPROVAL", "RETAIN_AFD_E2E_SETUP"} { - if value, ok := step.Env[variable]; ok && value != job.Env[variable] { - t.Errorf("%s overrides job selection for %s", step.Name, variable) - } - } - switch step.Name { - case "Prepare e2e variables": - foundKubeconfig = true - if !strings.Contains(step.Run, "KUBECONFIG=$RUNNER_TEMP/fleet-e2e-kubeconfig") { - t.Error("each job must prepare its own kubeconfig") - } - case "Setup e2e Environment": - foundSetup = true - if step.ID != "setup" || !strings.Contains(step.Run, "azure-principal-id.sh") { - t.Error("setup output must be addressable by cleanup") - } - case "Cleanup e2e": - foundCleanup = true - if step.If != "always() && steps.setup.outputs.resources_started == 'true'" { - t.Error("cleanup must require successful ownership preflight") - } - case "Collect agent logs": - if !strings.Contains(step.Env["LOG_DIR"], "${{ matrix.enable-afd }}") { - t.Error("collected logs must distinguish the two shared-VNet fixtures") - } - case "Upload agent logs": - for _, key := range []string{"name", "path"} { - if !strings.Contains(step.With[key], "${{ matrix.enable-afd }}") { - t.Errorf("artifact %s must distinguish the two shared-VNet fixtures", key) - } - } - } - } - if !foundSetup || !foundCleanup || !foundKubeconfig { - t.Fatal("shared E2E workflow is missing setup, cleanup or kubeconfig preparation") - } -} - func TestAFDConfiguration(t *testing.T) { tests := []struct { name, enabled, network, group, want string @@ -410,7 +302,6 @@ func afdTestEnvironment(t *testing.T) { "AFD_TEST_FAIL_COMMAND", "AFD_TEST_EMPTY_BINDINGS", "AFD_TEST_REAL_HELM", "AFD_TEST_SECOND_MANAGED_BY", "AFD_TEST_SECOND_CLUSTER_ID", "AFD_TEST_RENDERED", - "GITHUB_OUTPUT", } { t.Setenv(name, "") } diff --git a/test/scripts/bootstrap.sh b/test/scripts/bootstrap.sh index 08183aef..6132fb0c 100644 --- a/test/scripts/bootstrap.sh +++ b/test/scripts/bootstrap.sh @@ -58,9 +58,6 @@ if ! jq -e --arg prefix "$E2E_RESOURCE_PREFIX" --arg run "$E2E_RUN_ID" ' exit 1 fi echo "##vso[task.setvariable variable=e2eResourcesStarted]true" -if [[ -n "${GITHUB_OUTPUT:-}" ]]; then - echo "resources_started=true" >>"$GITHUB_OUTPUT" -fi if [[ "$RETAIN_AFD_E2E_SETUP" == true ]]; then trap 'echo "AFD setup interrupted; retaining resources for explicit later cleanup" >&2; exit 130' INT From b439350c8da5ece77f5a64460512e0bf09dd3936 Mon Sep 17 00:00:00 2001 From: Wei Weng Date: Tue, 24 Nov 2026 20:07:34 +0000 Subject: [PATCH 09/16] ci: use pipeline variable for E2E principal Read the service principal object ID from Azure DevOps configuration instead of decoding an access token. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- ...26-11-24-1842-shared-e2e-resource-group.md | 2 +- .pipeline/e2e-tests.yaml | 8 ++--- test/README.md | 2 +- test/scripts/azure-principal-id.sh | 31 ------------------- 4 files changed, 4 insertions(+), 39 deletions(-) delete mode 100644 test/scripts/azure-principal-id.sh diff --git a/.github/.copilot/breadcrumbs/2026-11-24-1842-shared-e2e-resource-group.md b/.github/.copilot/breadcrumbs/2026-11-24-1842-shared-e2e-resource-group.md index 3d03c2c1..2502f748 100644 --- a/.github/.copilot/breadcrumbs/2026-11-24-1842-shared-e2e-resource-group.md +++ b/.github/.copilot/breadcrumbs/2026-11-24-1842-shared-e2e-resource-group.md @@ -41,7 +41,7 @@ The Azure DevOps pipeline supplies a unique run ID per scenario and attempt; scr Cleanup verifies the group, run tags, resource IDs, AKS node-group ownership, role scopes and peering targets. It verifies Traffic Manager namespace tags and Front Door hub/Gateway identity, stops the run's hub controllers before deleting their profiles, deletes only identified roles and resources, and never deletes the shared group. It fails explicitly when ownership, controller quiescence or deletion cannot be verified. -Shared AFD requires the test principal object ID, grants it Network Contributor only on verified member node groups, and records the principal for cleanup. CI obtains the object ID from its Azure CLI access token without logging or storing the token. The pipeline service connection remains unchanged by default and can be selected explicitly after its grants are deployed. +Shared AFD requires the test principal object ID, grants it Network Contributor only on verified member node groups, and records the principal for cleanup. The user requested storing the object ID as the `E2E_TEST_PRINCIPAL_ID` Azure DevOps pipeline variable instead of parsing a token; the variable was configured for the current CI identity. It must be updated whenever the selected service connection changes; its identity is not independently verified by the pipeline. The user requested a generic local E2E guide and chose to retain both existing resource-group tag checks. The guide now uses a caller-selected group name and explains the required tag values; setup and cleanup behavior is unchanged. diff --git a/.pipeline/e2e-tests.yaml b/.pipeline/e2e-tests.yaml index f7943d92..fc120cfd 100644 --- a/.pipeline/e2e-tests.yaml +++ b/.pipeline/e2e-tests.yaml @@ -99,7 +99,7 @@ jobs: - bash: | set -euo pipefail : "${AZURE_SUBSCRIPTION_ID:?Set AZURE_SUBSCRIPTION_ID as a non-secret ADO pipeline variable}" - for tool in az docker helm kubectl jq yq make timeout sha256sum python3; do + for tool in az docker helm kubectl jq yq make timeout sha256sum; do command -v "$tool" done go version @@ -137,11 +137,7 @@ jobs: echo "error: shared resource group $AZURE_RESOURCE_GROUP does not exist" >&2 exit 1 fi - if [[ "$ENABLE_AZURE_FRONT_DOOR" == true && "$ENABLE_AFD_PRIVATE_LINK_AUTO_APPROVAL" == true ]]; then - E2E_TEST_PRINCIPAL_ID="$(bash test/scripts/azure-principal-id.sh)" - export E2E_TEST_PRINCIPAL_ID - echo "##vso[task.setvariable variable=E2E_TEST_PRINCIPAL_ID]$E2E_TEST_PRINCIPAL_ID" - fi + # E2E_TEST_PRINCIPAL_ID is a pipeline variable and must match the service connection. make e2e-setup - bash: | diff --git a/test/README.md b/test/README.md index ac615ebf..e9bb1335 100644 --- a/test/README.md +++ b/test/README.md @@ -12,7 +12,7 @@ networking components, and runs the Ginkgo tests under `test/e2e`. - [kubectl](https://kubernetes.io/docs/tasks/tools/) - [`jq`](https://jqlang.github.io/jq/download/) - [`yq`](https://github.com/mikefarah/yq#install) -- Python 3 and `sha256sum` +- `sha256sum` - Bash and GNU Make - An Azure subscription in which the signed-in identity can provision the test resources and create the required role assignments diff --git a/test/scripts/azure-principal-id.sh b/test/scripts/azure-principal-id.sh deleted file mode 100644 index f23c993c..00000000 --- a/test/scripts/azure-principal-id.sh +++ /dev/null @@ -1,31 +0,0 @@ -#!/bin/bash -set -o errexit -set -o nounset -set -o pipefail -set +x - -: "${AZURE_SUBSCRIPTION_ID:?AZURE_SUBSCRIPTION_ID is required}" - -az account get-access-token --subscription "$AZURE_SUBSCRIPTION_ID" \ - --resource https://management.azure.com/ --query accessToken -o tsv | - python3 -c ' -import base64 -import binascii -import json -import re -import sys - -try: - parts = sys.stdin.read().strip().split(".") - if len(parts) != 3: - raise ValueError("invalid token") - payload = parts[1] + "=" * (-len(parts[1]) % 4) - principal = json.loads(base64.urlsafe_b64decode(payload))["oid"] - if not isinstance(principal, str) or not re.fullmatch( - r"[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}", principal - ): - raise ValueError("invalid object ID") -except (binascii.Error, ValueError, UnicodeError, KeyError, TypeError): - sys.exit("error: Azure CLI token does not contain a valid principal object ID") -print(principal.lower()) -' From 6cde555e036b0f5f2c7e12eab3209e1ba593cbbc Mon Sep 17 00:00:00 2001 From: Wei Weng Date: Tue, 24 Nov 2026 20:18:05 +0000 Subject: [PATCH 10/16] ci: remove E2E setup preflight checks Run log collection and per-resource cleanup unconditionally without requiring a setup marker. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- ...26-11-24-1842-shared-e2e-resource-group.md | 16 +++++++++---- .pipeline/e2e-tests.yaml | 11 +++------ test/README.md | 24 +++++++++---------- test/scripts/bootstrap.sh | 20 ---------------- test/scripts/cleanup-shared-group.sh | 9 ------- 5 files changed, 27 insertions(+), 53 deletions(-) diff --git a/.github/.copilot/breadcrumbs/2026-11-24-1842-shared-e2e-resource-group.md b/.github/.copilot/breadcrumbs/2026-11-24-1842-shared-e2e-resource-group.md index 2502f748..82513ee7 100644 --- a/.github/.copilot/breadcrumbs/2026-11-24-1842-shared-e2e-resource-group.md +++ b/.github/.copilot/breadcrumbs/2026-11-24-1842-shared-e2e-resource-group.md @@ -29,6 +29,13 @@ Each Azure DevOps scenario creates and deletes a unique resource group. Fixed re ## Status +The user approved removing setup kubeconfig, group and collision checks, the cleanup marker, and matching cleanup checks. Azure DevOps log collection and cleanup will run with `always()`. Per-resource ownership checks remain. + +1. [x] Remove the selected setup and cleanup checks and marker. +2. [x] Make Azure DevOps log collection and cleanup unconditional. +3. [x] Update documentation and validate offline. +4. [ ] Push the changes. + The shared-group-only revision: 1. [x] Remove the legacy resource-group creation/deletion path and require per-run shared-group configuration. @@ -37,13 +44,13 @@ The shared-group-only revision: 4. [x] Update tests and documentation and validate offline. 5. [x] Push the shared-group-only revision. -The Azure DevOps pipeline supplies a unique run ID per scenario and attempt; scripts derive physical Azure names and retain the established logical Kubernetes contexts. Setup requires a new run-specific kubeconfig, verifies the group and rejects name or ownership collisions before enabling cleanup. +The Azure DevOps pipeline supplies a unique run ID per scenario and attempt; scripts derive physical Azure names and retain the established logical Kubernetes contexts. At the user's request, setup no longer validates the kubeconfig path, resource-group tags or run collisions. Azure DevOps always attempts log collection and cleanup. -Cleanup verifies the group, run tags, resource IDs, AKS node-group ownership, role scopes and peering targets. It verifies Traffic Manager namespace tags and Front Door hub/Gateway identity, stops the run's hub controllers before deleting their profiles, deletes only identified roles and resources, and never deletes the shared group. It fails explicitly when ownership, controller quiescence or deletion cannot be verified. +Cleanup verifies run tags, resource IDs, AKS node-group ownership, role scopes and peering targets. It verifies Traffic Manager namespace tags and Front Door hub/Gateway identity, stops the run's hub controllers before deleting their profiles, deletes only identified roles and resources, and never deletes the shared group. It fails explicitly when ownership, controller quiescence or deletion cannot be verified. Shared AFD requires the test principal object ID, grants it Network Contributor only on verified member node groups, and records the principal for cleanup. The user requested storing the object ID as the `E2E_TEST_PRINCIPAL_ID` Azure DevOps pipeline variable instead of parsing a token; the variable was configured for the current CI identity. It must be updated whenever the selected service connection changes; its identity is not independently verified by the pipeline. -The user requested a generic local E2E guide and chose to retain both existing resource-group tag checks. The guide now uses a caller-selected group name and explains the required tag values; setup and cleanup behavior is unchanged. +The user initially chose to retain both resource-group tag checks, then explicitly requested removing them. The guide uses a caller-selected pre-created group name. The user subsequently requested removal of `shared_group_test.go` and `azure_principal_id_test.go`. Dedicated mocked cleanup and principal-token regression coverage is no longer retained. @@ -58,4 +65,5 @@ Changed files: `.pipeline/e2e-tests.yaml`, `test/README.md`, the `test/scripts` - `GOTOOLCHAIN=go1.26.10 go test -tags=e2e -run '^$' ./test/e2e` and `go vet -tags=e2e ./test/e2e` passed without executing live E2E. - Performance packages compiled and passed `go vet` without running their suites. Installed Azure CLI option checks, Bash syntax, both workflow YAML parsing and `git diff --check` passed. - The generic guide's Markdown fences are balanced and its local links resolve. -- No live Azure provisioning, permission, test or cleanup operation was run. The proposed grants and service connection have not been enabled. Cleanup can fail closed and leave resources; there is no stale-run sweeper. Contributor on the shared RG is not a security boundary between runs. +- After preflight removal, mocked setup reached creation with unset and existing kubeconfig paths; mocked cleanup reached credential retrieval without kubeconfig or group-tag checks. Azure DevOps YAML checks verified unconditional log collection and cleanup, and the remaining script suite and vet passed. +- The new preflight-removal change has not been validated against live Azure. Setup can overwrite existing kubeconfig contexts and reuse run resources; uniqueness is the caller's responsibility. Cleanup can fail closed and leave resources; there is no stale-run sweeper. Contributor on the shared RG is not a security boundary between runs. diff --git a/.pipeline/e2e-tests.yaml b/.pipeline/e2e-tests.yaml index fc120cfd..f24e173d 100644 --- a/.pipeline/e2e-tests.yaml +++ b/.pipeline/e2e-tests.yaml @@ -132,11 +132,6 @@ jobs: echo "error: service connection subscription does not match the E2E subscription" >&2 exit 1 fi - exists=$(az group exists --subscription "$AZURE_SUBSCRIPTION_ID" -n "$AZURE_RESOURCE_GROUP") - if [[ "$exists" != true ]]; then - echo "error: shared resource group $AZURE_RESOURCE_GROUP does not exist" >&2 - exit 1 - fi # E2E_TEST_PRINCIPAL_ID is a pipeline variable and must match the service connection. make e2e-setup @@ -177,12 +172,12 @@ jobs: > "$LOG_DIR/environment.txt" make e2e-collect-logs displayName: Collect agent logs - condition: and(always(), eq(variables['e2eResourcesStarted'], 'true')) + condition: always() timeoutInMinutes: 5 - task: PublishPipelineArtifact@1 displayName: Publish agent logs - condition: and(always(), eq(variables['e2eResourcesStarted'], 'true')) + condition: always() timeoutInMinutes: 5 inputs: targetPath: '$(LOG_DIR)' @@ -190,7 +185,7 @@ jobs: - task: AzureCLI@2 displayName: Clean up this run's resources - condition: and(always(), eq(variables['e2eResourcesStarted'], 'true')) + condition: always() timeoutInMinutes: 90 inputs: azureSubscription: ${{ parameters.serviceConnection }} diff --git a/test/README.md b/test/README.md index e9bb1335..19ec3746 100644 --- a/test/README.md +++ b/test/README.md @@ -30,23 +30,24 @@ assigns Azure roles. Use a test subscription rather than a production subscripti ### Shared resource group -Use a pre-created test resource group of your choice. Setup and cleanup require these group tags: -`managedBy=aks-rp/ci-resources` and `workload=fleet-networking-e2e`; the latter is a tag value, -not the required group name. The identity must be able to manage test resources and assign the -necessary roles, including on AKS node resource groups. +Use a pre-created test resource group of your choice. The identity must be able to manage test +resources and assign the necessary roles, including on AKS node resource groups. For local runs, set the following in addition to the scenario variables: ```bash export AZURE_RESOURCE_GROUP= export E2E_RUN_ID= -export KUBECONFIG= +# Recommended: use a separate kubeconfig for this run. +export KUBECONFIG= # Required only when AFD automatic approval is enabled: export E2E_TEST_PRINCIPAL_ID= ``` Use a unique `E2E_RUN_ID` for every concurrent run and retry; never reuse an ID while a prior run or its cleanup is active. Use at most 63 lowercase letters, digits and hyphens, beginning with a -letter or digit. Setup refuses existing run resources and requires a new kubeconfig path. +letter or digit. Setup does not check for existing run resources. Reusing an ID can overwrite +or delete resources from another run. Existing kubeconfig contexts can also be overwritten; use +a separate kubeconfig to avoid changing them. For local AFD auto-approval, sign in as the specified service principal; otherwise disable auto-approval and arrange manual approval by an authorized PLS owner. @@ -55,9 +56,9 @@ group**. Keep the same run ID, kubeconfig and, for AFD auto-approval, principal If cleanup fails, inspect remaining resources before retrying; there is no automatic stale-run sweeper. -Run-specific names and cleanup checks prevent accidental cross-run deletion; they are not an Azure -security boundary: an identity with Contributor on the group can modify other runs' resources and -delete the group. +Cleanup checks resource ownership but does not prevent deletion of resources from another run +using the same ID. It is not an Azure security boundary: an identity with Contributor on the group +can modify other runs' resources and delete the group. ## Choose an E2E scenario @@ -728,9 +729,8 @@ Azure drift/deletion recovery, backend/member/weight changes and Kubernetes plus Azure resource absence during cleanup. The [E2E pipeline](../.pipeline/e2e-tests.yaml) enables ATM for the shared-VNet -matrix entry, uses the existing setup/test targets, and collects logs even after a failure. -Cleanup runs after ownership preflight has succeeded. These are implemented test/CI paths, not evidence that a -particular live run passed. +matrix entry, uses the existing setup/test targets, and attempts log collection and cleanup even +after a failure. These are implemented test/CI paths, not evidence that a particular live run passed. The reviewed ATM scenario has no application HTTP request, observed health-probe logs or statistical traffic-distribution assertion; its Azure comparison ignores diff --git a/test/scripts/bootstrap.sh b/test/scripts/bootstrap.sh index 6132fb0c..7740c742 100644 --- a/test/scripts/bootstrap.sh +++ b/test/scripts/bootstrap.sh @@ -38,26 +38,6 @@ az account set -s ${AZURE_SUBSCRIPTION_ID} export RESOURCE_GROUP="$AZURE_RESOURCE_GROUP" export LOCATION="${LOCATION:-eastus2}" -if [[ -z "${KUBECONFIG:-}" || "$KUBECONFIG" == *:* || -e "$KUBECONFIG" || -L "$KUBECONFIG" ]]; then - echo "error: shared setup requires a new, run-specific KUBECONFIG path" >&2 - exit 1 -fi -group="$(az group show --subscription "$AZURE_SUBSCRIPTION_ID" --name "$RESOURCE_GROUP" -o json)" -jq -e --arg id "/subscriptions/$AZURE_SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP" \ - '(.id | ascii_downcase) == ($id | ascii_downcase) and .tags.managedBy == "aks-rp/ci-resources" and .tags.workload == "fleet-networking-e2e"' \ - <<<"$group" > /dev/null -resources="$(az resource list --subscription "$AZURE_SUBSCRIPTION_ID" --resource-group "$RESOURCE_GROUP" -o json)" -if ! jq -e --arg prefix "$E2E_RESOURCE_PREFIX" --arg run "$E2E_RUN_ID" ' - all(.[]; - ((.name | ascii_downcase | startswith($prefix)) | not) and - .tags["fleet-e2e-run"] != $run and - ((.tags["networking.fleet.azure.com.trafficManagerProfile"] // "") | startswith($prefix + "-") | not) and - ((.tags["networking.fleet.azure.com.gateway-namespace"] // "") | startswith($prefix + "-") | not)) -' <<<"$resources" >/dev/null; then - echo "error: refusing to reuse resources for run $E2E_RUN_ID" >&2 - exit 1 -fi -echo "##vso[task.setvariable variable=e2eResourcesStarted]true" if [[ "$RETAIN_AFD_E2E_SETUP" == true ]]; then trap 'echo "AFD setup interrupted; retaining resources for explicit later cleanup" >&2; exit 130' INT diff --git a/test/scripts/cleanup-shared-group.sh b/test/scripts/cleanup-shared-group.sh index f0748175..0f4cb65a 100644 --- a/test/scripts/cleanup-shared-group.sh +++ b/test/scripts/cleanup-shared-group.sh @@ -10,11 +10,6 @@ if [[ "$RETAIN_AFD_E2E_SETUP" == true ]]; then fi group_id="/subscriptions/$AZURE_SUBSCRIPTION_ID/resourceGroups/$AZURE_RESOURCE_GROUP" -group="$(az group show --subscription "$AZURE_SUBSCRIPTION_ID" --name "$AZURE_RESOURCE_GROUP" -o json)" -jq -e --arg id "$group_id" \ - '(.id | ascii_downcase) == ($id | ascii_downcase) and .tags.managedBy == "aks-rp/ci-resources" and .tags.workload == "fleet-networking-e2e"' \ - <<<"$group" >/dev/null - resources="$(az resource list --subscription "$AZURE_SUBSCRIPTION_ID" --resource-group "$AZURE_RESOURCE_GROUP" -o json)" if ! jq -e --arg prefix "$E2E_RESOURCE_PREFIX" --arg run "$E2E_RUN_ID" --arg group "$group_id" \ --arg hub "$HUB_AZURE_CLUSTER" --arg member1 "$MEMBER_1_AZURE_CLUSTER" --arg member2 "$MEMBER_2_AZURE_CLUSTER" \ @@ -89,10 +84,6 @@ if [[ -n "$recorded_caller" && "$recorded_caller" != "${E2E_TEST_PRINCIPAL_ID:-} fi if [[ "$has_hub" == true && ( "$(jq 'length' <<<"$profiles")" -gt 0 || "$hub_has_controllers" == true ) ]]; then - if [[ -z "${KUBECONFIG:-}" || "$KUBECONFIG" == *:* ]]; then - echo "error: controller cleanup requires the run-specific KUBECONFIG path" >&2 - exit 1 - fi hub="$(az aks show --subscription "$AZURE_SUBSCRIPTION_ID" --resource-group "$AZURE_RESOURCE_GROUP" --name "$HUB_AZURE_CLUSTER" -o json)" jq -e --arg id "$group_id/providers/Microsoft.ContainerService/managedClusters/$HUB_AZURE_CLUSTER" --arg run "$E2E_RUN_ID" \ '(.id | ascii_downcase) == ($id | ascii_downcase) and .tags.source == "fleet-networking" and .tags["fleet-e2e-run"] == $run' \ From a2c5a17b5514a5a97a89eb34d5a1eb0876286ca4 Mon Sep 17 00:00:00 2001 From: Wei Weng Date: Tue, 24 Nov 2026 20:18:32 +0000 Subject: [PATCH 11/16] docs: record E2E preflight removal Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../breadcrumbs/2026-11-24-1842-shared-e2e-resource-group.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/.copilot/breadcrumbs/2026-11-24-1842-shared-e2e-resource-group.md b/.github/.copilot/breadcrumbs/2026-11-24-1842-shared-e2e-resource-group.md index 82513ee7..de51491e 100644 --- a/.github/.copilot/breadcrumbs/2026-11-24-1842-shared-e2e-resource-group.md +++ b/.github/.copilot/breadcrumbs/2026-11-24-1842-shared-e2e-resource-group.md @@ -34,7 +34,7 @@ The user approved removing setup kubeconfig, group and collision checks, the cle 1. [x] Remove the selected setup and cleanup checks and marker. 2. [x] Make Azure DevOps log collection and cleanup unconditional. 3. [x] Update documentation and validate offline. -4. [ ] Push the changes. +4. [x] Push the changes. The shared-group-only revision: From bd9103fc9f878878d9392cb02c3c4f7f112c418a Mon Sep 17 00:00:00 2001 From: Wei Weng Date: Tue, 24 Nov 2026 20:30:25 +0000 Subject: [PATCH 12/16] fix: use correct AKS admin context names Pass the unsuffixed context name to az aks get-credentials because Azure CLI appends -admin for admin credentials. Cover setup, performance setup and cleanup with an offline regression test. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- ...26-11-24-1842-shared-e2e-resource-group.md | 13 ++++ test/scripts/afd_commands_test.go | 75 +++++++++++++++++++ test/scripts/bootstrap.sh | 11 +-- test/scripts/cleanup-shared-group.sh | 2 +- 4 files changed, 95 insertions(+), 6 deletions(-) diff --git a/.github/.copilot/breadcrumbs/2026-11-24-1842-shared-e2e-resource-group.md b/.github/.copilot/breadcrumbs/2026-11-24-1842-shared-e2e-resource-group.md index de51491e..ec3de24f 100644 --- a/.github/.copilot/breadcrumbs/2026-11-24-1842-shared-e2e-resource-group.md +++ b/.github/.copilot/breadcrumbs/2026-11-24-1842-shared-e2e-resource-group.md @@ -29,6 +29,19 @@ Each Azure DevOps scenario creates and deletes a unique resource group. Fixed re ## Status +### Admin-context failure follow-up + +The approved Azure DevOps run failed during setup because Azure CLI appended `-admin` to context names that already included that suffix. The same issue blocked ATM and AFD cleanup. The user requested a fix, push and another run. + +1. [x] Reproduce the context failure in a focused offline test. +2. [x] Correct setup and cleanup and validate offline. +3. [ ] Inspect and report resources left by the failed run; obtain explicit approval before any manual cleanup. +4. [ ] Push the fix and trigger the requested new E2E run. + +Azure CLI appends `-admin` to an explicitly supplied context for admin credentials. Setup and cleanup now pass the unsuffixed logical cluster name; the Kubernetes context remains `-admin`. The focused mock reproduces the failure before the fix and passes afterward for ordinary setup, performance setup and cleanup. The full script suite, vet, Bash syntax and whitespace checks passed. + +The original run completed with failed ATM and AFD cleanup. Read-only inspection found six surviving AKS clusters and their managed node groups, plus run-owned registries, VNets and identities. Manual cleanup requires separate approval; do not delete the shared resource group. + The user approved removing setup kubeconfig, group and collision checks, the cleanup marker, and matching cleanup checks. Azure DevOps log collection and cleanup will run with `always()`. Per-resource ownership checks remain. 1. [x] Remove the selected setup and cleanup checks and marker. diff --git a/test/scripts/afd_commands_test.go b/test/scripts/afd_commands_test.go index 5c39dba9..ef038ca3 100644 --- a/test/scripts/afd_commands_test.go +++ b/test/scripts/afd_commands_test.go @@ -25,6 +25,81 @@ import ( "k8s.io/apimachinery/pkg/util/yaml" ) +func TestAKSAdminContexts(t *testing.T) { + bootstrap := readAFDFile(t, "bootstrap.sh") + _, setup, found := strings.Cut(bootstrap, "# Export kubeconfig.") + if !found { + t.Fatal("bootstrap kubeconfig section not found") + } + setup, _, found = strings.Cut(setup, "# Setup hub cluster credentials.") + if !found { + t.Fatal("bootstrap kubeconfig section is incomplete") + } + cleanup := readAFDFile(t, "cleanup-shared-group.sh") + const start = " az aks get-credentials --subscription" + _, cleanup, found = strings.Cut(cleanup, start) + if !found { + t.Fatal("cleanup credential retrieval not found") + } + cleanup, _, found = strings.Cut(cleanup, ` if [[ ! "$hub_uid"`) + if !found { + t.Fatal("cleanup credential retrieval is incomplete") + } + cleanup = start + cleanup + + for _, tt := range []struct { + name, network, script string + }{ + {"setup", "shared-vnet", setup + ` +for context in hub-admin member-1-admin member-2-admin; do + kubectl --context "$context" get namespace kube-system +done`}, + {"performance setup", "perf-test", setup + ` +for context in hub-admin member-1-admin member-2-admin member-3-admin member-4-admin; do + kubectl --context "$context" get namespace kube-system +done`}, + {"cleanup", "shared-vnet", cleanup + ` +[[ "$hub_uid" == 11111111-1111-1111-1111-111111111111 ]]`}, + } { + t.Run(tt.name, func(t *testing.T) { + afdTestEnvironment(t) + t.Setenv("AZURE_NETWORK_SETTING", tt.network) + dir := t.TempDir() + t.Setenv("TEST_CONTEXTS", filepath.Join(dir, "contexts")) + writeAFDCommand(t, filepath.Join(dir, "az"), `#!/bin/bash +set -euo pipefail +[[ "$1 $2" == "aks get-credentials" ]] +context=""; admin=false +while (($#)); do + case "$1" in + --admin) admin=true; shift ;; + --context) context="$2"; shift 2 ;; + *) shift ;; + esac +done +[[ "$admin" == true && -n "$context" ]] +printf '%s-admin\n' "$context" >>"$TEST_CONTEXTS" +`) + writeAFDCommand(t, filepath.Join(dir, "kubectl"), `#!/bin/bash +set -euo pipefail +[[ "$1" == --context ]] +grep -Fxq "$2" "$TEST_CONTEXTS" || { echo "missing context $2" >&2; exit 1; } +if [[ "$*" == *"config view"* ]]; then + echo "https://hub.example.test" +else + echo "11111111-1111-1111-1111-111111111111" +fi +`) + t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH")) + script := "set -euo pipefail\nsource ./e2e-config.sh\nexport RESOURCE_GROUP=\"$AZURE_RESOURCE_GROUP\"\n" + tt.script + output, err := runAFDScript(t, "-ec", script) + if err != nil { + t.Fatalf("admin contexts are not usable: %s: %v", output, err) + } + }) + } +} + func TestAFDCommandFailureStopsWork(t *testing.T) { tests := []struct { name, script, command, forbidden string diff --git a/test/scripts/bootstrap.sh b/test/scripts/bootstrap.sh index 7740c742..4cc15b20 100644 --- a/test/scripts/bootstrap.sh +++ b/test/scripts/bootstrap.sh @@ -237,13 +237,14 @@ EOF fi # Export kubeconfig. -az aks get-credentials --name $HUB_AZURE_CLUSTER -g $RESOURCE_GROUP --admin --context "$HUB_CLUSTER-admin" --overwrite-existing -az aks get-credentials --name $MEMBER_1_AZURE_CLUSTER -g $RESOURCE_GROUP --admin --context "$MEMBER_CLUSTER_1-admin" --overwrite-existing -az aks get-credentials --name $MEMBER_2_AZURE_CLUSTER -g $RESOURCE_GROUP --admin --context "$MEMBER_CLUSTER_2-admin" --overwrite-existing +# Azure CLI adds the "-admin" suffix for admin credentials. +az aks get-credentials --name $HUB_AZURE_CLUSTER -g $RESOURCE_GROUP --admin --context "$HUB_CLUSTER" --overwrite-existing +az aks get-credentials --name $MEMBER_1_AZURE_CLUSTER -g $RESOURCE_GROUP --admin --context "$MEMBER_CLUSTER_1" --overwrite-existing +az aks get-credentials --name $MEMBER_2_AZURE_CLUSTER -g $RESOURCE_GROUP --admin --context "$MEMBER_CLUSTER_2" --overwrite-existing if [ "${AZURE_NETWORK_SETTING}" == "perf-test" ] then - az aks get-credentials --name $MEMBER_3_AZURE_CLUSTER -g $RESOURCE_GROUP --admin --context "$MEMBER_CLUSTER_3-admin" --overwrite-existing - az aks get-credentials --name $MEMBER_4_AZURE_CLUSTER -g $RESOURCE_GROUP --admin --context "$MEMBER_CLUSTER_4-admin" --overwrite-existing + az aks get-credentials --name $MEMBER_3_AZURE_CLUSTER -g $RESOURCE_GROUP --admin --context "$MEMBER_CLUSTER_3" --overwrite-existing + az aks get-credentials --name $MEMBER_4_AZURE_CLUSTER -g $RESOURCE_GROUP --admin --context "$MEMBER_CLUSTER_4" --overwrite-existing fi HUB_URL="$(kubectl --context "$HUB_CLUSTER-admin" config view --minify -o jsonpath='{.clusters[0].cluster.server}')" export HUB_URL diff --git a/test/scripts/cleanup-shared-group.sh b/test/scripts/cleanup-shared-group.sh index 0f4cb65a..ac86d0c4 100644 --- a/test/scripts/cleanup-shared-group.sh +++ b/test/scripts/cleanup-shared-group.sh @@ -89,7 +89,7 @@ if [[ "$has_hub" == true && ( "$(jq 'length' <<<"$profiles")" -gt 0 || '(.id | ascii_downcase) == ($id | ascii_downcase) and .tags.source == "fleet-networking" and .tags["fleet-e2e-run"] == $run' \ <<<"$hub" >/dev/null az aks get-credentials --subscription "$AZURE_SUBSCRIPTION_ID" --resource-group "$AZURE_RESOURCE_GROUP" \ - --name "$HUB_AZURE_CLUSTER" --admin --context "$HUB_CLUSTER-admin" --overwrite-existing + --name "$HUB_AZURE_CLUSTER" --admin --context "$HUB_CLUSTER" --overwrite-existing hub_uid="$(kubectl --context "$HUB_CLUSTER-admin" get namespace kube-system -o jsonpath='{.metadata.uid}')" if [[ ! "$hub_uid" =~ ^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$ ]]; then echo "error: could not verify hub UID for controller profile cleanup" >&2 From 61248849003daf40232e1364b2aeaa715b85c071 Mon Sep 17 00:00:00 2001 From: Wei Weng Date: Tue, 24 Nov 2026 20:46:22 +0000 Subject: [PATCH 13/16] docs: record failed E2E cleanup Record approved cleanup and clarify Azure CLI admin context naming. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../2026-11-24-1842-shared-e2e-resource-group.md | 7 ++++--- test/scripts/cleanup-shared-group.sh | 1 + 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/.github/.copilot/breadcrumbs/2026-11-24-1842-shared-e2e-resource-group.md b/.github/.copilot/breadcrumbs/2026-11-24-1842-shared-e2e-resource-group.md index ec3de24f..aec74c5b 100644 --- a/.github/.copilot/breadcrumbs/2026-11-24-1842-shared-e2e-resource-group.md +++ b/.github/.copilot/breadcrumbs/2026-11-24-1842-shared-e2e-resource-group.md @@ -35,12 +35,13 @@ The approved Azure DevOps run failed during setup because Azure CLI appended `-a 1. [x] Reproduce the context failure in a focused offline test. 2. [x] Correct setup and cleanup and validate offline. -3. [ ] Inspect and report resources left by the failed run; obtain explicit approval before any manual cleanup. -4. [ ] Push the fix and trigger the requested new E2E run. +3. [x] Inspect and report resources left by the failed run; obtain explicit approval before manual cleanup. +4. [x] Push the fix. +5. [ ] Trigger and validate the requested new E2E run. Azure CLI appends `-admin` to an explicitly supplied context for admin credentials. Setup and cleanup now pass the unsuffixed logical cluster name; the Kubernetes context remains `-admin`. The focused mock reproduces the failure before the fix and passes afterward for ordinary setup, performance setup and cleanup. The full script suite, vet, Bash syntax and whitespace checks passed. -The original run completed with failed ATM and AFD cleanup. Read-only inspection found six surviving AKS clusters and their managed node groups, plus run-owned registries, VNets and identities. Manual cleanup requires separate approval; do not delete the shared resource group. +The original run completed with failed ATM and AFD cleanup. The user explicitly approved cleanup of those two scenarios. The fixed cleanup completed successfully; read-back found no tagged resources, no six AKS-managed node groups and no role assignments on those node-group scopes. The shared resource group and its tags were preserved, and temporary admin kubeconfigs were removed. The user approved removing setup kubeconfig, group and collision checks, the cleanup marker, and matching cleanup checks. Azure DevOps log collection and cleanup will run with `always()`. Per-resource ownership checks remain. diff --git a/test/scripts/cleanup-shared-group.sh b/test/scripts/cleanup-shared-group.sh index ac86d0c4..071decd7 100644 --- a/test/scripts/cleanup-shared-group.sh +++ b/test/scripts/cleanup-shared-group.sh @@ -88,6 +88,7 @@ if [[ "$has_hub" == true && ( "$(jq 'length' <<<"$profiles")" -gt 0 || jq -e --arg id "$group_id/providers/Microsoft.ContainerService/managedClusters/$HUB_AZURE_CLUSTER" --arg run "$E2E_RUN_ID" \ '(.id | ascii_downcase) == ($id | ascii_downcase) and .tags.source == "fleet-networking" and .tags["fleet-e2e-run"] == $run' \ <<<"$hub" >/dev/null + # Azure CLI adds the "-admin" suffix for admin credentials. az aks get-credentials --subscription "$AZURE_SUBSCRIPTION_ID" --resource-group "$AZURE_RESOURCE_GROUP" \ --name "$HUB_AZURE_CLUSTER" --admin --context "$HUB_CLUSTER" --overwrite-existing hub_uid="$(kubectl --context "$HUB_CLUSTER-admin" get namespace kube-system -o jsonpath='{.metadata.uid}')" From b846f80180a2bc692831646c84efcb4a0b787ad5 Mon Sep 17 00:00:00 2001 From: Wei Weng Date: Tue, 24 Nov 2026 21:07:45 +0000 Subject: [PATCH 14/16] docs: summarize shared E2E cleanup steps Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- test/scripts/cleanup-shared-group.sh | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/test/scripts/cleanup-shared-group.sh b/test/scripts/cleanup-shared-group.sh index 071decd7..81910dd3 100644 --- a/test/scripts/cleanup-shared-group.sh +++ b/test/scripts/cleanup-shared-group.sh @@ -1,4 +1,14 @@ #!/bin/bash +# +# 1. Load the run configuration and reject cleanup when AFD retention is enabled. +# 2. Find run-owned resources and verify their tags, names, types and scope. +# 3. Verify VNet peerings, controller profiles, the hub identity and the AFD test principal. +# 4. Collect and validate run-owned identities, node resource groups and role assignments. +# 5. Stop hub controllers when needed and delete verified Traffic Manager and Front Door profiles. +# 6. Remove node-group role assignments, delete AKS clusters and wait for node groups to disappear. +# 7. Remove remaining role assignments, peerings, public IPs, VNets, registries and identities. +# 8. Verify that no run-owned resources or controller profiles remain, preserving the shared group. +# set -o errexit set -o nounset set -o pipefail From 4d899ea533c89a50520609e6b3e7ebcf3747b95d Mon Sep 17 00:00:00 2001 From: Wei Weng Date: Tue, 24 Nov 2026 21:15:22 +0000 Subject: [PATCH 15/16] ci: avoid SIGPIPE in Gateway image smoke test Read the full Docker log stream while checking for the disabled controller message, preserving failure when it is absent. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .github/workflows/unit-integration-tests.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/unit-integration-tests.yml b/.github/workflows/unit-integration-tests.yml index 17646499..a18111a9 100644 --- a/.github/workflows/unit-integration-tests.yml +++ b/.github/workflows/unit-integration-tests.yml @@ -161,7 +161,7 @@ jobs: --retry-delay 1 --retry-max-time 30 --connect-timeout 1 --max-time 2 \ "http://$address/$path" done - docker logs "$container" 2>&1 | grep -q 'Azure Front Door reconciliation is disabled' + docker logs "$container" 2>&1 | grep 'Azure Front Door reconciliation is disabled' >/dev/null - name: Verify registry export and pull using a loopback-only registry shell: bash From 1ebace1857a7ef44598cc6fa42fd56a15ca52b94 Mon Sep 17 00:00:00 2001 From: xuxife Date: Thu, 26 Nov 2026 03:02:30 +1100 Subject: [PATCH 16/16] test: fix shared-RG E2E for atm/afd and use the dedicated WIF connection (#461) --- .pipeline/e2e-tests.yaml | 8 ++++-- test/README.md | 11 ++++++--- test/scripts/bootstrap.sh | 42 +++++++++++++++++++++----------- test/scripts/caller-object-id.sh | 10 ++++++++ 4 files changed, 51 insertions(+), 20 deletions(-) create mode 100755 test/scripts/caller-object-id.sh diff --git a/.pipeline/e2e-tests.yaml b/.pipeline/e2e-tests.yaml index f24e173d..b22d3dd8 100644 --- a/.pipeline/e2e-tests.yaml +++ b/.pipeline/e2e-tests.yaml @@ -10,7 +10,7 @@ pr: none parameters: - name: serviceConnection type: string - default: 'aks fleetnetworking' + default: 'aks-devinfra-fleet-networking-e2e-wif' - name: scenarios type: object default: @@ -132,7 +132,9 @@ jobs: echo "error: service connection subscription does not match the E2E subscription" >&2 exit 1 fi - # E2E_TEST_PRINCIPAL_ID is a pipeline variable and must match the service connection. + # Role assignments to the test principal follow the service connection that runs this job. + E2E_TEST_PRINCIPAL_ID="$(bash test/scripts/caller-object-id.sh)" + export E2E_TEST_PRINCIPAL_ID make e2e-setup - bash: | @@ -196,4 +198,6 @@ jobs: keepAzSessionActive: true inlineScript: | set -euo pipefail + E2E_TEST_PRINCIPAL_ID="$(bash test/scripts/caller-object-id.sh)" + export E2E_TEST_PRINCIPAL_ID make e2e-cleanup diff --git a/test/README.md b/test/README.md index 19ec3746..65529304 100644 --- a/test/README.md +++ b/test/README.md @@ -39,7 +39,8 @@ export AZURE_RESOURCE_GROUP= export E2E_RUN_ID= # Recommended: use a separate kubeconfig for this run. export KUBECONFIG= -# Required only when AFD automatic approval is enabled: +# Required for Traffic Manager and for AFD automatic approval: the object ID of the signed-in +# service principal (Azure Pipelines derives it with test/scripts/caller-object-id.sh). export E2E_TEST_PRINCIPAL_ID= ``` @@ -101,7 +102,9 @@ export ENABLE_TRAFFIC_MANAGER=true The setup configures the additional AKS identities, Azure role assignments, and controller feature flags required by `test/e2e/traffic_manager_test.go`. Tests in that file skip when -`ENABLE_TRAFFIC_MANAGER` is not `true`. +`ENABLE_TRAFFIC_MANAGER` is not `true`. Because some tests update Traffic Manager endpoints that +target the members' public IPs directly, setup also grants `E2E_TEST_PRINCIPAL_ID` Network +Contributor on both member node resource groups. ### Azure Front Door and Gateway API @@ -798,5 +801,5 @@ Delete only this run's verified resources; the shared resource group remains: make e2e-cleanup ``` -Cleanup requires the same `AZURE_RESOURCE_GROUP`, `E2E_RUN_ID`, `KUBECONFIG` and, for AFD -auto-approval, `E2E_TEST_PRINCIPAL_ID` used by setup. +Cleanup requires the same `AZURE_RESOURCE_GROUP`, `E2E_RUN_ID`, `KUBECONFIG` and, for Traffic +Manager or AFD auto-approval, `E2E_TEST_PRINCIPAL_ID` used by setup. diff --git a/test/scripts/bootstrap.sh b/test/scripts/bootstrap.sh index 4cc15b20..dc67297a 100644 --- a/test/scripts/bootstrap.sh +++ b/test/scripts/bootstrap.sh @@ -24,6 +24,12 @@ if [ "$ENABLE_TRAFFIC_MANAGER" == "true" ] && [ "$AZURE_NETWORK_SETTING" != "sha exit 1 fi +if [[ "$ENABLE_TRAFFIC_MANAGER" == true && + ! "${E2E_TEST_PRINCIPAL_ID:-}" =~ ^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$ ]]; then + echo "error: Traffic Manager E2E requires E2E_TEST_PRINCIPAL_ID" >&2 + exit 1 +fi + if [[ "$ENABLE_AZURE_FRONT_DOOR" == true ]]; then for tool in az jq helm kubectl go docker; do if ! command -v "$tool" >/dev/null; then @@ -201,6 +207,10 @@ EOF echo "Assigning roles to member-1 kubelet identity on the MC_resourceGroup of the member cluster" az role assignment create --role "Network Contributor" --assignee-object-id ${MEMBER_CLUSTER_1_KUBELET_PRINCIPAL_ID} --assignee-principal-type ServicePrincipal --scope "/subscriptions/${AZURE_SUBSCRIPTION_ID}/resourceGroups/${AKS_MEMBER_1_NODE_RESOURCE_GROUP}" > /dev/null + # The tests update Traffic Manager endpoints that target this member's public IPs, which requires joining them. + echo "Assigning Network Contributor to the E2E test principal on the MC_resourceGroup of member-1" + az role assignment create --role "Network Contributor" --assignee-object-id "${E2E_TEST_PRINCIPAL_ID}" --assignee-principal-type ServicePrincipal --scope "/subscriptions/${AZURE_SUBSCRIPTION_ID}/resourceGroups/${AKS_MEMBER_1_NODE_RESOURCE_GROUP}" > /dev/null + # Creating azure configuration file for the controllers echo "Generating azure configuration file:" $(pwd)/member_1_azure_config.yaml cat << EOF > $(pwd)/member_1_azure_config.yaml @@ -223,6 +233,10 @@ EOF echo "Assigning roles to member-2 kubelet identity on the MC_resourceGroup of the member cluster" az role assignment create --role "Network Contributor" --assignee-object-id ${MEMBER_CLUSTER_2_KUBELET_PRINCIPAL_ID} --assignee-principal-type ServicePrincipal --scope "/subscriptions/${AZURE_SUBSCRIPTION_ID}/resourceGroups/${AKS_MEMBER_2_NODE_RESOURCE_GROUP}" > /dev/null + # The tests update Traffic Manager endpoints that target this member's public IPs, which requires joining them. + echo "Assigning Network Contributor to the E2E test principal on the MC_resourceGroup of member-2" + az role assignment create --role "Network Contributor" --assignee-object-id "${E2E_TEST_PRINCIPAL_ID}" --assignee-principal-type ServicePrincipal --scope "/subscriptions/${AZURE_SUBSCRIPTION_ID}/resourceGroups/${AKS_MEMBER_2_NODE_RESOURCE_GROUP}" > /dev/null + # Creating azure configuration file for the controllers echo "Generating azure configuration file:" $(pwd)/member_2_azure_config.yaml cat << EOF > $(pwd)/member_2_azure_config.yaml @@ -342,10 +356,10 @@ kubectl apply -f `go env GOPATH`/pkg/mod/go.goms.io/fleet@v0.18.16/config/crd/ba helm install hub-net-controller-manager \ ./charts/hub-net-controller-manager/ \ --set image.repository=$REGISTRY/hub-net-controller-manager \ - --set image.tag=$TAG \ + --set-string image.tag="$TAG" \ --set crdInstaller.enabled=true \ --set crdInstaller.image.repository=$REGISTRY/net-crd-installer \ - --set crdInstaller.image.tag=$TAG \ + --set-string crdInstaller.image.tag="$TAG" \ --set crdInstaller.isE2ETest=true \ $( [ "$ENABLE_TRAFFIC_MANAGER" = "true" ] && echo "--set enableTrafficManagerFeature=true -f hub_azure_config.yaml" ) @@ -354,7 +368,7 @@ kubectl config use-context $MEMBER_CLUSTER_1-admin helm install mcs-controller-manager \ ./charts/mcs-controller-manager \ --set image.repository=$REGISTRY/mcs-controller-manager \ - --set image.tag=$TAG \ + --set-string image.tag="$TAG" \ --set config.hubURL=$HUB_URL \ --set config.provider=azure \ --set config.memberClusterName=$MEMBER_CLUSTER_1 \ @@ -362,10 +376,10 @@ helm install mcs-controller-manager \ $( [ "$AZURE_NETWORK_SETTING" = "unsupported" ] && echo "--set enableNetworkingFeatures=false" ) helm install member-net-controller-manager ./charts/member-net-controller-manager/ \ --set image.repository=$REGISTRY/member-net-controller-manager \ - --set image.tag=$TAG \ + --set-string image.tag="$TAG" \ --set crdInstaller.enabled=true \ --set crdInstaller.image.repository=$REGISTRY/net-crd-installer \ - --set crdInstaller.image.tag=$TAG \ + --set-string crdInstaller.image.tag="$TAG" \ --set crdInstaller.isE2ETest=true \ --set config.hubURL=$HUB_URL \ --set config.provider=azure \ @@ -378,7 +392,7 @@ kubectl config use-context $MEMBER_CLUSTER_2-admin helm install mcs-controller-manager \ ./charts/mcs-controller-manager \ --set image.repository=$REGISTRY/mcs-controller-manager \ - --set image.tag=$TAG \ + --set-string image.tag="$TAG" \ --set config.hubURL=$HUB_URL \ --set config.provider=azure \ --set config.memberClusterName=$MEMBER_CLUSTER_2 \ @@ -386,10 +400,10 @@ helm install mcs-controller-manager \ $( [ "$AZURE_NETWORK_SETTING" = "unsupported" ] && echo "--set enableNetworkingFeatures=false" ) helm install member-net-controller-manager ./charts/member-net-controller-manager/ \ --set image.repository=$REGISTRY/member-net-controller-manager \ - --set image.tag=$TAG \ + --set-string image.tag="$TAG" \ --set crdInstaller.enabled=true \ --set crdInstaller.image.repository=$REGISTRY/net-crd-installer \ - --set crdInstaller.image.tag=$TAG \ + --set-string crdInstaller.image.tag="$TAG" \ --set crdInstaller.isE2ETest=true \ --set config.hubURL=$HUB_URL \ --set config.provider=azure \ @@ -416,17 +430,17 @@ then helm install mcs-controller-manager \ ./charts/mcs-controller-manager \ --set image.repository=$REGISTRY/mcs-controller-manager \ - --set image.tag=$TAG \ + --set-string image.tag="$TAG" \ --set config.hubURL=$HUB_URL \ --set config.provider=azure \ --set config.memberClusterName=$MEMBER_CLUSTER_3 \ --set azure.clientid=$CLIENT_ID_FOR_MEMBER_3 helm install member-net-controller-manager ./charts/member-net-controller-manager/ \ --set image.repository=$REGISTRY/member-net-controller-manager \ - --set image.tag=$TAG \ + --set-string image.tag="$TAG" \ --set crdInstaller.enabled=true \ --set crdInstaller.image.repository=$REGISTRY/net-crd-installer \ - --set crdInstaller.image.tag=$TAG \ + --set-string crdInstaller.image.tag="$TAG" \ --set crdInstaller.isE2ETest=true \ --set config.hubURL=$HUB_URL \ --set config.provider=azure \ @@ -437,17 +451,17 @@ then helm install mcs-controller-manager \ ./charts/mcs-controller-manager \ --set image.repository=$REGISTRY/mcs-controller-manager \ - --set image.tag=$TAG \ + --set-string image.tag="$TAG" \ --set config.hubURL=$HUB_URL \ --set config.provider=azure \ --set config.memberClusterName=$MEMBER_CLUSTER_4 \ --set azure.clientid=$CLIENT_ID_FOR_MEMBER_4 helm install member-net-controller-manager ./charts/member-net-controller-manager/ \ --set image.repository=$REGISTRY/member-net-controller-manager \ - --set image.tag=$TAG \ + --set-string image.tag="$TAG" \ --set crdInstaller.enabled=true \ --set crdInstaller.image.repository=$REGISTRY/net-crd-installer \ - --set crdInstaller.image.tag=$TAG \ + --set-string crdInstaller.image.tag="$TAG" \ --set crdInstaller.isE2ETest=true \ --set config.hubURL=$HUB_URL \ --set config.provider=azure \ diff --git a/test/scripts/caller-object-id.sh b/test/scripts/caller-object-id.sh new file mode 100755 index 00000000..330bf338 --- /dev/null +++ b/test/scripts/caller-object-id.sh @@ -0,0 +1,10 @@ +#!/bin/bash +# Prints the object ID of the principal the Azure CLI is signed in as, read from its ARM access token, +# so that role assignments to the E2E test principal follow the service connection that runs the job. +set -o errexit +set -o nounset +set -o pipefail + +token="$(az account get-access-token --query accessToken -o tsv)" +jq -Rr 'split(".")[1] | gsub("-"; "+") | gsub("_"; "/") | (. + "===") | .[0:(length - (length % 4))] | + @base64d | fromjson | .oid' <<<"$token"