Skip to content

Instantly share code, notes, and snippets.

@satoshi256kbyte
Last active March 29, 2024 22:05
Show Gist options
  • Save satoshi256kbyte/ef99dfe6016c1a75265a2e533f2a93a5 to your computer and use it in GitHub Desktop.
Save satoshi256kbyte/ef99dfe6016c1a75265a2e533f2a93a5 to your computer and use it in GitHub Desktop.
【サンプルコード】AWS SAMでAWS StepFunctionsからAmazon ECS on Fargateのタスクを起動する
# More information about the configuration file can be found here:
# https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-config.html
version = 0.1
[default]
[default.global.parameters]
stack_name = "sam-app"
[default.build.parameters]
cached = true
parallel = true
[default.validate.parameters]
lint = true
[default.deploy.parameters]
capabilities = "CAPABILITY_IAM CAPABILITY_NAMED_IAM CAPABILITY_AUTO_EXPAND"
confirm_changeset = true
resolve_s3 = true
parameter_overrides = [
"ClusterArn=xxx",
"TaskDefinitionArn=xxx",
"ContainerName=xxx",
"SubnetId=xxx",
"SecurityGroupId=xxx",
"TaskExecutionRoleArn=xxx",
"TaskRoleArn=xxx"
]
[default.package.parameters]
resolve_s3 = true
[default.sync.parameters]
watch = true
[default.local_start_api.parameters]
warm_containers = "EAGER"
[default.local_start_lambda.parameters]
warm_containers = "EAGER"
{
"Comment": "A state machine that does mock stock trading.",
"StartAt": "Check Stock Value",
"States": {
"Check Stock Value": {
"Type": "Task",
"Resource": "${StockCheckerFunctionArn}",
"Retry": [
{
"ErrorEquals": [
"States.TaskFailed"
],
"IntervalSeconds": 15,
"MaxAttempts": 5,
"BackoffRate": 1.5
}
],
"Next": "Buy or Sell?"
},
"Buy or Sell?": {
"Type": "Choice",
"Choices": [
{
"Variable": "$.stock_price",
"NumericLessThanEquals": 50,
"Next": "Buy Stock"
}
],
"Default": "Sell Stock"
},
"Sell Stock": {
"Type": "Task",
"Resource": "${StockSellerFunctionArn}",
"Retry": [
{
"ErrorEquals": [
"States.TaskFailed"
],
"IntervalSeconds": 2,
"MaxAttempts": 3,
"BackoffRate": 1
}
],
"Next": "Record Transaction"
},
"Buy Stock": {
"Type": "Task",
"Resource": "${StockBuyerFunctionArn}",
"Retry": [
{
"ErrorEquals": [
"States.TaskFailed"
],
"IntervalSeconds": 2,
"MaxAttempts": 3,
"BackoffRate": 1
}
],
"Next": "Record Transaction"
},
"Record Transaction": {
"Type": "Task",
"Resource": "${DDBPutItem}",
"Parameters": {
"TableName": "${DDBTable}",
"Item": {
"Id": {
"S.$": "$.id"
},
"Type": {
"S.$": "$.type"
},
"Price": {
"N.$": "$.price"
},
"Quantity": {
"N.$": "$.qty"
},
"Timestamp": {
"S.$": "$.timestamp"
}
}
},
"Retry": [
{
"ErrorEquals": [
"States.TaskFailed"
],
"IntervalSeconds": 20,
"MaxAttempts": 5,
"BackoffRate": 10
}
],
"Next": "Run ECS task"
},
"Run ECS task": {
"Type": "Task",
"Resource": "arn:aws:states:::ecs:runTask.sync",
"Parameters": {
"LaunchType": "FARGATE",
"Cluster": "${ClusterArn}",
"TaskDefinition": "${TaskDefinitionArn}",
"NetworkConfiguration": {
"AwsvpcConfiguration": {
"AssignPublicIp": "ENABLED",
"SecurityGroups": [
"${SecurityGroupId}"
],
"Subnets": [
"${SubnetId}"
]
}
},
"Overrides": {
"ContainerOverrides": [
{
"Name": "${ContainerName}",
"Command": [
"--arg1",
"200",
"--arg2",
"200"
]
}
]
}
},
"Next": "Success",
"Catch": [
{
"ErrorEquals": [
"States.TaskFailed"
],
"Next": "Error"
}
]
},
"Success": {
"Type": "Pass",
"Comment": "Success",
"End": true
},
"Error": {
"Type": "Pass",
"Comment": "Error",
"End": true
}
}
}
AWSTemplateFormatVersion: "2010-09-09"
Transform: AWS::Serverless-2016-10-31
Description: >
sam-app
Sample SAM Template for sam-app
Parameters:
ClusterArn:
Type: String
TaskDefinitionArn:
Type: String
ContainerName:
Type: String
SubnetId:
Type: String
SecurityGroupId:
Type: String
TaskExecutionRoleArn:
Type: String
TaskRoleArn:
Type: String
Resources:
StockTradingStateMachine:
Type: AWS::Serverless::StateMachine # More info about State Machine Resource: https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-resource-statemachine.html
Properties:
Name: StockTradingStateMachine # Add
DefinitionUri: statemachine/stock_trader.asl.json
DefinitionSubstitutions:
StockCheckerFunctionArn: !GetAtt StockCheckerFunction.Arn
StockSellerFunctionArn: !GetAtt StockSellerFunction.Arn
StockBuyerFunctionArn: !GetAtt StockBuyerFunction.Arn
DDBPutItem: !Sub arn:${AWS::Partition}:states:::dynamodb:putItem
DDBTable: !Ref TransactionTable
ClusterArn: !Ref ClusterArn # Add
ContainerName: !Ref ContainerName # Add
TaskDefinitionArn: !Ref TaskDefinitionArn # Add
SubnetId: !Ref SubnetId # Add
SecurityGroupId: !Ref SecurityGroupId # Add
Role: !GetAtt StockTradingStateMachineRole.Arn # Modify
StockCheckerFunction:
Type: AWS::Serverless::Function # More info about Function Resource: https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-resource-function.html
Properties:
CodeUri: functions/stock_checker/
Handler: app.lambda_handler
Runtime: python3.10
Architectures:
- x86_64
StockSellerFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: functions/stock_seller/
Handler: app.lambda_handler
Runtime: python3.10
Architectures:
- x86_64
StockBuyerFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: functions/stock_buyer/
Handler: app.lambda_handler
Runtime: python3.10
Architectures:
- x86_64
TransactionTable:
Type: AWS::Serverless::SimpleTable # More info about SimpleTable Resource: https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-resource-simpletable.html
Properties:
PrimaryKey:
Name: Id
Type: String
ProvisionedThroughput:
ReadCapacityUnits: 1
WriteCapacityUnits: 1
#----------------------------------------
# IAM Role
#----------------------------------------
StockTradingStateMachineRole:
Type: AWS::IAM::Role
Properties:
RoleName: StockTradingStateMachineRole
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Service:
- states.amazonaws.com
Action: sts:AssumeRole
Policies:
- PolicyName: TaskRunnerStateMachinePolicy
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- ecs:RunTask
Resource:
- !Ref TaskDefinitionArn
- Effect: Allow
Action:
- ecs:StopTask
- ecs:DescribeTasks
Resource:
- "*"
- Effect: Allow
Action:
- events:PutTargets
- events:PutRule
- events:DescribeRule
Resource:
- !Sub arn:aws:events:${AWS::Region}:${AWS::AccountId}:rule/StepFunctionsGetEventsForECSTaskRule
- Effect: Allow
Action:
- iam:PassRole
Resource:
- !Ref TaskExecutionRoleArn
- !Ref TaskRoleArn
- Effect: Allow
Action:
- lambda:InvokeFunction
Resource:
- !GetAtt StockCheckerFunction.Arn
- !GetAtt StockSellerFunction.Arn
- !GetAtt StockBuyerFunction.Arn
- Effect: Allow
Action:
- dynamodb:PutItem
- dynamodb:UpdateItem
- dynamodb:BatchWriteItem
Resource:
- !GetAtt TransactionTable.Arn
Outputs:
# StockTradingStateMachineHourlyTradingSchedule is an implicit Schedule event rule created out of Events key under Serverless::StateMachine
# Find out more about other implicit resources you can reference within SAM
# https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-specification-generated-resources.html
StockTradingStateMachineArn:
Description: "Stock Trading State machine ARN"
Value: !Ref StockTradingStateMachine
StockTradingStateMachineRoleArn:
Description: "IAM Role created for Stock Trading State machine based on the specified SAM Policy Templates"
Value: !GetAtt StockTradingStateMachineRole.Arn
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment