name: Terraform on: push: branches: [main] pull_request: branches: [main] env: TF_VAR_netbird_token: ${{ secrets.NETBIRD_TOKEN }} defaults: run: working-directory: terraform jobs: terraform: runs-on: ubuntu-latest steps: - name: Checkout uses: actions/checkout@v4 - name: Setup Terraform uses: hashicorp/setup-terraform@v3 with: terraform_version: 1.7.0 - name: Terraform Init run: terraform init - name: Terraform Format Check run: terraform fmt -check continue-on-error: true - name: Terraform Validate run: terraform validate - name: Terraform Plan if: github.event_name == 'pull_request' run: terraform plan -no-color - name: Terraform Apply if: github.ref == 'refs/heads/main' && github.event_name == 'push' run: terraform apply -auto-approve - name: Export setup keys (encrypted) if: github.ref == 'refs/heads/main' && github.event_name == 'push' env: AGE_PUBLIC_KEY: ${{ secrets.AGE_PUBLIC_KEY }} run: | # Install age locally (no sudo in container) if ! command -v age &> /dev/null; then curl -sL https://github.com/FiloSottile/age/releases/download/v1.1.1/age-v1.1.1-linux-amd64.tar.gz | tar xz export PATH="$PWD/age:$PATH" fi # Extract all setup key values terraform output -json | python3 -c " import json, sys, subprocess outputs = json.load(sys.stdin) keys = {} for name, data in outputs.items(): if data.get('sensitive') and 'key' in name.lower(): result = subprocess.run(['terraform', 'output', '-raw', name], capture_output=True, text=True) if result.returncode == 0: keys[name] = result.stdout.strip() result = { 'generated': '$(date -u +%Y-%m-%dT%H:%M:%SZ)', 'commit': '${{ github.sha }}', 'keys': keys } print(json.dumps(result, indent=2)) " > setup-keys.json # Encrypt with age if [ -n "$AGE_PUBLIC_KEY" ]; then ./age/age -r "$AGE_PUBLIC_KEY" -o setup-keys.json.age setup-keys.json rm setup-keys.json echo "Setup keys encrypted to setup-keys.json.age" else echo "WARNING: AGE_PUBLIC_KEY not set, keys not encrypted!" rm setup-keys.json fi - name: Commit state and keys if: github.ref == 'refs/heads/main' && github.event_name == 'push' working-directory: . run: | git config user.name "Terraform CI" git config user.email "ci@localhost" # Add state files git add terraform/terraform.tfstate terraform/terraform.tfstate.backup 2>/dev/null || true # Add encrypted keys if generated if [ -f terraform/setup-keys.json.age ]; then git add terraform/setup-keys.json.age fi if ! git diff --staged --quiet; then git commit -m "chore: update terraform state and keys [skip ci]" git push fi