Tasks

A task is the translation of dynamic service information from the Consul Catalog into network infrastructure changes downstream. Consul-Terraform-Sync carries out automation for executing tasks using network drivers. For a Terraform driver, the scope of a task is a Terraform module.

Below is an example task configuration:

  1. task {
  2. name = "frontend-firewall-policies"
  3. description = "Add firewall policy rules for frontend services"
  4. providers = ["fake-firewall", "null"]
  5. services = ["web", "image"]
  6. source = "example/firewall-policy/module"
  7. version = "1.0.0"
  8. }

In the example task above, the “fake-firewall” and “null” providers, listed in the providers field, are used. These providers themselves should be configured in their own separate terraform_provider blocks. These providers are used in the Terraform module “example/firewall-policy/module”, configured in the source field, to create, update, and destroy resources. This module may do something like use the providers to create and destroy firewall policy objects based on IP addresses. The IP addresses come from the “web” and “image” service instances configured in the services field. This service-level information is retrieved by Consul-Terraform-Sync which watches Consul catalog for changes.

See task configuration for more details on how to configure a task.

A task can be either enabled or disabled using the task cli. When enabled, tasks are executed and automated as described in sections below. However, disabled tasks do not execute when changes are detected from Consul catalog. Since disabled tasks do not execute, they also do not store events until re-enabled.

Task Execution

An enabled task can be configured to monitor and execute on different types of conditions, such as changes to services (services condition) or service registration and deregistration (catalog-services condition).

A task can also monitor, but not execute on, other variables that provide additional information to the task’s module. For example, a task with a catalog-services condition may execute on registration changes, and monitor service instances for IP information.

A source input can be specified that implicitly includes variables to be provided to the task’s module. For example, a task can specify a Consul KV source input. The specified KV keys or key paths would be monitored for changes. Any changes detected would be included as input information for the modules. The module determines the details of what values are monitored and what values can execute the task.

The source input block is currently only supported when using a schedule condition. Adding a source input block alongside any other type of condition will result in an error. To accomplish a similar behaviour with other condition blocks, use the source_includes_var field.

Below are details on the types of execution conditions that Consul-Terraform-Sync supports.

Services Condition

The services condition is the default condition to execute a task. Tasks with the services condition monitor and execute on either changes to a list of configured services or changes to any services that match a given regex.

In order to configure a task with the services condition, the list of services to trigger the task must be configured in the task’s services or a regex must be configured in the task’s condition block. Only one of these two options can be configured for a single task. See the Services Condition configuration section for more details.

The services condition operates by monitoring the Health List Nodes For Service API and executing the task on any change of information for services configured. These changes include one or more changes to service values, like IP address, added or removed service instance, or tags. A complete list of values that would cause a task to run are expanded below:

AttributeDescription
idA unique Consul ID for this service. This is unique per Consul agent.
nameThe logical name of the service. Many service instances may share the same logical service name.
addressIP address of the service host — if empty, node address should be used.
portPort number of the service
metaList of user-defined metadata key/value pairs for the service
tagsList of tags for the service
namespaceConsul Enterprise namespace of the service instance
statusRepresentative status for the service instance based on an aggregate of the list of health checks
nodeName of the Consul node on which the service is registered
node_idID of the node on which the service is registered.
node_addressThe IP address of the Consul node on which the service is registered.
node_datacenterData center of the Consul node on which the service is registered.
node_tagged_addressesList of explicit LAN and WAN IP addresses for the agent
node_metaList of user-defined metadata key/value pairs for the node

The services condition is the default behavior if no condition block is configured for a task. The two tasks below have equivalent behavior, which is to execute when any of the listed services have changes to the previously stated attributes.

  1. task {
  2. name = "services_condition_task_1"
  3. description = "execute on changes to api, db, and web services"
  4. providers = ["my-provider"]
  5. source = "path/to/services-condition-module"
  6. services = ["api", "db", "web"]
  7. }
  8. task {
  9. name = "services_condition_task_2"
  10. description = "execute on changes to api, db, and web services"
  11. providers = ["my-provider"]
  12. source = "path/to/services-condition-module"
  13. services = ["api", "db", "web"]
  14. condition "services" {}
  15. }

Below is an example configuration for a task that will execute when a service with a name that matches the regular expression has a change. Note that because regexp is set, task.services is omitted.

  1. task {
  2. name = "services_condition_task"
  3. description = "execute on changes to services whose name starts with web"
  4. providers = ["my-provider"]
  5. source = "path/to/services-condition-module"
  6. condition "services" {
  7. regexp = "^web.*"
  8. }
  9. }

