Created
March 1, 2025 07:02
-
-
Save marweck/ba9a608f357eee9f1856cfb5a39679ad to your computer and use it in GitHub Desktop.
Standalone Fargate task definition
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import * as cdk from 'aws-cdk-lib'; | |
| import { Construct } from 'constructs'; | |
| import * as ec2 from 'aws-cdk-lib/aws-ec2'; | |
| import * as ecs from 'aws-cdk-lib/aws-ecs'; | |
| import * as iam from 'aws-cdk-lib/aws-iam'; | |
| import * as logs from 'aws-cdk-lib/aws-logs'; | |
| /** | |
| * You can run this task definition via CLI, SDK, lambda | |
| * CLI: aws ecs run-task --cluster <your-cluster-name> --task-definition <task-definition-arn> --launch-type FARGATE --network-configuration "awsvpcConfiguration={subnets=[<subnet-id>],securityGroups=[<security-group-id>],assignPublicIp=ENABLED}" | |
| */ | |
| export class FargateStandaloneStack extends cdk.Stack { | |
| constructor(scope: Construct, id: string, props?: cdk.StackProps) { | |
| super(scope, id, props); | |
| // Create a VPC (Virtual Private Cloud) | |
| const vpc = new ec2.Vpc(this, 'FargateVpc', { | |
| maxAzs: 2, // max availability zones | |
| natGateways: 1, // create NAT gateway for internet access | |
| }); | |
| // Create an ECS cluster | |
| const cluster = new ecs.Cluster(this, 'FargateCluster', { | |
| vpc, | |
| }); | |
| // Define a task definition for Fargate | |
| const taskDefinition = new ecs.FargateTaskDefinition(this, 'FargateTaskDef', { | |
| memoryLimitMiB: 1024, | |
| cpu: 512, | |
| }); | |
| // Add a container to the task definition | |
| taskDefinition.addContainer('FargateBatchContainer', { | |
| image: ecs.ContainerImage.fromRegistry('amazon/amazon-ecs-sample'), // Use a sample image from Amazon ECR | |
| logging: ecs.LogDrivers.awsLogs({ | |
| streamPrefix: 'FargateBatch', | |
| logGroup: new logs.LogGroup(this, 'FargateBatchLogGroup', { | |
| removalPolicy: cdk.RemovalPolicy.DESTROY, | |
| }), | |
| }), | |
| }); | |
| // You can trigger the task manually from other AWS services | |
| // For example, by creating a Lambda function or manually from AWS Console | |
| new cdk.CfnOutput(this, 'TaskDefinitionArn', { | |
| value: taskDefinition.taskDefinitionArn, | |
| description: 'The ARN of the task definition', | |
| }); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment