1. Answers
  2. Setting Environment Variables Across Deployment Stages

How do I set environment variables for different deployment stages?

In this guide, you’ll learn how to set environment variables for different deployment stages. This is useful for managing configurations like API keys, database URLs, and other sensitive information that differ between development, testing, staging, and production environments.

We will define environment variables for different stages using variables and conditional logic.

import * as pulumi from "@pulumi/pulumi";
import * as aws from "@pulumi/aws";

export = async () => {
    const config = new pulumi.Config();
    // The deployment stage (dev, test, prod)
    const env = config.get("env") || "dev";
    // Database URL for the application
    const databaseUrl = config.get("databaseUrl") || "localhost:5432";
    // API Key for the application
    const apiKey = config.get("apiKey") || "";
    const dbUrl = env == "prod" ? "prod-db.example.com" : env == "test" ? "test-db.example.com" : databaseUrl;
    const myApiKey = env == "prod" ? "PROD_API_KEY" : env == "test" ? "TEST_API_KEY" : apiKey;
    // Example resource (e.g., an AWS instance) setting environment variables
    const example = new aws.ec2.Instance("example", {
        ami: "ami-08d4ac5b634553e16",
        instanceType: aws.ec2.InstanceType.T2_Micro,
        tags: {
            Name: "example-instance",
            Env: env,
        },
        userData: `#!/bin/bash
export DATABASE_URL=${dbUrl}
export API_KEY=${myApiKey}
`,
    });
    return {
        databaseUrl: dbUrl,
        apiKey: myApiKey,
    };
}

Key Points:

  • Variables are set up for the deployment stage and environment-specific data.
  • Local values utilize conditional logic to switch values based on the environment.
  • Resources are configured to use these values, enhancing management across stages.
  • Outputs are defined to confirm the applied settings.

In this example, we set environment-specific configurations by using variables and conditional logic to manage values for different deployment stages, which can be integrated into resource definitions. This approach simplifies the management of environment variables across multiple stages of deployment.

Deploy this code

Want to deploy this code? Sign up for a free Pulumi account to deploy in a few clicks.

Sign up

New to Pulumi?

Want to deploy this code? Sign up with Pulumi to deploy in a few clicks.

Sign up