Once more than a handful of engineers share one staging environment, the environment becomes the bottleneck. Below is a setup that gives every pull request its own.
With one shared staging environment, you finish a feature, ask in Slack whether anyone is using staging, and wait, sometimes for hours. Then you deploy, fix what you find and redeploy until it works. Production deploys get batched up because they hurt.
Environment drift makes it worse. Staging and production slowly diverge, and some bugs only happen in production.
Every pull request gets its own environment, created when the PR opens and deleted when it closes.
PR Opened → GitHub Actions → CloudFormation Stack → ECS Service → Internal URL
PR Closed → GitHub Actions → Stack Deleted → Resources Cleaned Up
Each environment has its own database and ECS service, in a stack named after the Jira ticket. It uses the same database engine and version as production, on a smaller db.t3.micro instance and small Fargate tasks.
The URL is http://<env>.internal:8080, and it’s reachable only from inside the VPC. The tasks run in private subnets with no public IP, and the security group only admits 10.0.0.0/8 on port 8080. A task’s IP changes on every deploy, so each stack registers its service in Cloud Map, which keeps the DNS name pointed at the running task.
The stacks share one private DNS namespace named internal. Create it once, in a VPC with DNS support and DNS hostnames turned on, and store the namespace ID as a secret for the workflow.
aws servicediscovery create-private-dns-namespace --name internal --vpc vpc-0123456789abcdef0
The private subnets also need a route to ECR, through a NAT gateway or VPC endpoints, so tasks can pull the image.
It triggers on PR events and authenticates to AWS with OIDC. Images are tagged with the commit SHA. A tag that stays the same between pushes wouldn’t change the task definition, so CloudFormation would have nothing to do and the old image would keep running.
name: Ephemeral Environment
on:
pull_request:
types: [opened, synchronize, closed]
permissions:
id-token: write
contents: read
pull-requests: write
jobs:
deploy:
if: github.event.action != 'closed'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Extract Jira Ticket
id: jira
env:
HEAD_REF: ${{ github.head_ref }}
run: |
TICKET=$(echo "$HEAD_REF" | grep -oE '[A-Z]+-[0-9]+' | head -1)
echo "ticket=${TICKET:-pr-${{ github.event.number }}}" >> $GITHUB_OUTPUT
- name: Configure AWS credentials
uses: aws-actions/configure-aws-credentials@v4
with:
role-to-assume: ${{ secrets.AWS_ROLE_ARN }}
aws-region: us-east-1
- name: Log in to ECR
id: ecr
uses: aws-actions/amazon-ecr-login@v2
- name: Build and Push to ECR
env:
ECR_REGISTRY: ${{ steps.ecr.outputs.registry }}
run: |
docker build -t $ECR_REGISTRY/app:${{ github.sha }} .
docker push $ECR_REGISTRY/app:${{ github.sha }}
- name: Deploy CloudFormation Stack
env:
VPC_ID: ${{ secrets.VPC_ID }}
PRIVATE_SUBNET_IDS: ${{ secrets.PRIVATE_SUBNET_IDS }}
ECS_CLUSTER_ARN: ${{ secrets.ECS_CLUSTER_ARN }}
EXECUTION_ROLE_ARN: ${{ secrets.EXECUTION_ROLE_ARN }}
DB_SUBNET_GROUP: ${{ secrets.DB_SUBNET_GROUP }}
DB_SECRET_ARN: ${{ secrets.DB_SECRET_ARN }}
NAMESPACE_ID: ${{ secrets.NAMESPACE_ID }}
run: |
aws cloudformation deploy \
--stack-name env-${{ steps.jira.outputs.ticket }} \
--template-file infra/ephemeral.yaml \
--parameter-overrides \
EnvironmentName=${{ steps.jira.outputs.ticket }} \
ImageTag=${{ github.sha }} \
VpcId=$VPC_ID \
PrivateSubnetIds=$PRIVATE_SUBNET_IDS \
ECSClusterArn=$ECS_CLUSTER_ARN \
ExecutionRoleArn=$EXECUTION_ROLE_ARN \
DBSubnetGroupName=$DB_SUBNET_GROUP \
DBSecretArn=$DB_SECRET_ARN \
NamespaceId=$NAMESPACE_ID \
--tags \
JiraTicket=${{ steps.jira.outputs.ticket }} \
PRNumber=${{ github.event.number }} \
--no-fail-on-empty-changeset
- name: Comment PR with URL
if: github.event.action == 'opened'
uses: actions/github-script@v7
with:
script: |
github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.issue.number,
body: 'Environment deployed: http://${{ steps.jira.outputs.ticket }}.internal:8080 (reachable from inside the VPC)'
})
cleanup:
if: github.event.action == 'closed'
runs-on: ubuntu-latest
steps:
- name: Extract Jira Ticket
id: jira
env:
HEAD_REF: ${{ github.head_ref }}
run: |
TICKET=$(echo "$HEAD_REF" | grep -oE '[A-Z]+-[0-9]+' | head -1)
echo "ticket=${TICKET:-pr-${{ github.event.number }}}" >> $GITHUB_OUTPUT
- name: Configure AWS credentials
uses: aws-actions/configure-aws-credentials@v4
with:
role-to-assume: ${{ secrets.AWS_ROLE_ARN }}
aws-region: us-east-1
- name: Delete CloudFormation Stack
run: |
aws cloudformation delete-stack --stack-name env-${{ steps.jira.outputs.ticket }}
The template creates an ECS service with its own database. Parameters reference shared infrastructure (VPC, cluster, roles) outside the stack.
AWSTemplateFormatVersion: '2010-09-09'
Description: Ephemeral environment stack
Parameters:
EnvironmentName:
Type: String
Description: Jira ticket or PR identifier
ImageTag:
Type: String
Description: ECR image tag to deploy
VpcId:
Type: AWS::EC2::VPC::Id
Description: VPC for the environment
PrivateSubnetIds:
Type: List<AWS::EC2::Subnet::Id>
Description: Private subnets for ECS tasks
ECSClusterArn:
Type: String
Description: ARN of the shared ECS cluster
ExecutionRoleArn:
Type: String
Description: ARN of the ECS task execution role
DBSubnetGroupName:
Type: String
Description: DB subnet group for RDS
DBSecretArn:
Type: String
Description: Full ARN of a Secrets Manager secret with username and password keys
NamespaceId:
Type: String
Description: ID of the shared Cloud Map private DNS namespace named internal
Resources:
# Security group for the ECS service
ServiceSecurityGroup:
Type: AWS::EC2::SecurityGroup
Properties:
GroupDescription: !Sub 'Security group for ${EnvironmentName}'
VpcId: !Ref VpcId
SecurityGroupIngress:
- IpProtocol: tcp
FromPort: 8080
ToPort: 8080
CidrIp: 10.0.0.0/8
# Security group for the database
DBSecurityGroup:
Type: AWS::EC2::SecurityGroup
Properties:
GroupDescription: !Sub 'DB security group for ${EnvironmentName}'
VpcId: !Ref VpcId
SecurityGroupIngress:
- IpProtocol: tcp
FromPort: 5432
ToPort: 5432
SourceSecurityGroupId: !Ref ServiceSecurityGroup
# RDS PostgreSQL instance
Database:
Type: AWS::RDS::DBInstance
DeletionPolicy: Delete
Properties:
DBInstanceClass: db.t3.micro
Engine: postgres
EngineVersion: '15.19'
DBName: app
MasterUsername: !Sub '{{resolve:secretsmanager:${DBSecretArn}:SecretString:username}}'
MasterUserPassword: !Sub '{{resolve:secretsmanager:${DBSecretArn}:SecretString:password}}'
AllocatedStorage: 20
DBSubnetGroupName: !Ref DBSubnetGroupName
VPCSecurityGroups:
- !Ref DBSecurityGroup
PubliclyAccessible: false
BackupRetentionPeriod: 0
DeleteAutomatedBackups: true
# ECS Task Definition
TaskDefinition:
Type: AWS::ECS::TaskDefinition
Properties:
Family: ephemeral-app
Cpu: '256'
Memory: '512'
NetworkMode: awsvpc
RequiresCompatibilities:
- FARGATE
ExecutionRoleArn: !Ref ExecutionRoleArn
ContainerDefinitions:
- Name: app
Image: !Sub '${AWS::AccountId}.dkr.ecr.${AWS::Region}.amazonaws.com/app:${ImageTag}'
Essential: true
PortMappings:
- ContainerPort: 8080
Protocol: tcp
Environment:
- Name: DB_HOST
Value: !GetAtt Database.Endpoint.Address
- Name: DB_NAME
Value: app
- Name: ENVIRONMENT
Value: !Ref EnvironmentName
Secrets:
- Name: DB_USER
ValueFrom: !Sub '${DBSecretArn}:username::'
- Name: DB_PASSWORD
ValueFrom: !Sub '${DBSecretArn}:password::'
LogConfiguration:
LogDriver: awslogs
Options:
awslogs-group: !Ref LogGroup
awslogs-region: !Ref AWS::Region
awslogs-stream-prefix: !Ref EnvironmentName
# CloudWatch Log Group
LogGroup:
Type: AWS::Logs::LogGroup
Properties:
RetentionInDays: 7
# DNS name for the service: <EnvironmentName>.internal
ServiceDiscovery:
Type: AWS::ServiceDiscovery::Service
Properties:
Name: !Ref EnvironmentName
NamespaceId: !Ref NamespaceId
DnsConfig:
DnsRecords:
- Type: A
TTL: 10
RoutingPolicy: MULTIVALUE
HealthCheckCustomConfig:
FailureThreshold: 1
# ECS Service
Service:
Type: AWS::ECS::Service
DependsOn: Database
Properties:
Cluster: !Ref ECSClusterArn
TaskDefinition: !Ref TaskDefinition
DesiredCount: 1
LaunchType: FARGATE
NetworkConfiguration:
AwsvpcConfiguration:
Subnets: !Ref PrivateSubnetIds
SecurityGroups:
- !Ref ServiceSecurityGroup
AssignPublicIp: DISABLED
ServiceRegistries:
- RegistryArn: !GetAtt ServiceDiscovery.Arn
Outputs:
ServiceUrl:
Description: Internal service URL
Value: !Sub 'http://${EnvironmentName}.internal:8080'
DatabaseEndpoint:
Description: RDS endpoint
Value: !GetAtt Database.Endpoint.Address
The task execution role needs secretsmanager:GetSecretValue on the database secret, because ECS injects the username and password when the task starts. Passing them this way keeps the password out of the task definition, where anyone with ecs:DescribeTaskDefinition could read it. The app builds its connection string from those variables.
One command deletes everything in a stack. There’s no external state to manage, and GitHub Actions needs no additional tooling to run it. Fargate means there are no servers to clean up afterward.
The template leaves out DBInstanceIdentifier, ServiceName and LogGroupName. CloudFormation replaces a resource by creating the new one before deleting the old one, and with a fixed name the new one collides with the old and the update fails. Generated names avoid that, and the stack name already groups the resources.
The Cloud Map service is the exception, because its name is the URL. It only changes if EnvironmentName does, and that’s fixed for the life of the stack.
Each environment gets its own RDS instance. That costs more than a shared database, but test data can’t leak and developers can run migrations without coordinating.
To keep the cost down, the template uses db.t3.micro and keeps no backups. DeletionPolicy: Delete removes the database with the environment.
Nobody asks whether staging is free, and anyone who can reach the VPC can click through a change before it merges.
In us-east-1, the template’s 0.25 vCPU, 0.5GB Fargate task is about $0.012 an hour and a db.t3.micro running Postgres is $0.018. A PR that stays open for three days costs under three dollars, including the database’s 20GB of storage.
AI agents, automation, and websites, built in a few weeks and then maintained for a monthly fee. If something in your week should be software by now, book a call.