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..aec74c5b --- /dev/null +++ b/.github/.copilot/breadcrumbs/2026-11-24-1842-shared-e2e-resource-group.md @@ -0,0 +1,83 @@ +# Shared E2E resource group + +## Requirements and decisions + +- 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). + +## 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. [x] 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 + +### 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. [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. 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. + +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. [x] 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. +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. [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. 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 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 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. + +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 + +- `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. +- The generic guide's Markdown fences are balanced and its local links resolve. +- 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/.github/workflows/e2e-tests.yml b/.github/workflows/e2e-tests.yml deleted file mode 100644 index 0d5f102a..00000000 --- a/.github/workflows/e2e-tests.yml +++ /dev/null @@ -1,141 +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: - - network-setting: shared-vnet - enable-traffic-manager: true - enable-afd: false - - network-setting: peered-vnet - enable-traffic-manager: false - enable-afd: false - - network-setting: dynamic-ip-allocation - enable-traffic-manager: false - enable-afd: false - - network-setting: unsupported - enable-traffic-manager: false - enable-afd: false - - 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 }} - 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 "AZURE_RESOURCE_GROUP=fleet-networking-e2e-$RANDOM" >> "$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 - run: | - 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: | - 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() - 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/.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 diff --git a/.pipeline/e2e-tests.yaml b/.pipeline/e2e-tests.yaml index 2a9bf5e0..b22d3dd8 100644 --- a/.pipeline/e2e-tests.yaml +++ b/.pipeline/e2e-tests.yaml @@ -8,6 +8,9 @@ trigger: pr: none parameters: + - name: serviceConnection + type: string + default: 'aks-devinfra-fleet-networking-e2e-wif' - name: scenarios type: object default: @@ -61,7 +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) }} - AZURE_RESOURCE_GROUP: 'fleet-ado-$(Build.BuildId)-$(SCENARIO)-$(System.JobAttempt)' + AZURE_RESOURCE_GROUP: 'fleet-networking-e2e' + E2E_RUN_ID: '$(Build.BuildId)-$(SCENARIO)-$(System.JobAttempt)' 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 +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; do + for tool in az docker helm kubectl jq yq make timeout sha256sum; do command -v "$tool" done go version @@ -115,7 +119,7 @@ jobs: displayName: Set up E2E environment timeoutInMinutes: 180 inputs: - azureSubscription: 'aks fleetnetworking' + azureSubscription: ${{ parameters.serviceConnection }} scriptType: bash scriptLocation: inlineScript addSpnToEnvironment: false @@ -128,12 +132,9 @@ 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" != false ]]; then - echo "error: refusing to reuse resource group $AZURE_RESOURCE_GROUP" >&2 - exit 1 - fi - echo "##vso[task.setvariable variable=e2eResourcesStarted]true" + # 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: | @@ -150,7 +151,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 @@ -173,23 +174,23 @@ 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)' artifact: 'e2e-$(SCENARIO)-$(System.JobAttempt)' - task: AzureCLI@2 - displayName: Clean up this run's resource group - condition: and(always(), eq(variables['e2eResourcesStarted'], 'true')) - timeoutInMinutes: 20 + displayName: Clean up this run's resources + condition: always() + timeoutInMinutes: 90 inputs: - azureSubscription: 'aks fleetnetworking' + azureSubscription: ${{ parameters.serviceConnection }} scriptType: bash scriptLocation: inlineScript addSpnToEnvironment: false @@ -197,21 +198,6 @@ jobs: keepAzSessionActive: true inlineScript: | set -euo pipefail - 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 + E2E_TEST_PRINCIPAL_ID="$(bash test/scripts/caller-object-id.sh)" + export E2E_TEST_PRINCIPAL_ID 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 2f5ec947..65529304 100644 --- a/test/README.md +++ b/test/README.md @@ -12,8 +12,10 @@ 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) +- `sha256sum` - 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 +28,39 @@ 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. +### Shared resource group + +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= +# Recommended: use a separate kubeconfig for this run. +export KUBECONFIG= +# 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= +``` + +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 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. + +`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. + +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 All scenarios use the same setup, test, and cleanup targets. The environment variables determine @@ -67,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 @@ -472,8 +509,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. @@ -590,6 +627,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 \ @@ -693,10 +731,9 @@ 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 -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 -particular live run passed. +The [E2E pipeline](../.pipeline/e2e-tests.yaml) enables ATM for the shared-VNet +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 @@ -742,6 +779,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' ``` @@ -757,10 +795,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 Traffic +Manager or 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 93b0470b..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,12 +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 { - resourceGroupName := os.Getenv("AZURE_RESOURCE_GROUP") - registryName := strings.ReplaceAll(resourceGroupName, "-", "") - return fmt.Sprintf("%s.azurecr.io/app", registryName) + registry := os.Getenv("REGISTRY") + if registry == "" { + panic("REGISTRY is required for E2E workload images") + } + return fmt.Sprintf("%s/app", registry) } // UniqueTestNamespace gives a unique namespace name. func UniqueTestNamespace() string { - return fmt.Sprintf("%s-%s", TestNamespacePrefix, 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", prefix, 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..1d5b1dfe --- /dev/null +++ b/test/e2e/framework/workload_manager_test.go @@ -0,0 +1,53 @@ +/* +Copyright (c) Microsoft Corporation. +Licensed under the MIT license. +*/ + +package framework + +import ( + "strings" + "testing" + + "k8s.io/apimachinery/pkg/util/validation" +) + +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 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() + }) +} diff --git a/test/e2e/traffic_manager_test.go b/test/e2e/traffic_manager_test.go index a9f0fc45..fc2d861b 100644 --- a/test/e2e/traffic_manager_test.go +++ b/test/e2e/traffic_manager_test.go @@ -618,7 +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)) + 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 +632,9 @@ var _ = Describe("Test exporting service via Azure traffic manager", Ordered, fu Name: ptr.To(armnetwork.PublicIPAddressSKUNameStandard), }, } + 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..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 @@ -206,7 +281,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 +429,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 e0c4ee23..fa6f9b45 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" @@ -14,86 +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 { - Network string `json:"network-setting"` - ATM bool `json:"enable-traffic-manager"` - AFD bool `json:"enable-afd"` - } - } - } - Steps []struct { - Name 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" { - t.Fatal("AFD selection, exact test approvals and ordinary cleanup must reach the entire job") - } - scenarios := make(map[string]bool) - for _, row := range job.Strategy.Matrix.Include { - 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) - } - } - 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 "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) - } - } - } - } -} - func TestAFDConfiguration(t *testing.T) { tests := []struct { name, enabled, network, group, want string @@ -159,7 +83,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 +105,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 +167,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,18 +237,18 @@ 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" ;; "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 ` @@ -344,13 +266,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,6 +295,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_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", @@ -384,9 +308,22 @@ func afdTestEnvironment(t *testing.T) { 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 4980b118..f06c8687 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}-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..e1f6caae 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}-member-1-vnet" export MEMBER_1_SUBNET=member-1-subnet -export MEMBER_2_VNET=member-2-vnet +export MEMBER_2_VNET="${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..d899be35 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}-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..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 @@ -36,28 +42,21 @@ 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}" -az group create --name $RESOURCE_GROUP --location $LOCATION --tags "source=fleet-networking" -# Defer function to recycle created Azure resource. -function cleanup { - az group delete -n $RESOURCE_GROUP --no-wait --yes -} 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 else - trap cleanup INT TERM + 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 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" +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, @@ -69,40 +68,28 @@ 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}" 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 +101,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 +109,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 +124,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') @@ -170,8 +157,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 @@ -184,22 +169,22 @@ 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 - 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 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 +198,18 @@ 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 + + # 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 @@ -235,14 +224,18 @@ 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 + + # 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 @@ -258,29 +251,30 @@ 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 +# 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_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" --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 # 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') - 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 @@ -362,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" ) @@ -374,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 \ @@ -382,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 \ @@ -398,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 \ @@ -406,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 \ @@ -436,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 \ @@ -457,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" diff --git a/test/scripts/cleanup-shared-group.sh b/test/scripts/cleanup-shared-group.sh new file mode 100644 index 00000000..81910dd3 --- /dev/null +++ b/test/scripts/cleanup-shared-group.sh @@ -0,0 +1,313 @@ +#!/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 + +source "$(dirname "${BASH_SOURCE[0]}")/e2e-config.sh" +if [[ "$RETAIN_AFD_E2E_SETUP" == true ]]; then + echo "error: shared cleanup requires non-retained setup" >&2 + exit 1 +fi + +group_id="/subscriptions/$AZURE_SUBSCRIPTION_ID/resourceGroups/$AZURE_RESOURCE_GROUP" +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 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 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 + (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 + 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 + # 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}')" + 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..0e13c2c0 100644 --- a/test/scripts/cleanup.sh +++ b/test/scripts/cleanup.sh @@ -16,6 +16,4 @@ case "${RETAIN_AFD_E2E_SETUP:-false}" in ;; esac -[[ -z "${AZURE_RESOURCE_GROUP}" ]] && echo "AZURE_RESOURCE_GROUP is not set" && exit 1 - -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 5394ee0a..23266bcf 100644 --- a/test/scripts/e2e-config.sh +++ b/test/scripts/e2e-config.sh @@ -5,6 +5,42 @@ 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}" +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 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 return 1 @@ -33,6 +69,16 @@ if [[ "$ENABLE_AZURE_FRONT_DOOR" == true ]]; then echo "error: AFD requires AZURE_SUBSCRIPTION_ID and AZURE_RESOURCE_GROUP" >&2 return 1 fi + 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 [[ "${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 @@ -40,8 +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. - export REGISTRY="${AZURE_RESOURCE_GROUP//-}.azurecr.io" if [[ -z "${TAG:-}" ]]; then TAG="$(git rev-parse --short=7 HEAD)" || return 1 export TAG @@ -50,3 +94,10 @@ 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 + +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 35b43101..c02e00fe 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 [[ "$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/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[@]}"