You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用CircleCI与AWS Lambda实现多阶段(dev/prod)移动应用API环境变量配置

Got it, let's walk through how to set up separate dev and production environments for your mobile app API using CircleCI and AWS Lambda—with isolated environment variables for database connections and SNS keys. This approach keeps your secrets secure and ensures each environment stays independent:

1. Store Environment-Specific Secrets in AWS

First, keep sensitive configs (DB URLs, SNS keys) out of your codebase. AWS offers two reliable tools for this:

  • AWS Secrets Manager: Ideal for rotating secrets (like DB credentials) and storing highly sensitive data with built-in encryption. Create separate secrets for dev and prod, e.g., dev/api-secrets and prod/api-secrets.
  • AWS Systems Manager Parameter Store: A simpler choice for non-rotating values, organized by clear paths like /dev/db/connection-string and /prod/sns/api-key.

Whichever tool you pick, make sure to segregate dev and prod resources explicitly to avoid accidental cross-environment access.

2. Set Up CircleCI Contexts for Environment Segmentation

CircleCI Contexts let you manage environment variables across projects without hardcoding them. Here’s how to use them:

  • Create two contexts in your CircleCI project: dev-env and prod-env.
  • Add the necessary AWS credentials (IAM access key/secret key) to each context. Critical note: Use an IAM user with least privilege—only grant access to dev resources for the dev context, and prod resources for the prod context.
  • Include an ENVIRONMENT variable in each context (set to dev for dev-env, prod for prod-env) to flag which environment you’re targeting.
3. Configure Your CircleCI Config to Deploy to Each Environment

Update your .circleci/config.yml to define separate workflows for dev and prod deployments. Here’s a simplified example:

version: 2.1

workflows:
  dev-deploy:
    jobs:
      - build-and-deploy:
          context: dev-env
          filters:
            branches:
              only: dev
  prod-deploy:
    jobs:
      - build-and-deploy:
          context: prod-env
          filters:
            branches:
              only: main

jobs:
  build-and-deploy:
    docker:
      - image: cimg/python:3.11
    steps:
      - checkout
      - run:
          name: Install dependencies
          command: pip install -r requirements.txt
      - run:
          name: Configure AWS CLI
          command: |
            aws configure set aws_access_key_id $AWS_ACCESS_KEY_ID
            aws configure set aws_secret_access_key $AWS_SECRET_ACCESS_KEY
            aws configure set region $AWS_REGION
      - run:
          name: Deploy to Lambda
          command: |
            # Use AWS CLI to update Lambda with environment flag
            aws lambda update-function-configuration \
              --function-name my-api-lambda-$ENVIRONMENT \
              --environment Variables="{ENV=$ENVIRONMENT}"
            # Alternatively, use Serverless Framework if you prefer:
            # serverless deploy --stage $ENVIRONMENT

This setup triggers a dev deployment when code is pushed to the dev branch, and a prod deployment when changes are merged to main.

4. Make Lambda Fetch Environment-Specific Secrets at Runtime

Instead of hardcoding secrets into Lambda’s environment variables (which are visible in the AWS Console), have Lambda pull secrets from AWS Secrets Manager/Parameter Store on cold start. Here’s a Python example:

import os
import boto3
from botocore.exceptions import ClientError

def get_environment_secrets():
    environment = os.environ['ENV']
    secret_name = f"{environment}/api-secrets"
    region_name = os.environ['AWS_REGION']

    session = boto3.session.Session()
    client = session.client(service_name='secretsmanager', region_name=region_name)

    try:
        secret_response = client.get_secret_value(SecretId=secret_name)
        return eval(secret_response['SecretString']) # Parse JSON-formatted secret
    except ClientError as e:
        raise e

# Initialize secrets once during Lambda cold start
secrets = get_environment_secrets()
db_connection = secrets['db_url']
sns_key = secrets['sns_api_key']

def lambda_handler(event, context):
    # Use db_connection and sns_key in your API logic here
    return {"statusCode": 200, "body": "API running successfully"}

This way, sensitive data never lives in Lambda’s config, and you only need to update the secret in AWS to adjust configs for either environment.

Quick Best Practices
  • Lock down IAM permissions: The CircleCI IAM user should only have permission to deploy Lambda functions for its target environment. The Lambda execution role should only have access to the secrets/parameters for its environment.
  • Test in dev first: Add a test step in your CircleCI job to run integration tests against the dev Lambda deployment before pushing to prod.
  • Avoid cross-environment leaks: Never reference prod resources in your dev config, and vice versa.

内容的提问来源于stack exchange,提问作者Anuradha Wickramarachi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:47:22