Define AWS infrastructure with AWS CDK constructs and best practices in Google Antigravity
# AWS CDK Infrastructure Patterns for Google Antigravity
AWS CDK enables infrastructure definition using familiar programming languages. This guide covers CDK patterns optimized for Google Antigravity IDE and Gemini 3.
## CDK Stack Structure
```typescript
// lib/main-stack.ts
import * as cdk from 'aws-cdk-lib';
import * as ec2 from 'aws-cdk-lib/aws-ec2';
import * as ecs from 'aws-cdk-lib/aws-ecs';
import * as rds from 'aws-cdk-lib/aws-rds';
import { Construct } from 'constructs';
interface MainStackProps extends cdk.StackProps {
environment: string;
projectName: string;
}
export class MainStack extends cdk.Stack {
public readonly vpc: ec2.Vpc;
public readonly cluster: ecs.Cluster;
constructor(scope: Construct, id: string, props: MainStackProps) {
super(scope, id, props);
// Create VPC
this.vpc = new ec2.Vpc(this, 'Vpc', {
maxAzs: 3,
natGateways: 3,
subnetConfiguration: [
{
cidrMask: 24,
name: 'Public',
subnetType: ec2.SubnetType.PUBLIC,
},
{
cidrMask: 24,
name: 'Private',
subnetType: ec2.SubnetType.PRIVATE_WITH_EGRESS,
},
{
cidrMask: 28,
name: 'Database',
subnetType: ec2.SubnetType.PRIVATE_ISOLATED,
},
],
});
// Create ECS Cluster
this.cluster = new ecs.Cluster(this, 'Cluster', {
vpc: this.vpc,
containerInsights: true,
enableFargateCapacityProviders: true,
});
// Apply tags to all resources
cdk.Tags.of(this).add('Environment', props.environment);
cdk.Tags.of(this).add('Project', props.projectName);
}
}
```
## L3 Construct for Fargate Service
```typescript
// lib/constructs/fargate-api.ts
import * as cdk from 'aws-cdk-lib';
import * as ec2 from 'aws-cdk-lib/aws-ec2';
import * as ecs from 'aws-cdk-lib/aws-ecs';
import * as ecsPatterns from 'aws-cdk-lib/aws-ecs-patterns';
import * as logs from 'aws-cdk-lib/aws-logs';
import { Construct } from 'constructs';
export interface FargateApiProps {
cluster: ecs.ICluster;
image: ecs.ContainerImage;
containerPort: number;
cpu?: number;
memoryLimitMiB?: number;
desiredCount?: number;
environment?: Record<string, string>;
secrets?: Record<string, ecs.Secret>;
healthCheckPath?: string;
domainName?: string;
certificateArn?: string;
}
export class FargateApi extends Construct {
public readonly service: ecsPatterns.ApplicationLoadBalancedFargateService;
public readonly loadBalancerDnsName: string;
constructor(scope: Construct, id: string, props: FargateApiProps) {
super(scope, id);
// Create log group
const logGroup = new logs.LogGroup(this, 'LogGroup', {
retention: logs.RetentionDays.ONE_MONTH,
removalPolicy: cdk.RemovalPolicy.DESTROY,
});
// Create Fargate service with ALB
this.service = new ecsPatterns.ApplicationLoadBalancedFargateService(this, 'Service', {
cluster: props.cluster,
cpu: props.cpu || 256,
memoryLimitMiB: props.memoryLimitMiB || 512,
desiredCount: props.desiredCount || 2,
taskImageOptions: {
image: props.image,
containerPort: props.containerPort,
environment: props.environment,
secrets: props.secrets,
logDriver: ecs.LogDrivers.awsLogs({
streamPrefix: id,
logGroup,
}),
},
publicLoadBalancer: true,
circuitBreaker: { rollback: true },
});
// Configure health check
this.service.targetGroup.configureHealthCheck({
path: props.healthCheckPath || '/health',
healthyThresholdCount: 2,
unhealthyThresholdCount: 3,
interval: cdk.Duration.seconds(30),
timeout: cdk.Duration.seconds(5),
});
// Configure auto-scaling
const scaling = this.service.service.autoScaleTaskCount({
minCapacity: props.desiredCount || 2,
maxCapacity: 10,
});
scaling.scaleOnCpuUtilization('CpuScaling', {
targetUtilizationPercent: 70,
scaleInCooldown: cdk.Duration.seconds(300),
scaleOutCooldown: cdk.Duration.seconds(60),
});
scaling.scaleOnMemoryUtilization('MemoryScaling', {
targetUtilizationPercent: 80,
});
this.loadBalancerDnsName = this.service.loadBalancer.loadBalancerDnsName;
}
}
```
## RDS Database Construct
```typescript
// lib/constructs/database.ts
import * as cdk from 'aws-cdk-lib';
import * as ec2 from 'aws-cdk-lib/aws-ec2';
import * as rds from 'aws-cdk-lib/aws-rds';
import * as secretsmanager from 'aws-cdk-lib/aws-secretsmanager';
import { Construct } from 'constructs';
export interface DatabaseProps {
vpc: ec2.IVpc;
instanceType?: ec2.InstanceType;
allocatedStorage?: number;
databaseName: string;
allowedSecurityGroups?: ec2.ISecurityGroup[];
}
export class Database extends Construct {
public readonly instance: rds.DatabaseInstance;
public readonly secret: secretsmanager.ISecret;
public readonly securityGroup: ec2.SecurityGroup;
constructor(scope: Construct, id: string, props: DatabaseProps) {
super(scope, id);
// Create security group
this.securityGroup = new ec2.SecurityGroup(this, 'SecurityGroup', {
vpc: props.vpc,
description: 'Database security group',
});
// Allow connections from specified security groups
props.allowedSecurityGroups?.forEach(sg => {
this.securityGroup.addIngressRule(sg, ec2.Port.tcp(5432), 'Allow PostgreSQL');
});
// Create RDS instance
this.instance = new rds.DatabaseInstance(this, 'Instance', {
engine: rds.DatabaseInstanceEngine.postgres({
version: rds.PostgresEngineVersion.VER_15_4,
}),
instanceType: props.instanceType || ec2.InstanceType.of(
ec2.InstanceClass.T3,
ec2.InstanceSize.MEDIUM
),
vpc: props.vpc,
vpcSubnets: { subnetType: ec2.SubnetType.PRIVATE_ISOLATED },
securityGroups: [this.securityGroup],
databaseName: props.databaseName,
allocatedStorage: props.allocatedStorage || 20,
storageType: rds.StorageType.GP3,
storageEncrypted: true,
multiAz: true,
backupRetention: cdk.Duration.days(7),
deletionProtection: true,
removalPolicy: cdk.RemovalPolicy.SNAPSHOT,
});
this.secret = this.instance.secret!;
// Output
new cdk.CfnOutput(this, 'Endpoint', {
value: this.instance.instanceEndpoint.hostname,
});
}
}
```
## App Entry Point
```typescript
// bin/app.ts
import 'source-map-support/register';
import * as cdk from 'aws-cdk-lib';
import { MainStack } from '../lib/main-stack';
import { ApiStack } from '../lib/api-stack';
import { DatabaseStack } from '../lib/database-stack';
const app = new cdk.App();
const environment = app.node.tryGetContext('environment') || 'dev';
const projectName = app.node.tryGetContext('projectName') || 'myapp';
const env = {
account: process.env.CDK_DEFAULT_ACCOUNT,
region: process.env.CDK_DEFAULT_REGION || 'us-east-1',
};
const mainStack = new MainStack(app, `${projectName}-${environment}-main`, {
env,
environment,
projectName,
});
const databaseStack = new DatabaseStack(app, `${projectName}-${environment}-database`, {
env,
vpc: mainStack.vpc,
});
new ApiStack(app, `${projectName}-${environment}-api`, {
env,
cluster: mainStack.cluster,
database: databaseStack.database,
});
```
## Best Practices
1. **L3 Constructs**: Create high-level constructs for common patterns
2. **Stack Separation**: Split resources into logical stacks
3. **Context Values**: Use CDK context for environment configuration
4. **Aspects**: Apply cross-cutting concerns with aspects
5. **cdk.json**: Configure app settings and context defaults
6. **Testing**: Write unit tests with assertions
Google Antigravity's Gemini 3 can generate CDK constructs from architecture requirements and suggest best practices.This AWS CDK prompt is ideal for developers working on:
By using this prompt, you can save hours of manual coding and ensure best practices are followed from the start. It's particularly valuable for teams looking to maintain consistency across their aws cdk implementations.
Yes! All prompts on Antigravity AI Directory are free to use for both personal and commercial projects. No attribution required, though it's always appreciated.
This prompt works excellently with Claude, ChatGPT, Cursor, GitHub Copilot, and other modern AI coding assistants. For best results, use models with large context windows.
You can modify the prompt by adding specific requirements, constraints, or preferences. For AWS CDK projects, consider mentioning your framework version, coding style, and any specific libraries you're using.