Certainly! Here's an example serverless.yml file that demonstrates how to create a periodic ECS task using an image stored in ECR on AWS:
service: my-periodic-task
provider:
name: aws
runtime: python3.8
region: us-west-2
functions:
periodicTask:
handler: handler.run
events:
- schedule: rate(1 hour)
resources:
Resources:
PeriodicTaskDefinition:
Type: AWS::ECS::TaskDefinition
Properties:
Family: my-periodic-task
ContainerDefinitions:
- Name: my-container
Image: ${aws:accountId}.dkr.ecr.${aws:region}.amazonaws.com/my-ecr-repository:latest
Memory: 512
Cpu: 256
Essential: true
LogConfiguration:
LogDriver: awslogs
Options:
awslogs-group: /ecs/my-periodic-task
awslogs-region: ${aws:region}
awslogs-stream-prefix: ecs
PeriodicTaskSchedule:
Type: AWS::Events::Rule
Properties:
Name: my-periodic-task-schedule
ScheduleExpression: rate(1 hour)
State: ENABLED
Targets:
- Id: my-periodic-task-target
Arn: ${aws:accountId}:cluster:my-ecs-cluster
RoleArn: ${aws:accountId}:role/ecsEventsRole
EcsParameters:
TaskDefinitionArn: !Ref PeriodicTaskDefinition
TaskCount: 1
ECSCluster:
Type: AWS::ECS::Cluster
Properties:
ClusterName: my-ecs-cluster
plugins:
- serverless-python-requirements
Let's go through the important parts of this serverless.yml file:
-
The provider section specifies the cloud provider (AWS), runtime (Python 3.8), and the region where the resources will be deployed.
-
The functions section defines a single function named periodicTask. The handler property specifies the Python function that will be executed when the task runs. The events property sets up a scheduled event that triggers the task every hour using the rate expression.
-
The resources section defines the necessary AWS resources for the periodic ECS task:
PeriodicTaskDefinition: This is the ECS task definition that specifies the container configuration. It includes the container name, image URI (referencing the image in ECR), memory and CPU allocations, and logging configuration.
PeriodicTaskSchedule: This is an AWS Events rule that defines the schedule for triggering the periodic task. It uses the rate expression to run the task every hour and targets the specified ECS cluster and task definition.
ECSCluster: This creates an ECS cluster where the periodic task will run.
-
The plugins section includes the serverless-python-requirements plugin, which helps in packaging and deploying Python dependencies.
Make sure to replace the placeholders (my-periodic-task, my-ecr-repository, my-ecs-cluster, etc.) with your actual resource names and configurations.
To deploy this serverless application, you can run the following command:
serverless deploy
This will create the necessary AWS resources and set up the periodic ECS task based on the provided configuration.
Note: Make sure you have the necessary permissions and roles set up in your AWS account to create and manage ECS tasks, ECR repositories, and other related resources.