Course contentsShow
← Docker, Kubernetes & CI/CD
Lesson 771 of 80211. Production Operations and ReliabilityFree lesson

Managing Infrastructure Secrets and Sensitive Data

Implement secure workflows for injecting credentials and secrets into infrastructure templates without exposing sensitive data in version control.

In this lesson, you will learn how to decouple sensitive credentials from your declarative infrastructure templates to ensure they remain encrypted and outside of version control.

The Challenge of Static Configurations

When managing infrastructure as code (IaC), we strive for transparency and reproducibility. However, keeping secrets like API tokens, database passwords, or private keys directly in your Terraform or Kubernetes manifests is a critical security failure. Once a secret is committed to a Git repository, it is essentially compromised. Even if you delete the file in a future commit, the sensitive data remains in the repository's history, reachable by anyone with read access.

Injecting Secrets at Runtime

Instead of defining secrets directly in templates, adopt the "Late-Binding" approach. Your infrastructure code should define the requirement for a secret without containing the secret itself.

For Kubernetes, this is achieved by referencing Secrets objects. Your deployment template should look like this:

spec:
  containers:
    - name: app-container
      env:
        - name: DB_PASSWORD
          valueFrom:
            secretKeyRef:
              name: db-credentials
              key: password

In this example, the template describes the desired state, but the actual value is injected by the cluster at runtime. The db-credentials object is managed separately—usually created via a secure automated process or a dedicated secret management tool—and is never stored in your application's source control.

Securing the CI/CD Pipeline

In a CI/CD context, sensitive data should be injected into the environment during the execution phase, not the build phase. Modern CI/CD platforms provide "Protected Variables" or "Secret Stores." By using these, the runner fetches the value from a secure vault (like HashiCorp Vault or cloud-native key management services) only at the moment of deployment. This ensures that even if your infrastructure templates are public or audited by many team members, the credentials themselves remain accessible only to the automated service identity running the deployment.

By treating secrets as external runtime dependencies rather than configuration constants, you maintain auditability and security without sacrificing the declarative nature of your infrastructure.

Key Takeaway: Never hardcode sensitive values in your configuration files; instead, use reference patterns to inject secrets dynamically during deployment, ensuring they remain separated from your version-controlled source code.