In this lesson, you will learn how to leverage CI/CD pipeline variables to dynamically inject environment-specific settings into your .NET application’s Kubernetes manifests at deployment time.
The Problem: Hardcoding vs. Dynamic Injection
When deploying a .NET microservice, you often face the challenge of managing differences between Development, Staging, and Production environments (e.g., API base URLs, connection strings, or feature flags). Hardcoding these in your appsettings.json is a security risk and an operational bottleneck. Instead, we treat our Kubernetes manifest (or Helm values) as a template where sensitive or environment-specific values are populated by the build pipeline.
The Pipeline-to-Manifest Workflow
In a robust deployment pipeline (e.g., Azure DevOps, GitHub Actions), you define variables scoped to your environment. During the deployment stage, the pipeline tool searches your YAML manifest for specific tokens—often represented as #{VARIABLE_NAME}#—and performs a text replacement before applying the file to the cluster.
Consider a Kubernetes Deployment.yaml template:
env:
- name: API_ENDPOINT
value: "#{API_ENDPOINT_URL}#"
- name: CONNECTION_STRING
valueFrom:
secretKeyRef:
name: db-secrets
key: #{DB_SECRET_KEY}#
At runtime, your pipeline engine replaces #{API_ENDPOINT_URL}# with https://prod-api.company.com. The resulting "processed" file is then sent to kubectl apply.
Why this matters for .NET
By injecting these values as environment variables, your .NET application remains decoupled from the infrastructure. Your ConfigurationBuilder in Program.cs automatically picks these up through the AddEnvironmentVariables() provider. This ensures that your container image remains identical across all environments, adhering to the "Build Once, Deploy Anywhere" principle. You aren't changing the code; you are changing the "context" the container runs in, which keeps your deployments predictable and easily auditable.
Key Takeaway: Use pipeline-level variable replacement to transform generic environment configuration tokens into environment-specific values at the moment of deployment, ensuring your application images remain immutable and environment-agnostic.