name: argocd-promote-helm on: workflow_call: inputs: name: type: string required: false promotion_chart_path: type: string required: false default: ".gitops/promote/helm" destination_path: type: string required: false default: ".gitops/deploy/helm/templates" project: type: string required: true environment_name: type: string required: true environment_repository: type: string required: true promotion_pr: type: boolean required: false default: false description: "If true, creates a PR in the environment repository instead of pushing directly" promotion_mode: type: string required: false default: "" description: "Promotion mode: direct, pull-request, or pull-request-merge. When set, overrides promotion_pr and create_pull_request." create_pull_request: type: boolean required: false description: "DEPRECATED: Use promotion_pr instead. Kept for backwards compatibility." values: type: string required: false default: "" merge_existing_values: type: boolean required: false default: true description: "Merge previously deployed runtime values. Set false for authoritative values, so omitted keys are removed." preview: type: boolean required: false default: false description: "If true, creates a preview environment. Mode is auto-detected: PR events use PR-style previews, push events use branch-style previews." comment: required: false type: string default: "" description: "Comment body for preview PRs. Leave empty to use default." preview_urls: required: false type: string default: "" description: "Newline-delimited public HTTPS URLs to wait for before publishing the preview comment. All URLs must become reachable." preview_readiness_timeout_seconds: required: false type: number default: 1200 description: "Maximum time to wait for every preview URL to become reachable. Must be between 1 and 3600 seconds." dry_run: required: false type: boolean default: false description: "If true, skip commit and push steps (useful for testing)" auth_mode: required: false type: string default: "pat" description: "Authentication mode: 'pat' for Personal Access Token (requires GH_PAT secret), 'app' for GitHub App (requires GH_APP_ID and GH_APP_KEY secrets)" secrets: GH_PAT: required: false description: "Personal Access Token for authentication. Required if GH_APP_ID is not provided." GH_APP_ID: required: false description: "GitHub App ID for authentication. If provided with GH_APP_KEY secret, uses GitHub App token instead of GH_PAT." GH_APP_KEY: required: false description: "GitHub App private key. Required if GH_APP_ID is provided." jobs: argocd-promote-helm: runs-on: ubuntu-latest environment: name: ${{ inputs.environment_name }} url: https://github.com/${{ inputs.environment_repository }} permissions: contents: write issues: write pull-requests: write steps: - name: Resolve Configuration id: config uses: actions/github-script@v9 env: INPUT_NAME: ${{ inputs.name }} INPUT_PROJECT: ${{ inputs.project }} INPUT_PREVIEW: ${{ inputs.preview }} INPUT_PROMOTION_PR: ${{ inputs.promotion_pr }} INPUT_PROMOTION_MODE: ${{ inputs.promotion_mode }} INPUT_CREATE_PULL_REQUEST: ${{ inputs.create_pull_request }} INPUT_DESTINATION_PATH: ${{ inputs.destination_path }} INPUT_PREVIEW_URLS: ${{ inputs.preview_urls }} INPUT_DRY_RUN: ${{ inputs.dry_run }} with: script: | // Helper: sanitize string for k8s (lowercase, alphanumeric and hyphens only) const sanitize = (str) => str .toLowerCase() .replace(/[^a-z0-9-]/g, '-') .replace(/-+/g, '-') .replace(/^-|-$/g, ''); // Get inputs from env (workflow inputs aren't directly available in github-script) const legacyPromotionPR = process.env.INPUT_PROMOTION_PR === 'true' || process.env.INPUT_CREATE_PULL_REQUEST === 'true'; const requestedPromotionMode = process.env.INPUT_PROMOTION_MODE.trim(); const validPromotionModes = ['direct', 'pull-request', 'pull-request-merge']; if (requestedPromotionMode && !validPromotionModes.includes(requestedPromotionMode)) { core.setFailed(`Invalid promotion_mode: ${requestedPromotionMode}. Expected one of: ${validPromotionModes.join(', ')}`); return; } const promotionMode = requestedPromotionMode || (legacyPromotionPR ? 'pull-request' : 'direct'); const inputs = { name: process.env.INPUT_NAME, project: process.env.INPUT_PROJECT, preview: process.env.INPUT_PREVIEW === 'true', promotionMode, promotionPR: promotionMode !== 'direct', destinationPath: process.env.INPUT_DESTINATION_PATH, hasPreviewUrls: process.env.INPUT_PREVIEW_URLS.trim() !== '', dryRun: process.env.INPUT_DRY_RUN === 'true', }; if (inputs.preview && inputs.hasPreviewUrls && inputs.promotionMode === 'pull-request' && !inputs.dryRun) { core.setFailed('preview_urls cannot be checked with promotion_mode=pull-request because the environment change is not merged by this workflow'); return; } // Detect mode and type const pullRequestEvents = ['pull_request', 'pull_request_target']; const isPullRequestEvent = pullRequestEvents.includes(context.eventName); const pr = context.payload.pull_request; if (isPullRequestEvent && !pr) { core.setFailed(`Missing pull request payload for ${context.eventName}`); return; } const baseRepository = `${context.repo.owner}/${context.repo.repo}`; const headRepository = pr?.head?.repo?.full_name; if (isPullRequestEvent && headRepository !== baseRepository) { core.setFailed(`Fork pull requests are not supported: expected ${baseRepository}, received ${headRepository || 'unknown'}`); return; } const mode = isPullRequestEvent ? 'pr' : 'push'; const type = inputs.preview ? 'preview' : 'release'; const repoName = inputs.name || context.repo.repo; // Compute config based on type and mode let config; if (type === 'release') { const refName = context.ref.replace('refs/heads/', '').replace('refs/tags/', ''); const isTag = context.ref.startsWith('refs/tags/'); const sourceInfo = isTag ? `https://github.com/${context.repo.owner}/${context.repo.repo}/releases/tag/${refName}` : `https://github.com/${context.repo.owner}/${context.repo.repo}/tree/${refName}`; config = { name: repoName, fileName: repoName, targetRevision: refName, namespace: inputs.project, imageTag: '', sourceInfo, }; } else if (mode === 'pr') { const name = `${repoName}-pr-${pr.number}`; config = { name, fileName: `${repoName}-pr-${pr.number}`, targetRevision: pr.head.ref, namespace: name, imageTag: `pr-${pr.number}-${pr.head.sha}`, sourceInfo: pr.html_url, }; } else { // Preview + Push: sanitize for k8s compatibility // Truncate repo part first to leave room for separator and branch const repoPart = sanitize(repoName).slice(0, 62).replace(/-$/, ''); const maxBranchLen = Math.max(0, 63 - repoPart.length - 1); const refName = context.ref.replace('refs/heads/', ''); const sanitizedBranch = sanitize(refName).slice(0, maxBranchLen).replace(/-$/, ''); const name = sanitizedBranch ? `${repoPart}-${sanitizedBranch}` : repoPart; config = { name, fileName: name, targetRevision: refName, namespace: name, imageTag: sanitizedBranch ? `${sanitizedBranch}-${context.sha}` : context.sha, sourceInfo: `https://github.com/${context.repo.owner}/${context.repo.repo}/tree/${refName}`, }; } // Add derived values const refName = context.ref.replace('refs/heads/', '').replace('refs/tags/', ''); config.argoName = `${inputs.project}-${config.name}`; config.destinationYaml = `environment/${inputs.destinationPath}/${config.fileName}.yaml`; // Compute commit message config.commitMessage = type === 'release' ? `feat(${config.name}): promote to ${config.sourceInfo}` : `feat(${context.repo.repo}): preview ${config.sourceInfo}`; // Compute PR config (if promotion PR is enabled) if (inputs.promotionPR) { if (type === 'release') { config.prTitle = `Promote ${config.name} to ${refName}`; config.prBody = `Promotes ${config.name} to ${config.sourceInfo}`; config.prBranch = `promote/${config.name}-${refName}`; } else { config.prTitle = `Preview ${config.name}`; config.prBody = `Preview environment for ${config.sourceInfo}`; config.prBranch = `preview/${config.name}`; } } // Set outputs (camelCase -> snake_case for consistency) const outputs = { mode, type, promotion_mode: inputs.promotionMode, promotion_pr: inputs.promotionPR, name: config.name, file_name: config.fileName, argo_name: config.argoName, destination_yaml: config.destinationYaml, target_revision: config.targetRevision, namespace: config.namespace, image_tag: config.imageTag, source_info: config.sourceInfo, }; for (const [key, value] of Object.entries(outputs)) { core.setOutput(key, value); } // Set env vars for steps that need them const envVars = { NAME: config.name, FILE_NAME: config.fileName, ARGO_NAME: config.argoName, DESTINATION_YAML: config.destinationYaml, COMMIT_MESSAGE: config.commitMessage, ...(inputs.promotionPR && { PR_TITLE: config.prTitle, PR_BODY: config.prBody, PR_BRANCH: config.prBranch, }), }; for (const [key, value] of Object.entries(envVars)) { core.exportVariable(key, value); } // Log config for debugging core.info('Resolved configuration:'); core.info(JSON.stringify({ ...outputs, ...envVars }, null, 2)); - name: Generate GitHub App Token if: inputs.auth_mode == 'app' id: generate-token uses: actions/create-github-app-token@v3 with: app-id: ${{ secrets.GH_APP_ID }} private-key: ${{ secrets.GH_APP_KEY }} owner: ${{ github.repository_owner }} - name: Resolve Auth Token id: auth env: APP_TOKEN: ${{ steps.generate-token.outputs.token }} PAT_TOKEN: ${{ secrets.GH_PAT }} AUTH_MODE: ${{ inputs.auth_mode }} run: | if [ "$AUTH_MODE" = "app" ]; then echo "token=$APP_TOKEN" >> $GITHUB_OUTPUT else echo "token=$PAT_TOKEN" >> $GITHUB_OUTPUT fi - name: Checkout repository uses: actions/checkout@v7 - name: Checkout Environment Project uses: actions/checkout@v7 with: path: environment repository: ${{ inputs.environment_repository }} token: ${{ steps.auth.outputs.token }} - name: "[Preview][Promotion PR] Create or Checkout Preview Branch" if: inputs.preview && steps.config.outputs.promotion_pr == 'true' env: PR_BRANCH: ${{ env.PR_BRANCH }} run: | cd environment git fetch origin $PR_BRANCH || git checkout -b $PR_BRANCH git checkout $PR_BRANCH - name: Save Existing Argo Application Values id: save_values env: ARGO_NAME: ${{ env.ARGO_NAME }} DESTINATION_YAML: ${{ env.DESTINATION_YAML }} run: | echo "{}" > existing_values.yaml echo "Checking for existing values from Application ${{ env.ARGO_NAME }} in destination file ${{ env.DESTINATION_YAML }}" if [ -f "${{ env.DESTINATION_YAML }}" ]; then echo "Destination file ${{ env.DESTINATION_YAML }} exists:" cat "${{ env.DESTINATION_YAML }}" echo "Finding Application: ${{ env.ARGO_NAME }} in destination file..." EXISTING_APPLICATION=$(yq eval 'select(.kind == "Application" and .metadata.name == "'${{ env.ARGO_NAME }}'")' "${{ env.DESTINATION_YAML }}") # Check if application was found if [ -z "$EXISTING_APPLICATION" ] || [ "$EXISTING_APPLICATION" = "null" ]; then echo "No Application found with name: ${{ env.ARGO_NAME }}" else echo "Found Application: ${{ env.ARGO_NAME }}" # Extract existing values from the destination file EXISTING_VALUES=$(echo "$EXISTING_APPLICATION" | yq eval '.spec.source.helm.values' -) if [ "$EXISTING_VALUES" != "null" ] && [ -n "$EXISTING_VALUES" ]; then echo "Existing values:" echo "$EXISTING_VALUES" # Create temporary files for the values echo "$EXISTING_VALUES" > existing_values.yaml else echo "No existing values found, using only new values." fi fi else echo "Destination file does not exist, using only new values." fi - name: Create Argo Application in Environment From Helm Chart env: NAME: ${{ env.NAME }} DESTINATION_YAML: ${{ env.DESTINATION_YAML }} TARGET_REVISION: ${{ steps.config.outputs.target_revision }} NAMESPACE: ${{ steps.config.outputs.namespace }} IMAGE_TAG: ${{ steps.config.outputs.image_tag }} run: | mkdir -p environment/${{ inputs.destination_path }} # A values file preserves revisions containing Helm --set delimiters. jq -n \ --arg targetRevision "$TARGET_REVISION" \ '{application: {targetRevision: $targetRevision}}' \ > target-revision-values.json # Build preview-specific flags PREVIEW_FLAGS="" if [ "${{ inputs.preview }}" == "true" ]; then PREVIEW_FLAGS="--set preview=true --set application.image.tag=${IMAGE_TAG}" fi helm template ${{ inputs.promotion_chart_path }} \ --values target-revision-values.json \ --set application.name=${{ env.NAME }} \ --set application.repository=https://github.com/${{ github.repository }}.git \ --set application.destination.namespace=${NAMESPACE} \ --set project=${{ inputs.project }} \ --set-literal application.values="${{ inputs.values }}" \ ${PREVIEW_FLAGS} \ > "${{ env.DESTINATION_YAML }}" cat "${{ env.DESTINATION_YAML }}" - name: Store New Argo Application Values id: store_new_values env: ARGO_NAME: ${{ env.ARGO_NAME }} DESTINATION_YAML: ${{ env.DESTINATION_YAML }} run: | NEW_VALUES="" cat "${{ env.DESTINATION_YAML }}" echo "Finding Application ${{ env.ARGO_NAME }} in rendered template..." APPLICATION=$(yq eval 'select(.kind == "Application" and .metadata.name == "'${{ env.ARGO_NAME }}'")' "${{ env.DESTINATION_YAML }}") if [ -z "$APPLICATION" ] || [ "$APPLICATION" = "null" ]; then echo "No Application found with name: ${{ env.ARGO_NAME }}" else echo "Found Application: ${{ env.ARGO_NAME }}" NEW_VALUES=$(echo "$APPLICATION" | yq eval '.spec.source.helm.values' -) if [ -z "$NEW_VALUES" ] || [ "$NEW_VALUES" = "null" ]; then echo "No helm values found in Application ${{ env.ARGO_NAME }}" echo "{}" > new_values.yaml else echo "$NEW_VALUES" > new_values.yaml fi fi echo "New values:" cat new_values.yaml - name: Merge Argo Application Values id: merge_values env: MERGE_EXISTING_VALUES: ${{ inputs.merge_existing_values }} run: | if [ "$MERGE_EXISTING_VALUES" = "true" ]; then # Preserve existing callers' behavior: new values override matching keys. MERGED_VALUES=$(yq eval-all 'select(fileIndex == 0) * select(fileIndex == 1)' existing_values.yaml new_values.yaml | yq '.' --prettyPrint --no-colors) else # A complete preview render is authoritative. Do not resurrect keys removed by reset. MERGED_VALUES=$(yq '.' new_values.yaml --prettyPrint --no-colors) fi if [ -z "$MERGED_VALUES" ] || [ "$MERGED_VALUES" = "null" ]; then MERGED_VALUES="{}" fi echo "$MERGED_VALUES" > merged_values.yaml if [ "$MERGE_EXISTING_VALUES" = "false" ] || [ "$MERGED_VALUES" != "{}" ]; then # Replacement must also write {}, otherwise a reset to defaults retains old values. echo "has_values=true" >> "$GITHUB_OUTPUT" else echo "has_values=false" >> "$GITHUB_OUTPUT" fi echo "Merged values:" cat merged_values.yaml - name: Replace values with merged values if: steps.merge_values.outputs.has_values == 'true' env: DESTINATION_YAML: ${{ env.DESTINATION_YAML }} ARGO_NAME: ${{ env.ARGO_NAME }} run: | echo "Replacing values in the generated YAML file with merged values" echo "Checking for destination file: ${{ env.DESTINATION_YAML }}" if [ -f "${{ env.DESTINATION_YAML }}" ]; then echo "Destination file exists, finding existing application..." EXISTING_APPLICATION=$(yq eval 'select(.kind == "Application" and .metadata.name == "'${{ env.ARGO_NAME }}'")' "${{ env.DESTINATION_YAML }}") # Update the Application's helm values with merged values yq eval '(select(.kind == "Application" and .metadata.name == "'${{ env.ARGO_NAME }}'").spec.source.helm.values) = strload("merged_values.yaml")' -i "${{ env.DESTINATION_YAML }}" echo "Successfully replaced values in ${{ env.DESTINATION_YAML }} with merged values" else echo "Destination file does not exist, using only new values." fi cat "$DESTINATION_YAML" - name: Commit Environment Changes id: commit_changes env: COMMIT_MESSAGE: ${{ env.COMMIT_MESSAGE }} DESTINATION_YAML: ${{ env.DESTINATION_YAML }} run: | cd environment if output=$(git status --porcelain) && [ -z "$output" ]; then # Working directory clean echo "No changes to commit" echo "committed_changes=false" >> $GITHUB_OUTPUT else # Uncommitted changes echo "has_changes=true" >> $GITHUB_OUTPUT # Stage files to show diff for new files (intent to add) git add -N . # Capture diff for dry run reporting (includes new files now) { echo 'diff<> $GITHUB_OUTPUT # Capture output file content (strip environment/ prefix since we've cd'd into it) OUTPUT_FILE_PATH=$(echo "${{ env.DESTINATION_YAML }}" | sed 's@^environment/@@') { echo 'output_file</dev/null || echo "File not found" echo 'EOF' } >> $GITHUB_OUTPUT if [ "${{ inputs.dry_run }}" == "true" ]; then echo "[DRY RUN] Would commit changes with message: ${{ env.COMMIT_MESSAGE }}" echo "committed_changes=false" >> $GITHUB_OUTPUT git status git diff else git config --local user.email "github-actions[bot]@users.noreply.github.com" git config --local user.name "github-actions[bot]" git add -A git commit -m "${{ env.COMMIT_MESSAGE }}" echo "committed_changes=true" >> $GITHUB_OUTPUT fi fi - name: Log Push / PR Details run: | echo "Dry Run: ${{ inputs.dry_run }}" echo "Has Changes: ${{ steps.commit_changes.outputs.has_changes }}" echo "Changes committed: ${{ steps.commit_changes.outputs.committed_changes }}" echo "Promotion mode: ${{ steps.config.outputs.promotion_mode }}" echo "Promotion PR: ${{ steps.config.outputs.promotion_pr }}" echo "Preview: ${{ inputs.preview }}" echo "Event Type: ${{ github.event_name }}" - name: "[Promotion] Push Environment Changes" if: inputs.dry_run == false && steps.config.outputs.promotion_pr != 'true' && steps.commit_changes.outputs.committed_changes == 'true' env: GH_TOKEN: ${{ steps.auth.outputs.token }} run: | cd environment # Detect default branch from remote with fallback DEFAULT_BRANCH=$(git symbolic-ref refs/remotes/origin/HEAD 2>/dev/null | sed 's@^refs/remotes/origin/@@') if [ -z "$DEFAULT_BRANCH" ]; then # Fallback: query remote directly DEFAULT_BRANCH=$(git ls-remote --symref origin HEAD 2>/dev/null | grep '^ref:' | sed 's@^ref: refs/heads/@@' | sed 's@\s.*@@') fi if [ -z "$DEFAULT_BRANCH" ]; then # Last resort fallback DEFAULT_BRANCH="main" echo "Warning: Could not detect default branch, falling back to 'main'" fi echo "Pushing to default branch: ${DEFAULT_BRANCH}" git push https://x-access-token:${{ steps.auth.outputs.token }}@github.com/${{ inputs.environment_repository }}.git HEAD:refs/heads/${DEFAULT_BRANCH} - name: "[Dry Run][Promotion] Push Environment Changes" if: inputs.dry_run && steps.config.outputs.promotion_pr != 'true' && steps.commit_changes.outputs.has_changes == 'true' run: | echo "[DRY RUN] Would push changes to ${{ inputs.environment_repository }}" - name: "[Release][Promotion PR] Create Pull Request" if: inputs.dry_run == false && steps.config.outputs.promotion_pr == 'true' && inputs.preview == false && steps.commit_changes.outputs.committed_changes == 'true' uses: peter-evans/create-pull-request@v8 env: PR_TITLE: ${{ env.PR_TITLE }} PR_BODY: ${{ env.PR_BODY }} PR_BRANCH: ${{ env.PR_BRANCH }} with: path: environment branch: ${{ env.PR_BRANCH }} token: ${{ steps.auth.outputs.token }} title: ${{ env.PR_TITLE }} body: ${{ env.PR_BODY }} - name: "[Dry Run][Release][Promotion PR] Create Pull Request" if: inputs.dry_run && steps.config.outputs.promotion_pr == 'true' && inputs.preview == false && steps.commit_changes.outputs.has_changes == 'true' env: PR_TITLE: ${{ env.PR_TITLE }} PR_BODY: ${{ env.PR_BODY }} PR_BRANCH: ${{ env.PR_BRANCH }} run: | echo "[DRY RUN] Would create PR in ${{ inputs.environment_repository }}" echo " Title: ${{ env.PR_TITLE }}" echo " Branch: ${{ env.PR_BRANCH }}" echo " Body: ${{ env.PR_BODY }}" - name: "[Preview][Promotion PR] Push to Branch" if: inputs.dry_run == false && steps.config.outputs.promotion_pr == 'true' && inputs.preview && steps.commit_changes.outputs.committed_changes == 'true' env: GH_TOKEN: ${{ steps.auth.outputs.token }} PR_BRANCH: ${{ env.PR_BRANCH }} run: | cd environment git push https://x-access-token:${{ steps.auth.outputs.token }}@github.com/${{ inputs.environment_repository }}.git HEAD:refs/heads/${{ env.PR_BRANCH }} - name: "[Dry Run][Preview][Promotion PR] Push to Branch" if: inputs.dry_run && steps.config.outputs.promotion_pr == 'true' && inputs.preview && steps.commit_changes.outputs.has_changes == 'true' env: PR_BRANCH: ${{ env.PR_BRANCH }} run: | echo "[DRY RUN] Would push changes to ${{ inputs.environment_repository }} branch ${{ env.PR_BRANCH }}" - name: "[Preview][Promotion PR] Create Pull Request" if: inputs.dry_run == false && steps.config.outputs.promotion_pr == 'true' && inputs.preview && steps.commit_changes.outputs.committed_changes == 'true' env: GH_TOKEN: ${{ steps.auth.outputs.token }} PR_TITLE: ${{ env.PR_TITLE }} PR_BODY: ${{ env.PR_BODY }} PR_BRANCH: ${{ env.PR_BRANCH }} run: | cd environment # Detect default branch from remote with fallback DEFAULT_BRANCH=$(git symbolic-ref refs/remotes/origin/HEAD 2>/dev/null | sed 's@^refs/remotes/origin/@@') if [ -z "$DEFAULT_BRANCH" ]; then # Fallback: query remote directly DEFAULT_BRANCH=$(git ls-remote --symref origin HEAD 2>/dev/null | grep '^ref:' | sed 's@^ref: refs/heads/@@' | sed 's@\s.*@@') fi if [ -z "$DEFAULT_BRANCH" ]; then # Last resort fallback DEFAULT_BRANCH="main" echo "Warning: Could not detect default branch, falling back to 'main'" fi # Check if PR already exists EXISTING_PR=$(gh pr list --head ${{ env.PR_BRANCH }} --repo ${{ inputs.environment_repository }} --json number --jq '.[0].number' || echo "") if [ -n "$EXISTING_PR" ]; then echo "PR already exists with head branch ${{ env.PR_BRANCH }} (PR #$EXISTING_PR), skipping creation" else echo "Creating new PR with head branch ${{ env.PR_BRANCH }} targeting ${DEFAULT_BRANCH}" gh pr create --repo ${{ inputs.environment_repository }} --title "${{ env.PR_TITLE }}" --body "${{ env.PR_BODY }}" --base ${DEFAULT_BRANCH} --head ${{ env.PR_BRANCH }} fi - name: "[Promotion PR] Merge Pull Request" if: inputs.dry_run == false && steps.config.outputs.promotion_mode == 'pull-request-merge' && steps.commit_changes.outputs.committed_changes == 'true' env: GH_TOKEN: ${{ steps.auth.outputs.token }} PR_BRANCH: ${{ env.PR_BRANCH }} run: | PR_NUMBER=$(gh pr list \ --repo ${{ inputs.environment_repository }} \ --head "${PR_BRANCH}" \ --state open \ --json number \ --jq '.[0].number') if [ -z "${PR_NUMBER}" ]; then echo "No open promotion PR found for branch ${PR_BRANCH}" exit 1 fi echo "Squash-merging promotion PR #${PR_NUMBER}" gh pr merge "${PR_NUMBER}" \ --repo ${{ inputs.environment_repository }} \ --squash \ --delete-branch - name: "[Dry Run][Preview][Promotion PR] Create Pull Request" if: inputs.dry_run && steps.config.outputs.promotion_pr == 'true' && inputs.preview && steps.commit_changes.outputs.has_changes == 'true' env: PR_TITLE: ${{ env.PR_TITLE }} PR_BODY: ${{ env.PR_BODY }} PR_BRANCH: ${{ env.PR_BRANCH }} run: | echo "[DRY RUN] Would create PR in ${{ inputs.environment_repository }}" echo " Title: ${{ env.PR_TITLE }}" echo " Branch: ${{ env.PR_BRANCH }}" echo " Body: ${{ env.PR_BODY }}" - name: "[PR Event] Set Comment Identifier" if: steps.config.outputs.mode == 'pr' && (inputs.dry_run || inputs.preview) id: comment_id run: | # Auto-generate unique identifier based on project and config IDENTIFIER="argocd-promote-helm-${{ inputs.project }}-${{ inputs.preview && 'preview' || 'release' }}-${{ steps.config.outputs.promotion_pr == 'true' && 'promotion-pr' || 'promotion' }}" echo "identifier=${IDENTIFIER}" >> $GITHUB_OUTPUT - name: "[PR Event] Find Comment" if: steps.config.outputs.mode == 'pr' && (inputs.dry_run || inputs.preview) uses: peter-evans/find-comment@v4 id: fc with: issue-number: ${{ github.event.pull_request.number }} comment-author: 'github-actions[bot]' body-includes: ${{ steps.comment_id.outputs.identifier }} - name: "[Preview][PR Event] Mark Preview as Provisioning" if: inputs.dry_run == false && inputs.preview && inputs.preview_urls != '' && steps.config.outputs.mode == 'pr' uses: peter-evans/create-or-update-comment@v5 with: comment-id: ${{ steps.fc.outputs.comment-id }} issue-number: ${{ github.event.pull_request.number }} body: | Preview promotion is complete. Waiting for public DNS and TLS to finish provisioning… edit-mode: replace - name: "[Preview][PR Event] Wait for Public URLs" if: inputs.dry_run == false && inputs.preview && inputs.preview_urls != '' && steps.config.outputs.mode == 'pr' id: wait_for_preview_urls continue-on-error: true uses: actions/github-script@v9 env: PREVIEW_URLS: ${{ inputs.preview_urls }} PREVIEW_READINESS_TIMEOUT_SECONDS: ${{ inputs.preview_readiness_timeout_seconds }} with: script: | const { Resolver } = require('node:dns').promises; const https = require('node:https'); const net = require('node:net'); const fail = (type, message, pendingUrls = []) => { core.setOutput('failure_type', type); core.setOutput('failure_message', message); core.setOutput('pending_urls', pendingUrls.join('\n')); core.setFailed(message); }; const timeoutSeconds = Number(process.env.PREVIEW_READINESS_TIMEOUT_SECONDS); if (!Number.isInteger(timeoutSeconds) || timeoutSeconds < 1 || timeoutSeconds > 3600) { fail('validation', 'preview_readiness_timeout_seconds must be an integer between 1 and 3600'); return; } const rawUrls = process.env.PREVIEW_URLS .split(/\r?\n/) .map((value) => value.trim()) .filter(Boolean); const uniqueUrls = [...new Set(rawUrls)]; if (uniqueUrls.length === 0) { fail('validation', 'preview_urls must contain at least one non-empty URL'); return; } if (uniqueUrls.length > 20) { fail('validation', 'preview_urls supports at most 20 URLs'); return; } let endpoints; try { endpoints = uniqueUrls.map((value) => { let url; try { url = new URL(value); } catch { throw new Error(`Invalid preview URL: ${value}`); } if (url.protocol !== 'https:') { throw new Error(`Preview URL must use HTTPS: ${value}`); } if (url.username || url.password) { throw new Error(`Preview URL must not contain credentials: ${value}`); } if (url.port && url.port !== '443') { throw new Error(`Preview URL must use port 443: ${value}`); } if (net.isIP(url.hostname) !== 0) { throw new Error(`Preview URL must use a DNS hostname: ${value}`); } return { value, url }; }); } catch (error) { fail('validation', error.message); return; } const isPublicIpv4 = (address) => { const octets = address.split('.').map(Number); if (octets.length !== 4 || octets.some((part) => !Number.isInteger(part) || part < 0 || part > 255)) { return false; } const [a, b] = octets; return !( a === 0 || a === 10 || a === 127 || (a === 100 && b >= 64 && b <= 127) || (a === 169 && b === 254) || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 0) || (a === 192 && b === 168) || (a === 198 && (b === 18 || b === 19)) || a >= 224 ); }; const remainingMilliseconds = (deadline) => Math.max(0, deadline - Date.now()); const resolvePublicAddresses = async (hostname, deadline) => { const resolver = new Resolver(); resolver.setServers(['1.1.1.1', '1.0.0.1']); const timeoutMilliseconds = remainingMilliseconds(deadline); if (timeoutMilliseconds === 0) { throw new Error('readiness deadline exceeded'); } const timer = setTimeout(() => resolver.cancel(), timeoutMilliseconds); let answers; try { answers = await resolver.resolve4(hostname); } finally { clearTimeout(timer); } const addresses = [...new Set(answers)].filter(isPublicIpv4); if (addresses.length === 0) { throw new Error(`${hostname} has no public A records`); } return addresses; }; const probe = (endpoint, address, deadline) => new Promise((resolve, reject) => { const timeoutMilliseconds = Math.min(10_000, remainingMilliseconds(deadline)); if (timeoutMilliseconds === 0) { reject(new Error('readiness deadline exceeded')); return; } const request = https.request(endpoint.url, { method: 'HEAD', headers: { 'user-agent': 'hops-ops/workflows-gitops preview-readiness', }, lookup: (_hostname, options, callback) => { if (options?.all) { callback(null, [{ address, family: 4 }]); } else { callback(null, address, 4); } }, }, (response) => { clearTimeout(timer); response.resume(); const status = response.statusCode || 0; if (status >= 200 && status < 500) { resolve(status); } else { reject(new Error(`HTTP ${status || 'unknown'}`)); } }); const timer = setTimeout( () => request.destroy(new Error('request timed out or readiness deadline exceeded')), timeoutMilliseconds, ); request.on('error', (error) => { clearTimeout(timer); reject(error); }); request.end(); }); const checkEndpoint = async (endpoint, deadline) => { const addresses = await resolvePublicAddresses(endpoint.url.hostname, deadline); try { return await Promise.any(addresses.map(async (address) => { const status = await probe(endpoint, address, deadline); return { ready: true, status, address }; })); } catch (error) { const failures = (error.errors || []).map((failure, index) => ( `${addresses[index]}: ${failure.message}` )); throw new Error(failures.join('; ') || error.message); } }; const deadline = Date.now() + timeoutSeconds * 1000; const pending = new Map(endpoints.map((endpoint) => [endpoint.value, endpoint])); let attempt = 0; while (pending.size > 0 && Date.now() < deadline) { attempt += 1; const results = await Promise.all([...pending.entries()].map(async ([value, endpoint]) => { try { const result = await checkEndpoint(endpoint, deadline); return { value, result }; } catch (error) { return { value, error }; } })); for (const result of results) { if (result.error) { core.info(`Not ready: ${result.value} (${result.error.message})`); } else { core.info(`Ready: ${result.value} (HTTP ${result.result.status} via ${result.result.address})`); pending.delete(result.value); } } if (pending.size > 0 && Date.now() < deadline) { const delaySeconds = Math.min(30, 5 * (2 ** Math.min(attempt - 1, 3))); const remainingMilliseconds = deadline - Date.now(); await new Promise((resolve) => setTimeout(resolve, Math.min(delaySeconds * 1000, remainingMilliseconds))); } } if (pending.size > 0) { fail( 'timeout', `Timed out waiting for ${pending.size} preview URL(s)`, [...pending.keys()], ); return; } core.setOutput( 'default_comment', `Your preview environment is ready! :rocket:\n\n${uniqueUrls.map((url) => `- ${url}`).join('\n')}`, ); - name: "[Preview][PR Event] Create or Update Comment" if: >- inputs.dry_run == false && inputs.preview && steps.config.outputs.mode == 'pr' && (inputs.preview_urls == '' || steps.wait_for_preview_urls.outcome == 'success') uses: peter-evans/create-or-update-comment@v5 with: comment-id: ${{ steps.fc.outputs.comment-id }} issue-number: ${{ github.event.pull_request.number }} body: | ${{ inputs.comment || steps.wait_for_preview_urls.outputs.default_comment || 'Your preview environment has been published! :rocket:' }} edit-mode: replace - name: "[Preview][PR Event] Report Readiness Failure" if: inputs.dry_run == false && inputs.preview && steps.config.outputs.mode == 'pr' && steps.wait_for_preview_urls.outcome == 'failure' uses: peter-evans/create-or-update-comment@v5 with: comment-id: ${{ steps.fc.outputs.comment-id }} issue-number: ${{ github.event.pull_request.number }} body: | Preview promotion completed, but its public readiness check failed (`${{ steps.wait_for_preview_urls.outputs.failure_type }}`). ```text ${{ steps.wait_for_preview_urls.outputs.failure_message }} ``` Any affected endpoints remain unlinked to avoid caching an unavailable preview: ```text ${{ steps.wait_for_preview_urls.outputs.pending_urls }} ``` edit-mode: replace - name: "[Preview][PR Event] Enforce Public Readiness" if: inputs.dry_run == false && inputs.preview && steps.config.outputs.mode == 'pr' && steps.wait_for_preview_urls.outcome == 'failure' run: | echo "One or more public preview URLs did not become ready in time" >&2 exit 1 - name: "[Dry Run][PR Event] Create or Update Comment" if: inputs.dry_run && steps.config.outputs.mode == 'pr' uses: peter-evans/create-or-update-comment@v5 env: NAME: ${{ env.NAME }} ARGO_NAME: ${{ env.ARGO_NAME }} DESTINATION_YAML: ${{ env.DESTINATION_YAML }} with: comment-id: ${{ steps.fc.outputs.comment-id }} issue-number: ${{ github.event.pull_request.number }} body: | ## Dry Run: ${{ inputs.preview && 'Preview' || 'Release' }} (${{ steps.config.outputs.promotion_pr == 'true' && 'Promotion PR' || 'Promotion' }}) Workflow validation completed successfully. ### Settings | Setting | Value | |---------|-------| | Environment Repository | `${{ inputs.environment_repository }}` | | Project | `${{ inputs.project }}` | | Application Name | `${{ env.ARGO_NAME }}` | | Output File | `${{ env.DESTINATION_YAML }}` | | Type | ${{ inputs.preview && 'Preview' || 'Release' }} | | Method | ${{ steps.config.outputs.promotion_pr == 'true' && 'Promotion PR' || 'Promotion' }} | ### Completed - Helm template generated for `${{ env.ARGO_NAME }}` - Changes detected: ${{ steps.commit_changes.outputs.has_changes == 'true' && 'Yes' || 'No' }} ### Skipped (dry run) - Commit to environment repository - ${{ steps.config.outputs.promotion_pr == 'true' && 'Create PR in' || 'Push to' }} `${{ inputs.environment_repository }}`
Environment Diff ```diff ${{ steps.commit_changes.outputs.diff }} ```
Generated Output File ```yaml ${{ steps.commit_changes.outputs.output_file }} ```
> This was a dry run. No changes were made to the environment repository. edit-mode: replace