Catalog-Services Condition

Tasks with a catalog-services condition monitor and execute on service registration changes for services that satisfy the condition configuration. ‘Service registration changes’ specifically refers to service registration and deregistration where service registration occurs on the first service instance registration, and service deregistration occurs on the last service instance registration. Tasks with a catalog-services condition may, depending on the module, additionally monitor but not execute on service instance information.

The catalog-services condition operates by monitoring the Catalog List Services API and executing the task when services are added or removed in the list of registered services. Note, the task does not execute on changes to the tags of the list of services. This is similar to how changes to service instance information, mentioned above, also does not execute a task.

Below is an example configuration for a task that will execute when a service with a name that matches the “web.*“ regular expression in datacenter “dc1” has a registration change. It additionally monitors but does not execute on service instance changes to “web-api” in datacenter “dc2”.

  1. task {
  2. name = "catalog_service_condition_task"
  3. source = "path/to/catalog-services-module"
  4. providers = ["my-provider"]
  5. services = ["web-api"]
  6. condition "catalog-services" {
  7. datacenter = "dc1"
  8. regexp = "web.*"
  9. source_includes_var = false
  10. }
  11. }
  12. service {
  13. name = "web-api"
  14. datacenter = "dc2"
  15. }

The module selected for a task will likely determine whether the task should be configured with a catalog-services condition. Module authors have the option to include and use the catalog_services input variable in addition to the required services variable. When this variable is included in the module, the user of this module will need to configure the task condition’s source_includes_var value to be true. Catalog-Services condition modules should have the condition type and source_includes_var configuration value documented for users to reference when configuring a task.

In addition to source_includes_var, a task’s catalog-services condition has other configuration fields that can be used to specify which services’ registration changes should execute the task. For example, registration changes can be filtered for services in a specific datacenter or namespace. See the Catalog-Services Condition configuration section for more details.

One particular condition configuration, regexp, filters service registration changes by services that have a name which matches the configured regular expression. When unconfigured, the regexp value will default to match on any service that has a name which matches the services listed in task.services. As such, either regexp or task.services must be configured. When both are configured, see example above, the task will monitor and execute on registration changes to services matching the regexp, and the task will additionally monitor but not execute on service instances listed in task.services to optionally provide additional service information to the module.

Consul KV Condition

Tasks with a consul-kv condition monitor and execute on Consul KV changes for KV pairs that satisfy the condition configuration. The consul-kv condition operates by monitoring the Consul KV API and executing the task when a configured KV entry is created, deleted, or updated.

Based on the recurse option, the condition either monitors a single Consul KV pair for a given path or monitors all pairs that are prefixed by that path. In the example below, because recurse is set to true, the path option is treated as a prefix. Changes to an entry with the key my-key and an entry with the key my-key/another-key would both trigger the task. If recurse were set to false, then only changes to my-key would trigger the task.

  1. task {
  2. name = "consul_kv_condition_task"
  3. description = "execute on changes to Consul KV entry"
  4. source = "path/to/consul-kv-module"
  5. providers = ["my-provider"]
  6. services = ["web-api"]
  7. condition "consul-kv" {
  8. path = "my-key"
  9. recurse = true
  10. datacenter = "dc1"
  11. namespace = "default"
  12. source_includes_var = true
  13. }
  14. }

If the task condition’s source_includes_var field is set to true, then the value of the Consul KV pair(s) will be available in the consul_kv input variable. To use the variable, add consul_kv as an input variable to the module, in addition to the required services variable. The condition type and source_includes_var configuration value should be documented in the module so that users can reference them when configuring a task.

Schedule Condition

All scheduled tasks must be configured with a schedule condition. The schedule condition sets the cadence to trigger a task with a cron configuration. The schedule condition block does not support parameters to configure source input. As a result, inputs must be configured separately. You can configure task.services or a source_input block to set the source input.

Below is an example configuration for a task that will execute every Monday, which is set by the schedule condition’s cron configuration. The source input is defined by the task.services configuration. When the task is triggered on Monday, it will retrieve the latest information on “web” and “db” from Consul and provide this to the module’s input variables.

  1. task {
  2. name = "scheduled_task"
  3. description = "execute every Monday using service information from web and db"
  4. services = ["web", "db"]
  5. source = "path/to/module"
  6. condition "schedule" {
  7. cron = "* * * * Mon"
  8. }
  9. }

Below are the available options for source input types and how to configure them:

Running Behavior

