Search code examples
amazon-ecs

AWS ECS. How to ensure only one instance of a task is running?


I'm wanting to setup an ECS task to schedule various other application tasks.

The "tasks" this task will schedule will mostly involve calling restful endpoints in another load balanced service.

I know there are other ways to do this, using cloudwatch to trigger a lambda etc. However this seems overly complex for what I need.

I was planning to just make a very simple, light-weight apline based image with a crontab to do the triggering of the restful calls.

This all seems easy enough. The only concern I have is that I would want to prevent, as far as possible, having multiple instances of this task running, even if only for a short period of time.

If my CI/CD pipeline triggers an update to this cron task, then there may be a short period of time, where the old and new task will be running simultaneously.

There may therefore be a small chance that a cron task could be triggered twice.

What I would like to do, is to have ECS stop the currently running task completely, before attempting to start the new one.

This seems to be contrary to the normal way it wants to work, where it will ensure the new task is up, and healthy before stopping the old one.

Is this possible, and if so, how do I configure it?

It's not a problem if my crons don't run for a period of time, but it could be a problem if any get triggered more than once.


Solution

  • Instead of using ECS Service (which makes sure a particular number of tasks is always running and deploys via rolling or B/G deploy strategy which is not you desire) - how about using StopTask and RunTask api to control when a task is stopped and started - gives you complete control.