Search code examples
migrationamazon-ecsknex.js

Knex.js execute migrations and wait for completed execution in aws ecs


In my GitLab pipeline, I am executing the following task

- aws ecs run-task --profile gitlab --cluster $SERVER_CLUSTER_ARN --task-definition $TASK_DEF_ARN --network-configuration '{"awsvpcConfiguration":{"subnets":["'$SUBNET_ID'"]}}' --launch-type FARGATE --overrides '{"containerOverrides":[{"environment":[{"name":"MONGO_DB","value":"'$MONGO_DB'"},{"name":"DB_USER","value":"'$DB_USER'"},{"name":"DB_PASS","value":"'$DB_PASS'"}],"name":"lh-server","command":["app/run-fargate-migrations.js"]}]}'

And then, the script I run is the following

async function runMigrations () {
  console.log('Running MySQL migrations...')
  console.log('mongo-url:', mongoConfig.mongodb.url)
  console.log('mongo-databaseName:', mongoConfig.mongodb.databaseName)

  knexConfig.development.migrations.directory = '/app/db/knex/migrations'
  knexConfig.development.migrations.stub = '/app/db/knex/migration.stub'

  const knexInstance = knex(knexConfig.development)
  await knexInstance.migrate.latest()

  console.log('Done')
}

runMigrations().then(() => {
  console.log('All migrations have been applied successfully')
  process.exit(0)
}).catch(e => {
  console.error('Error while applying migrations:', e)
  process.exit(1)
})

But the pipeline gets green before all the migrations are executed. How can I wait for all the migrations to be executed before moving forward?


Solution

  • In your pipeline, you need to capture the task ID that is returned from the aws ecs run-task command, and then wait on the task to stop, via the aws ecs wait task-stopped command.