Certainly! Here's an example of a serverless.yml file that creates 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
custom:
ecrRepository: my-ecr-repository
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: ${self:custom.ecrRepository}:latest
Memory: 512
Cpu: 256
PeriodicTaskSchedule:
Type: AWS::Events::Rule
Properties:
Name: my-periodic-task-schedule
ScheduleExpression: rate(1 hour)
State: ENABLED
Targets:
- Id: my-periodic-task-target
Arn: !GetAtt PeriodicTaskDefinition.Arn
RoleArn: !GetAtt PeriodicTaskExecutionRole.Arn
EcsParameters:
TaskDefinitionArn: !Ref PeriodicTaskDefinition
TaskCount: 1
PeriodicTaskExecutionRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Service:
- events.amazonaws.com
Action: sts:AssumeRole
Policies:
- PolicyName: PeriodicTaskExecutionPolicy
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- ecs:RunTask
Resource: '*'
In this example:
-
The provider section specifies the cloud provider (AWS), runtime (Python 3.8), and the region where the resources will be deployed.
-
The custom section defines a custom variable ecrRepository that holds the name of the ECR repository where the container image is stored.
-
The functions section defines a dummy function named periodicTask with a schedule event that triggers the task every hour. The actual task execution is handled by ECS.
-
The resources section defines the necessary AWS resources:
PeriodicTaskDefinition: An ECS task definition that specifies the container image to be used, memory and CPU requirements.
PeriodicTaskSchedule: An AWS Events rule that triggers the task on a schedule (every hour in this example).
PeriodicTaskExecutionRole: An IAM role that allows AWS Events to run the ECS task.
-
The Image property in the ContainerDefinitions section references the ECR repository using the ${self:custom.ecrRepository}:latest syntax, assuming the latest tag is used for the image.
When you deploy this serverless configuration using the serverless deploy command, it will create the necessary resources in AWS to run the periodic ECS task using the specified container image from ECR.
Note: Make sure to replace my-ecr-repository with the actual name of your ECR repository, and adjust the memory and CPU requirements according to your task's needs.