open-consul/website/content/docs/nia/tasks.mdx
Kim Ngo da26191d11
Add protocol example for TFC driver address (#11319)
* Add protocol example for TFC driver address
* Format cts code blocks
2021-10-15 11:01:10 -05:00

284 lines
20 KiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

---
layout: docs
page_title: Tasks
description: >-
Consul-Terraform-Sync Tasks
---
# 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:
```hcl
task {
name = "frontend-firewall-policies"
description = "Add firewall policy rules for frontend services"
providers = ["fake-firewall", "null"]
services = ["web", "image"]
source = "example/firewall-policy/module"
version = "1.0.0"
}
```
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](/docs/nia/configuration#terraform-provider). 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](/docs/nia/configuration#task) for more details on how to configure a task.
A task can be either enabled or disabled using the [task cli](/docs/nia/cli/task). 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](/docs/nia/tasks#event) 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](/docs/nia/tasks#services-condition)) or service registration and deregistration ([catalog-services condition](/docs/nia/tasks#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 tasks 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`](/docs/nia/configuration#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](/docs/nia/configuration#services-condition) configuration section for more details.
The services condition operates by monitoring the [Health List Nodes For Service API](/api-docs/health#list-nodes-for-service) 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:
| Attribute | Description |
| ----------------------- | ------------------------------------------------------------------------------------------------- |
| `id` | A unique Consul ID for this service. This is unique per Consul agent. |
| `name` | The logical name of the service. Many service instances may share the same logical service name. |
| `address` | IP address of the service host -- if empty, node address should be used. |
| `port` | Port number of the service |
| `meta` | List of user-defined metadata key/value pairs for the service |
| `tags` | List of tags for the service |
| `namespace` | Consul Enterprise namespace of the service instance |
| `status` | Representative status for the service instance based on an aggregate of the list of health checks |
| `node` | Name of the Consul node on which the service is registered |
| `node_id` | ID of the node on which the service is registered. |
| `node_address` | The IP address of the Consul node on which the service is registered. |
| `node_datacenter` | Data center of the Consul node on which the service is registered. |
| `node_tagged_addresses` | List of explicit LAN and WAN IP addresses for the agent |
| `node_meta` | List 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.
```hcl
task {
name = "services_condition_task_1"
description = "execute on changes to api, db, and web services"
providers = ["my-provider"]
source = "path/to/services-condition-module"
services = ["api", "db", "web"]
}
task {
name = "services_condition_task_2"
description = "execute on changes to api, db, and web services"
providers = ["my-provider"]
source = "path/to/services-condition-module"
services = ["api", "db", "web"]
condition "services" {}
}
```
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.
```hcl
task {
name = "services_condition_task"
description = "execute on changes to services whose name starts with web"
providers = ["my-provider"]
source = "path/to/services-condition-module"
condition "services" {
regexp = "^web.*"
}
}
```
### 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](/api-docs/catalog#list-services) 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".
```hcl
task {
name = "catalog_service_condition_task"
source = "path/to/catalog-services-module"
providers = ["my-provider"]
services = ["web-api"]
condition "catalog-services" {
datacenter = "dc1"
regexp = "web.*"
source_includes_var = false
}
}
service {
name = "web-api"
datacenter = "dc2"
}
```
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](/docs/nia/terraform-modules#catalog-services-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`](/docs/nia/configuration#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](/docs/nia/configuration#catalog-services-condition) configuration section for more details.
One particular condition configuration, [`regexp`](/docs/nia/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`](/docs/nia/configuration#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](/api-docs/kv#read-key) 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.
```hcl
task {
name = "consul_kv_condition_task"
description = "execute on changes to Consul KV entry"
source = "path/to/consul-kv-module"
providers = ["my-provider"]
services = ["web-api"]
condition "consul-kv" {
path = "my-key"
recurse = true
datacenter = "dc1"
namespace = "default"
source_includes_var = true
}
}
```
If the task condition's [`source_includes_var`](/docs/nia/configuration#source_includes_var-1) field is set to `true`, then the value of the Consul KV pair(s) will be available in the [`consul_kv` input variable](/docs/nia/terraform-modules#consul-kv-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`](/docs/nia/configuration#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`](/docs/nia/configuration#services) or a [`source_input` block](/docs/nia/configuration#source_input) to set the source input.
Below is an example configuration for a task that will execute every Monday, which is set by the schedule conditions [`cron`](/docs/nia/configuration#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 modules input variables.
```hcl
task {
name = "scheduled_task"
description = "execute every Monday using service information from web and db"
services = ["web", "db"]
source = "path/to/module"
condition "schedule" {
cron = "* * * * Mon"
}
}
```
Below are the available options for source input types and how to configure them:
- [Services source input](/docs/nia/terraform-modules/#services-source-input): configure through [`task.services`](/docs/nia/configuration#services) or [`source_input "services"`](/docs/nia/configuration#services-source-input)
- [Consul KV source input](/docs/nia/terraform-modules/#consul-kv-source-input): configure through [`source_input "consul-kv"`](/docs/nia/configuration#consul-kv-source-input)
#### 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](/docs/nia/cli#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](/docs/nia/cli#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](/docs/nia/cli#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](/docs/nia/cli/task#task-enable): 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](#event) 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](/docs/nia/configuration#buffer_period-1) 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](/docs/nia/api#status) 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:
```json
{
"id": "ef202675-502f-431f-b133-ed64d15b0e0e",
"success": false,
"start_time": "2020-11-24T12:05:18.651231-05:00",
"end_time": "2020-11-24T12:05:20.900115-05:00",
"task_name": "task_b",
"error": {
"message": "example error: error while doing terraform-apply"
},
...
}
```
For complete information on the event structure, see [events in our API documentation](/docs/nia/api#event). Event information can be retrieved by using the [`include=events` parameter](/docs/nia/api#include) with the [task status API](/docs/nia/api#task-status).
### 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:
```json
{
"task_name": "task_b",
"status": "errored",
"providers": ["null"],
"services": ["web"],
"events_url": "/v1/status/tasks/task_b?include=events"
}
```
Task status information can be retrieved with [task status API](/docs/nia/api#task-status). 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:
```json
{
"task_summary": {
"successful": 28,
"errored": 5,
"critical": 1
}
}
```
Overall status information can be retrieved with [overall status API](/docs/nia/api#overall-status). The API documentation includes details on what health statuses are available and how it is calculated based on task statuses' health status information.