如何用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:
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-secretsandprod/api-secrets. - AWS Systems Manager Parameter Store: A simpler choice for non-rotating values, organized by clear paths like
/dev/db/connection-stringand/prod/sns/api-key.
Whichever tool you pick, make sure to segregate dev and prod resources explicitly to avoid accidental cross-environment access.
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-envandprod-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
ENVIRONMENTvariable in each context (set todevfordev-env,prodforprod-env) to flag which environment you’re targeting.
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.
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.
- 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

