# Environments and Secrets

Course: [CI/CD](https://www.devtutorials.ai/learn/cicd) · Section: Continuous Delivery
Source: https://www.devtutorials.ai/learn/cicd/continuous-delivery/environments-and-secrets

> Deploy through environments with approval rules, keep secrets in the platform, sign in to Azure with OIDC instead of a stored password, and deploy to production only from main after staging.

## Environments and Secrets

CI checked the change. Now CD takes it to real places: staging, then production.

To do that safely, the pipeline needs:

- **environments** with rules, like "production needs approval".
- **secrets**, like the key to sign in to Azure.
- a way to sign in **without** storing a password.
- an order: staging first, production only from main.

**Simple lesson:** production is a locked room. The pipeline needs the right key, at the right time, with a person's OK.

### A Real-World Example

Think about a bank locker.

- You need **your own** key. Not a copy anyone can borrow.
- A **bank officer** must be present to open it.
- The officer checks your **ID** each visit.
- You cannot open it from the street. Only from inside the bank.

Now map it:

- **The locker** = production.
- **The officer** = an approval rule.
- **ID checked each visit** = a short-lived sign-in token.
- **Only from inside** = only from the main branch.

**Simple lesson:** approval, identity and place. All three, every time.

## Environments

**Environment** (in a pipeline) = a named target with its own rules and secrets.

| Platform | Where you set it up | In the YAML |
|---|---|---|
| GitHub Actions | Settings → Environments | `environment: production` on the job |
| Azure Pipelines | Pipelines → Environments | a `deployment` job with `environment: production` |

Rules you can add to an environment:

- **Required reviewers:** a person must approve before the job runs.
- **Branch rule:** only main can deploy here.
- **Secrets for this environment only:** staging cannot see production's keys.

**Simple lesson:** a deploy job without an environment skips every rule you set.

## Secrets

**Secret** = a value that must stay hidden, like a password or API key.

- Store it in the platform, never in the YAML file or the code.
- The platform hides it in logs. It shows `***` instead.
- Give each environment its own secrets.

| Platform | Use a secret |
|---|---|
| GitHub Actions | `${{ secrets.NAME }}` |
| Azure Pipelines | `$(NAME)`, marked as secret in a variable group |

`***` in a log does not make a secret safe. A step can still send it somewhere else. Fewer secrets is better than hidden secrets.

**Simple lesson:** keep secrets out of files, and keep as few as you can.

## Sign In Without a Password: OIDC

The old way:

- Make a long-lived password (a "client secret") in Azure.
- Store it as a pipeline secret.
- It works for a year or two, from anywhere, for anyone who has it.

The better way is **OIDC**.

**OIDC** = the pipeline proves who it is with a short-lived token, instead of a stored password.

- Azure is told once: "trust tokens from this repo and this environment".
- Each run gets a fresh token that lasts minutes.
- There is no password to leak.

| Platform | How |
|---|---|
| GitHub Actions | `azure/login` with no client-secret, plus `permissions: id-token: write` on the job |
| Azure Pipelines | A service connection using workload identity federation, used by `AzureCLI@2` |

**Real tools vs this lab:** setting up OIDC also needs a one-time step in Azure, called a federated credential. Your cloud admin usually does it once. In this lab, that trust is already in place.

**Simple lesson:** a token that dies in minutes is safer than a password that lives for years.

## Rules for Production

### Only From Main

- A pull request is not reviewed yet.
- It must never deploy to production.

| Platform | Condition |
|---|---|
| GitHub Actions | `if: github.ref == 'refs/heads/main'` |
| Azure Pipelines | `condition: and(succeeded(), eq(variables['Build.SourceBranch'], 'refs/heads/main'))` |

### Staging First

- Production should wait for staging to finish.
- Use `needs` or `dependsOn`, just like in Your First Pipeline.

Add the branch rule in the environment settings too. Then even a wrong YAML file cannot deploy a pull request to production.

**Simple lesson:** main only, staging first, approval before production.

1. In your starter repo, open **Settings → Environments**.
2. Create `staging` and `production`. Give production a required reviewer (you).
3. Add the variables `AZURE_CLIENT_ID`, `AZURE_TENANT_ID` and `AZURE_SUBSCRIPTION_ID` from the README.

**What you should see:** two environments, and production showing "Required reviewers". You deploy into them in the next lesson.

## Quick Check

## Cheat Sheet

GitHub Actions:

```yaml
permissions:
  contents: read

jobs:
  deploy-production:
    needs: deploy-staging
    if: github.ref == 'refs/heads/main'
    runs-on: ubuntu-latest
    environment: production
    permissions:
      contents: read
      id-token: write
    steps:
      - uses: actions/download-artifact@v4
        with:
          name: web
          path: dist
      - uses: azure/login@v2
        with:
          client-id: ${{ vars.AZURE_CLIENT_ID }}
          tenant-id: ${{ vars.AZURE_TENANT_ID }}
          subscription-id: ${{ vars.AZURE_SUBSCRIPTION_ID }}
      - uses: azure/webapps-deploy@v3
        with:
          app-name: shop-web-production
          package: dist
```

Azure Pipelines:

```yaml
jobs:
  - deployment: deploy_production
    dependsOn: deploy_staging
    condition: and(succeeded(), eq(variables['Build.SourceBranch'], 'refs/heads/main'))
    environment: production
    strategy:
      runOnce:
        deploy:
          steps:
            - task: AzureWebApp@1
              inputs:
                azureSubscription: shop-production-oidc
                appType: webAppLinux
                appName: shop-web-production
                package: $(Pipeline.Workspace)/web
```

## Common mistakes

| Mistake | Wrong idea | Correct idea | What goes wrong |
|---|---|---|---|
| Secrets in YAML | The repo is private | Files get copied and shared | The key leaks |
| One secret for all environments | Simpler to manage | Each environment gets its own | A staging leak opens production |
| Long-lived client secret | It is the normal way | Use OIDC | A stolen secret works for years |
| No `id-token: write` | OIDC just works | The job must be allowed to ask | "Unable to get ACTIONS_ID_TOKEN_REQUEST_URL" |
| Deploy job without `environment` | The name is enough | The environment applies the rules | No approval, no branch rule |

## What to Remember

- Environment = a target with rules and its own secrets.
- Secrets live in the platform, never in files.
- OIDC: short-lived token, no stored password.
- Production: main only, after staging, with approval.

## Exercises

Next: **Deploy for Real**
