Search code examples
amazon-web-servicesdockerscheduled-tasksamazon-ecsaws-fargate

Start TaskDefinition from AWS::Events::Rule with parameter


we have got a TaskDefinition of type FARGATE which is starting a Docker container in ECS which is executing a Kotlin application. When the application terminates the container and related task are killed.

This TaskDefinition is started by a ScheduledTask which has the TaskDefinition as target:

  TaskSchedule:
    Type: AWS::Events::Rule
    Properties:
      Description: "My amazing rule"
      ScheduleExpression: "cron(0 12 1 2 ? *)"
      State: "ENABLED"
      Targets:
        - Arn:
            'Fn::ImportValue': !Sub "${ApplicationName}-cluster"
          Id: !Sub "${ApplicationName}-${EnvironmentName}-task-id"
          RoleArn: !GetAtt TaskSchedulerRole.Arn
          EcsParameters:
            LaunchType: "FARGATE"
            TaskCount: 1
            TaskDefinitionArn: !Ref TaskDefinition

Now, we have the need of having two different ScheduledTask that will start the application with different parameters. The parameter will have to be used as environment variable.

The easy way of doing this would be having two task definitions, each one with its own environment variable like:

Environment:
   - Name: VARIABLE
     Value: "value"

and two separate AWS::Events::Rule rules each invoking its task definition:

Rule 1 -> TaskDefinition1 (with variable 1) -> start application with VARIABLE_1
Rule 2 -> TaskDefinition2 (with variable 2) -> start application with VARIABLE_2

Considering the task definitions would be totally duplicated and the only difference would be the environment variable, isn't there a way of defining a parameter in the rule which is then passed to the task definition? I can see there's a Input property that can be specified in the Target section of the rule, which seems to be a valid json string, but I can't figure out how that is supposed to be used on the task definition side.

Thanks!


Solution

  • This is how I solved the issue:

    Input: !Sub '{ "containerOverrides": [{"name": "container-name", "environment": [{"name":"VARIABLE", "value": "override value"}]}]}'
    

    This is overriding the value of the passed environment variable inside the container.