Sub topic 8
Environments from Development to Production
This chapter assumes you can read a GitHub Actions workflow, know what a build artifact is, and understand the difference between continuous integration and continuous delivery. Earlier chapters covered building once and promoting the same artifact. This chapter covers where that artifact goes: the environments it passes through on its way to users.
What an environment is
An environment is a place where your application runs, together with everything it needs to run: servers or containers, a database, network rules, configuration, and credentials. The same artifact can run in many environments. What changes is the surroundings.
Most teams use some version of this sequence:
| Environment | Purpose | Who uses it | Data |
|---|---|---|---|
| Local or development | Writing and trying out code | One developer, or a shared dev team | Fake or seed data |
| Test or CI | Automated checks on every change | The pipeline | Created fresh for each run |
| Staging | A rehearsal that mirrors production | Testers, product owners, the pipeline | Anonymized or synthetic copy |
| Production | Serving real users | Customers | Real data |
The names vary. Some teams add a QA environment, a performance environment, or a per-pull-request preview environment. The names matter less than the idea. Each environment gives you more confidence than the previous one, and each costs more to get wrong.
Why have more than one
A single environment forces a choice between speed and safety. If everyone deploys straight to production, a bad change reaches customers immediately. If everyone shares one test server, people overwrite each other's work and test results become hard to trust.
Separate environments solve this by isolating risk:
- Failures in an early environment affect only developers.
- Slower or riskier checks, such as load tests and manual review, run where they cannot hurt users.
- You can test a deployment itself (the scripts, migrations, and configuration) before doing it for real.
That last point is easy to miss. Tests prove that the code works. Deploying to staging proves that the release procedure works.
Promotion through environments
Promotion means moving the same artifact from one environment to the next after it passes that environment's checks. The artifact does not get rebuilt. If you rebuild for each environment, the thing you tested in staging is not the thing you ship, and the staging result tells you less.
Each arrow into a deploy step is a gate. A gate is a condition that must be true before the pipeline continues. Common gates are:
- Automated tests passing.
- A manual approval from a named person or team.
- A time window, such as no deploys on Friday afternoons.
- A check that monitoring in the previous environment looks healthy.
Configuration differs, code does not
If the artifact is identical everywhere, then anything that differs between environments must live outside it. This is configuration: database addresses, API endpoints, feature settings, log levels, and secrets.
The usual approach is to read configuration at startup from environment variables or a configuration service. The artifact asks "what is my database URL?" and each environment gives a different answer.
import os
def load_config() -> dict:
return {
"database_url": os.environ["DATABASE_URL"],
"log_level": os.environ.get("LOG_LEVEL", "INFO"),
"payments_api": os.environ["PAYMENTS_API_URL"],
}
if __name__ == "__main__":
os.environ.setdefault("DATABASE_URL", "postgres://localhost/dev")
os.environ.setdefault("PAYMENTS_API_URL", "https://sandbox.example.com")
print(load_config())Two details matter here. Required values use os.environ[...], so a missing value fails immediately at startup instead of causing a strange error later. Optional values have a default. Never give a default to anything that would be dangerous if it silently pointed at the wrong place, such as a production database address.
Configuration drift
Drift happens when environments slowly become different in ways nobody planned. Staging runs an older database version. Production has a firewall rule that staging lacks. Someone installed a package by hand on one server.
Drift is the main reason "it passed in staging" fails to predict production behavior. Reduce it by:
- Creating environments from code (infrastructure as code) instead of by hand.
- Using the same container image or base operating system everywhere.
- Making manual changes to servers a rare, recorded exception.
- Rebuilding staging periodically from the same definition as production.
Parity and its limits
Staging should be as similar to production as you can afford. Full parity is often too expensive. A production cluster of 40 servers may have a staging cluster of 2. This is a reasonable trade-off as long as you know what it hides. A two-server staging cannot reveal problems that only appear under heavy load or with many instances competing for the same resource. Write down where staging differs from production so that people know which risks it cannot cover.
Environments in a pipeline definition
GitHub Actions supports environments as a named feature. A job that declares environment: production is tied to that environment's settings: its secrets, its variables, and its protection rules. These are configured in the repository settings, not in the YAML file.
The deploy job from the CI/CD workflow shows the pattern:
name: ci-cd
on:
push:
branches: [main]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
cache: npm
- run: npm ci
- run: npm test
- run: npm run build
- uses: actions/upload-artifact@v4
with:
name: dist
path: dist/
deploy:
needs: build
runs-on: ubuntu-latest
environment: production
steps:
- uses: actions/checkout@v4
- uses: actions/download-artifact@v4
with:
name: dist
path: dist/
- run: ./scripts/deploy.sh dist/Reading it with environments in mind:
- The
buildjob runs once and uploadsdist/as the artifact. - The
deployjob waits forbuildthroughneeds: build. environment: productionattaches the production environment's rules. If you configured required reviewers, the job pauses until one of them approves.- The deploy job downloads the same
distartifact instead of rebuilding. scripts/deploy.shis a placeholder for your own deployment script. It reads production configuration from variables and secrets defined on the environment.
Adding a staging step means adding another job with environment: staging between build and production, with needs chaining them in order.
deploy-staging:
needs: build
runs-on: ubuntu-latest
environment: staging
steps:
- uses: actions/download-artifact@v4
with:
name: dist
path: dist/
- run: ./scripts/deploy.sh dist/
deploy-production:
needs: deploy-staging
runs-on: ubuntu-latest
environment: production
steps:
- uses: actions/download-artifact@v4
with:
name: dist
path: dist/
- run: ./scripts/deploy.sh dist/The same script runs in both jobs. Only the environment, and therefore the configuration and secrets, differs. This is the property you want: one procedure, exercised in staging before it touches production.
Environment-scoped secrets
A secret defined on the production environment is available only to jobs that declare that environment. A job running for a pull request from a fork, or a job tied to staging, cannot read it. This limits the damage if a lower environment is compromised. Using separate credentials per environment also means a leaked staging key cannot touch production data.
Data in non-production environments
Test and staging environments need realistic data to be useful, but copying production data brings privacy and legal risk. Options, from safest to riskiest:
- Synthetic data generated by scripts. Safe, but may miss real-world oddities.
- Anonymized or masked copies of production, where names, emails, and identifiers are replaced.
- Raw copies of production. Avoid this. Staging usually has weaker access controls than production.
Database changes need special care. A schema migration runs in each environment in turn, so the staging run is your rehearsal for the production run. A migration that takes two seconds on a small staging database can lock a large production table for minutes. Test migrations against data of realistic size where you can.
Common errors
- Rebuilding per environment. The artifact in production differs from the one tested. Build once and promote.
- Environment checks in code. Branches like
if env == "production"mean the code path in production is one your tests never ran. Keep behavior differences in configuration values instead. - Shared resources between environments. Staging and production sharing a queue or database means staging tests can affect real users.
- Skipping staging for "small" changes. Small changes cause outages too. If the process is too slow, speed up the process.
- Staging that nobody trusts. If staging is often broken or stale, people begin to ignore its results.
Environments and delivery models
Environments are what separate continuous delivery from continuous deployment. In continuous delivery, a human approval gate usually sits before production. In continuous deployment, no such gate exists, so the automated checks in earlier environments must carry all the confidence. The more gates you remove, the more you depend on the quality of your tests and the realism of staging.
Exercise
Your pipeline builds the application separately inside each of the staging and production deploy jobs. Staging tests pass, but production fails after release. Name the problem with this design and describe the fix.
Show answer
The pipeline rebuilds per environment, so the production build is not the artifact that was tested in staging. A different dependency version or build setting could explain the failure. The fix is to build once in a build job, upload the result as an artifact, and have both deploy jobs download that same artifact. Environment differences should then come only from configuration and secrets.
Exercise
A developer adds if (env === "production") { skipEmailValidation(); } to the code. Why is this risky, and what should be done instead?
Show answer
The production-only branch never runs in test or staging, so no earlier environment verifies it. Behavior should differ only through configuration values, such as a setting read from an environment variable, so every environment runs the same code path and tests can set the value explicitly.