»lifecycle Stanza

Placementjob -> group -> task -> lifecycle

The lifecycle stanza is used to express task dependencies in Nomad and configures when a task is run within the lifecycle of a task group.

Main tasks are tasks that do not have a lifecycle stanza. Lifecycle task hooks are run in relation to the main tasks. Tasks can be run as Prestart Hooks, which ensures the prestart task is run before the main tasks are run.

Tasks can be run with an additional parameter to indicate that they are sidecars, which ensures that they are running over the duration of the whole task group. This will allow you to run a long-lived task in a task group for a batch job. The absence of the sidecar flag indicates that the task is ephemeral and the task will not be restarted if it completes successfully. This allows you to run an ephemeral prestart task in a task group for a service job, which can serve as initialization that occurs before the main services are started.

Learn more about Nomad's task dependencies on the HashiCorp Learn website.

job "docs" {
  group "example" {

    task "init" {
      lifecycle {
        hook    = "prestart"
      }
      ...
    }

    task "logging" {
      lifecycle {
        hook    = "prestart"
        sidecar = true
      }
      ...
    }

    task "main" {
      ...
    }

  }
}

»lifecycle Parameters

  • hook (string: "prestart") - Specifies when a task should be run within the lifecycle of a group. Currently only Prestart Hooks are supported.

  • sidecar (bool: false) - Controls whether or not a task is ephemeral or long-lived within the task group. If a lifecycle task is ephemeral (sidecar = false), the task will not be restarted after it completes successfully. If a lifecycle task is long-lived (sidecar = true) and it terminates, it will be restarted as long as the task group is running in its allocation.