Scheduled tasks generally run on schedule, but they can be triggered on demand when running Consul-Terraform-Sync in the following ways:

  • Long-running mode: At the beginning of the long-running mode, Consul-Terraform-Sync first passes through a once-mode phase in which all tasks are executed once. Scheduled tasks will trigger once during this once-mode phase. This behavior also applies to tasks that are not scheduled. After once-mode has completed, scheduled tasks subsequently trigger on schedule.

  • Inspect mode: When running in inspect mode, the terminal will output a plan of proposed updates that would be made if the tasks were to trigger at that moment and then exit. No changes are applied in this mode. The outputted plan for a scheduled task is also the proposed updates that would be made if the task was triggered at that moment, even if off-schedule.

  • Once mode: During the once mode, all tasks are only triggered one time. Scheduled tasks will execute during once mode even if not on the schedule.

  • Enable CLI: When a task is enabled through the CLI, any type of task, including scheduled tasks, will be triggered at that time.

Buffer Period

Because scheduled tasks trigger on a configured cadence, buffer periods are disabled for scheduled tasks. Any configured buffer_period at the global level or task level will only apply to dynamic tasks and not scheduled ones.

Events

Events are stored each time a task executes. For scheduled tasks, an event will be stored each time the task triggers on schedule regardless of if there was a change in Consul catalog.

Task Automation

Consul-Terraform-Sync will attempt to execute each enabled task once upon startup to synchronize infrastructure with the current state of Consul. The daemon will stop and exit if any error occurs while preparing the automation environment or executing a task for the first time. This helps ensure tasks have proper configuration and are executable before the daemon transitions into running tasks in full automation as service changes are discovered over time. As a result, it is not recommended to configure a task as disabled from the start. After all tasks have successfully executed once, task failures during automation will be logged and retried or attempted again after a subsequent change.

Tasks are executed near-real time when service changes are detected. For services or environments that are prone to flapping, it may be useful to configure a buffer period for a task to accumulate changes before it is executed. The buffer period would reduce the number of consecutive network calls to infrastructure by batching changes for a task over a short duration of time.

Status Information

Status-related information is collected and offered via status API to provide visibility into what and how the tasks are running. Information is offered in three-levels (lowest to highest):

  • Event data
  • Task status
  • Overall status

These three levels form a hierarchy where each level of data informs the one higher. The lowest-level, event data, is collected each time a task runs to update network infrastructure. This event data is then aggregated to inform individual task statuses. The count distribution of all the task statuses inform the overall status’s task summary.

Event

When a task is triggered, Consul-Terraform-Sync takes a series of steps in order to update the network infrastructure. These steps consist of fetching the latest data from Consul for the task’s source inputs and then updating the network infrastructure accordingly. An event captures information across this process. It stores information to help understand if the update to network infrastructure was successful or not and any errors that may have occurred.

A dynamic task will store an event when it is triggered by a change in Consul. A scheduled task will store an event when it is triggered on schedule, regardless if there is a change in Consul. A disabled task does not update network infrastructures, so it will not store events until until re-enabled.

Sample event:

  1. {
  2. "id": "ef202675-502f-431f-b133-ed64d15b0e0e",
  3. "success": false,
  4. "start_time": "2020-11-24T12:05:18.651231-05:00",
  5. "end_time": "2020-11-24T12:05:20.900115-05:00",
  6. "task_name": "task_b",
  7. "error": {
  8. "message": "example error: error while doing terraform-apply"
  9. },
  10. ...
  11. }

For complete information on the event structure, see events in our API documentation. Event information can be retrieved by using the include=events parameter with the task status API.

Task Status

Each time a task runs to update network infrastructure, event data is stored for that run. 5 most recent events are stored for each task, and these stored events are used to determine task status. For example, if the most recent stored event is not successful but the others are, then the task’s health status is “errored”.

Sample task status:

  1. {
  2. "task_name": "task_b",
  3. "status": "errored",
  4. "providers": ["null"],
  5. "services": ["web"],
  6. "events_url": "/v1/status/tasks/task_b?include=events"
  7. }

Task status information can be retrieved with task status API. The API documentation includes details on what health statuses are available and how it is calculated based on events’ success/failure information.

Overall Status

Overall status returns a summary of the health statuses across all tasks. The summary is the count of tasks in each health status category.

Sample overall status:

  1. {
  2. "task_summary": {
  3. "successful": 28,
  4. "errored": 5,
  5. "critical": 1
  6. }
  7. }

Overall status information can be retrieved with overall status API. The API documentation includes details on what health statuses are available and how it is calculated based on task statuses’ health status information.