# Workflow Variables Some fields in a workflow specification allow for variable references which are automatically substituted by Argo. ## How to use variables Variables are enclosed in curly braces: ```yaml apiVersion: argoproj.io/v1alpha1 kind: Workflow metadata: generateName: hello-world-parameters- spec: entrypoint: print-message arguments: parameters: - name: message value: hello world templates: - name: print-message inputs: parameters: - name: message container: image: busybox command: [ echo ] args: [ "{{inputs.parameters.message}}" ] ``` The following variables are made available to reference various meta-data of a workflow: ## Template Tag Kinds There are two kinds of template tag: * **simple** The default, e.g. `{{workflow.name}}` * **expression** Where`{{` is immediately followed by `=`, e.g. `{{=workflow.name}}`. ### Simple The tag is substituted with the variable that has a name the same as the tag. Simple tags **may** have white-space between the brackets and variable as seen below. However, there is a known issue where variables may fail to interpolate with white-space, so it is recommended to avoid using white-space until this issue is resolved. [Please report](https://github.com/argoproj/argo-workflows/issues/8960) unexpected behavior with reproducible examples. ```yaml args: [ "{{ inputs.parameters.message }}" ] ``` ### Expression The tag is substituted with the result of evaluating the tag as an expression. Note that any hyphenated parameter names or step names will cause a parsing error. You can reference them by indexing into the parameter or step map, e.g. `inputs.parameters['my-param']` or `steps['my-step'].outputs.result`. [Learn more about the expression syntax](https://expr-lang.org/docs/language-definition). #### Examples Plain list: ```text [1, 2] ``` Filter a list: ```text filter([1, 2], { # > 1}) ``` Map a list: ```text map([1, 2], { # * 2 }) ``` Cast to int: ```text asInt(inputs.parameters['my-int-param']) ``` Cast to float: ```text asFloat(inputs.parameters['my-float-param']) ``` Cast to string: ```text string(1) ``` We provide some additional functions: Convert to a JSON string (needed for `withParam`): ```text toJson([1, 2]) ``` `toJson` is the same as [expr's built-in `toJSON` function](https://expr-lang.org/docs/language-definition#toJSON), except `toJson` does not add indentation. Extract data from JSON: ```text jsonpath(inputs.parameters.json, '$.some.path') ``` You can also use [Sprig functions](http://masterminds.github.io/sprig/): Trim a string: ```text sprig.trim(inputs.parameters['my-string-param']) ``` !!! Warning "Sprig error handling" Sprig functions often do not raise errors. For example, if `int` is used on an invalid value, it returns `0`. Please review the Sprig documentation to understand which functions raise errors and which do not. ## Reference ### All Templates | Variable | Description| |----------|------------| | `inputs.parameters.`| Input parameter to a template | | `inputs.parameters`| All input parameters to a template as a JSON string | | `inputs.artifacts.` | Input artifact to a template | | `node.name` | Full name of the node | ### Steps Templates | Variable | Description| |----------|------------| | `steps.name` | Name of the step | | `steps..id` | unique id of container step | | `steps..ip` | IP address of a previous daemon container step | | `steps..status` | Phase status of any previous step | | `steps..exitCode` | Exit code of any previous script or container step | | `steps..startedAt` | Time-stamp when the step started | | `steps..finishedAt` | Time-stamp when the step finished | | `steps..hostNodeName` | Host node where step ran | | `steps..outputs.result` | Output result of any previous container, script, or HTTP step | | `steps..outputs.parameters` | When the previous step uses `withItems` or `withParams`, this contains a JSON array of the output parameter maps of each invocation | | `steps..outputs.parameters.` | Output parameter of any previous step. When the previous step uses `withItems` or `withParams`, this contains a JSON array of the output parameter values of each invocation | | `steps..outputs.artifacts.` | Output artifact of any previous step | **Note:** If a step was Skipped (its `when` condition was false), references to its outputs resolve according to the rules in [Outputs of Skipped and Omitted Nodes](#outputs-of-skipped-and-omitted-nodes). ### DAG Templates | Variable | Description| |----------|------------| | `tasks.name` | Name of the task | | `tasks..id` | unique id of container task | | `tasks..ip` | IP address of a previous daemon container task | | `tasks..status` | Phase status of any previous task | | `tasks..exitCode` | Exit code of any previous script or container task | | `tasks..startedAt` | Time-stamp when the task started | | `tasks..finishedAt` | Time-stamp when the task finished | | `tasks..hostNodeName` | Host node where task ran | | `tasks..outputs.result` | Output result of any previous container, script, or HTTP task | | `tasks..outputs.parameters` | When the previous task uses `withItems` or `withParams`, this contains a JSON array of the output parameter maps of each invocation | | `tasks..outputs.parameters.` | Output parameter of any previous task. When the previous task uses `withItems` or `withParams`, this contains a JSON array of the output parameter values of each invocation | | `tasks..outputs.artifacts.` | Output artifact of any previous task | **Note:** If a task was Skipped (its `when` condition was false) or Omitted (its `depends` condition was not satisfied), references to its outputs resolve according to the rules in [Outputs of Skipped and Omitted Nodes](#outputs-of-skipped-and-omitted-nodes). ### Outputs of Skipped and Omitted Nodes > v4.0.7 and after A step or task that was Skipped (its `when` condition was false) or Omitted (its `depends` condition was not satisfied) never ran, so it produced no outputs. References to its declared output parameters and `outputs.result` resolve as follows: 1. If the producing template declares a `valueFrom.default` for the output parameter, every reference resolves to that default. 1. Otherwise the output is *absent*, which is not the same as an empty string. An absent output must be handled by one of the following, or the referencing node fails with a terminal error: * If an argument consists solely of such a reference and the consuming template's input parameter declares a `default`, the argument is omitted so that input default applies. * An expression tag sees the value as `nil`. Use the `??` operator to choose a fallback, e.g. `{{= steps.producer.outputs.parameters.msg ?? 'fallback'}}`. * In template outputs, a `valueFrom.default` declared on the aggregating output parameter applies when its `valueFrom.parameter` reference is absent or its `valueFrom.expression` fails. 1. An unhandled reference to an absent output fails the node with a terminal error (it is not retried): a simple tag such as `{{steps.producer.outputs.parameters.msg}}` with no consumer input default, a bare `{{= steps.producer.outputs.parameters.msg}}`, or an operation on the `nil` such as `+ '-suffix'`. These rules apply wherever the reference appears: step and task arguments, `when` clauses, [`LifecycleHook`](lifecyclehook.md) and exit handler arguments and expressions, the enclosing template's `outputs.parameters`, `spec.volumes`, and artifact `subPath` fields. The exception is a step or task whose own `when` evaluates to false: it never runs, so absent references in its body are left unresolved instead of failing the workflow. A legitimately empty output is **not** absent: if the producer ran and wrote an empty string, `??` does not fire and the empty string is substituted. For the same reason, an expression comparison such as `{{= steps.producer.outputs.parameters.msg == ''}}` is false when the producer was skipped, because `nil` is not equal to `''`. Declare `valueFrom.default: ""` on the producer's output if you want a skipped output to behave exactly like an empty one. See the [skipped output defaults examples](https://github.com/argoproj/argo-workflows/tree/main/examples/skipped-output-defaults) for runnable workflows demonstrating each rule. ### HTTP Templates Only available for `successCondition` | Variable | Description| |----------|------------| | `request.method` | Request method (`string`) | | `request.url` | Request URL (`string`) | | `request.body` | Request body (`string`) | | `request.headers` | Request headers (`map[string][]string`) | | `response.statusCode` | Response status code (`int`) | | `response.body` | Response body (`string`) | | `response.headers` | Response headers (`map[string][]string`) | ### CronWorkflows | Variable | Description| |----------|------------| | `cronworkflow.name` | Name of the CronWorkflow (`string`) | | `cronworkflow.namespace` | Namespace of the CronWorkflow (`string`) | | `cronworkflow.labels.` | CronWorkflow labels (`string`) | | `cronworkflow.labels.json` | CronWorkflow labels as a JSON string (`string`) | | `cronworkflow.annotations.` | CronWorkflow annotations (`string`) | | `cronworkflow.annotations.json` | CronWorkflow annotations as a JSON string (`string`) | | `cronworkflow.lastScheduledTime` | The time since this workflow was last scheduled, value is nil on first run (`*time.Time`) | | `cronworkflow.failed` | Counts how many times child workflows failed | | `cronworkflow.succeeded` | Counts how many times child workflows succeeded | ### `RetryStrategy` When using the `expression` field within `retryStrategy`, special variables are available. | Variable | Description| |----------|------------| | `lastRetry.exitCode` | Exit code of the last retry | | `lastRetry.status` | Status of the last retry | | `lastRetry.duration` | Duration in seconds of the last retry | | `lastRetry.message` | Message output from the last retry. For a failed DAG template, this is `child '' failed`, where the node ID is the ID of the first failed task in the `tasks` list, whatever order the tasks failed in. | Note: These variables evaluate to a string type. If using advanced expressions, either cast them to int values (`expression: "{{=asInt(lastRetry.exitCode) >= 2}}"`) or compare them to string values (`expression: "{{=lastRetry.exitCode != '2'}}"`). ### Container/Script Templates | Variable | Description| |----------|------------| | `pod.name` | Pod name of the container/script | | `node.taskName` | v4.2 and after: Name of this attempt of the container/script, the same as `pod.name`; the default artifact repository key format uses it | | `retries` | The retry number of the container/script if `retryStrategy` is specified | | `lastRetry` | The last retry is a structure that contains the fields `exitCode`, `status`, `duration` and `message` of the last retry | | `inputs.artifacts..path` | Local path of the input artifact | | `outputs.artifacts..path` | Local path of the output artifact | | `outputs.parameters..path` | Local path of the output parameter | ### Loops (`withItems` / `withParam`) | Variable | Description| |----------|------------| | `item` | Value of the item in a list | | `item.` | Field value of the item in a list of maps | ### Metrics When emitting custom metrics in a `template`, special variables are available that allow self-reference to the current step. | Variable | Description | |----------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | `status` | Phase status of the metric-emitting template | | `duration` | Duration of the metric-emitting template in seconds (only applicable in `Template`-level metrics, for `Workflow`-level use `workflow.duration`) | | `exitCode` | Exit code of the metric-emitting template | | `inputs.parameters.` | Input parameter of the metric-emitting template | | `outputs.parameters.` | Output parameter of the metric-emitting template | | `outputs.result` | Output result of the metric-emitting template | | `resourcesDuration.{cpu,memory}` | Resources duration **in seconds**. Must be one of `resourcesDuration.cpu` or `resourcesDuration.memory`, if available. For more info, see the [Resource Duration](resource-duration.md) doc. | | `retries` | Retried count by retry strategy | | `pod.name` | Pod name of the metric-emitting template, for a template that runs a pod. With a `retryStrategy`, each attempt is counted with its own pod name. | ### Real-Time Metrics Some variables can be emitted in real-time (as opposed to just when the step/task completes). To emit these variables in real time, set `realtime: true` under `gauge` (note: only Gauge metrics allow for real time variable emission). Metrics currently available for real time emission: For `Workflow`-level metrics: * `workflow.duration` For `Template`-level metrics: * `duration` ### Global | Variable | Description| |----------|------------| | `workflow.name` | Workflow name | | `workflow.namespace` | Workflow namespace | | `workflow.mainEntrypoint` | Workflow's initial entrypoint | | `workflow.serviceAccountName` | Workflow service account name | | `workflow.uid` | Workflow UID. Useful for setting ownership reference to a resource, or a unique artifact location | | `workflow.parameters.` | Input parameter to the workflow | | `workflow.parameters` | All input parameters to the workflow as a JSON string (this is deprecated in favor of `workflow.parameters.json` as this doesn't work with expression tags and that does) | | `workflow.parameters.json` | All input parameters to the workflow as a JSON string | | `workflow.outputs.parameters.` | Global parameter in the workflow | | `workflow.outputs.artifacts.` | Global artifact in the workflow | | `workflow.annotations.` | Workflow annotations | | `workflow.annotations.json` | all Workflow annotations as a JSON string | | `workflow.labels.` | Workflow labels | | `workflow.labels.json` | all Workflow labels as a JSON string | | `workflow.creationTimestamp` | Workflow creation time-stamp formatted in RFC 3339 (e.g. `2018-08-23T05:42:49Z`) | | `workflow.creationTimestamp.` | Creation time-stamp formatted with a [`strftime`](http://strftime.org) format character. | | `workflow.creationTimestamp.RFC3339` | Creation time-stamp formatted with in RFC 3339. | | `workflow.priority` | Workflow priority | | `workflow.duration` | Workflow duration estimate in seconds, may differ from actual duration by a couple of seconds | | `workflow.scheduledTime` | Scheduled runtime formatted in RFC 3339 (only available for `CronWorkflow`) | An output with a `globalName` sets `workflow.outputs.parameters.` or `workflow.outputs.artifacts.`. The controller exports a `globalName` output when the node that produces it finishes. When more than one node sets the same global output, the value is from the node that finished last. When two of those nodes finish in the same second, which one wins is not defined. These nodes also export their `globalName` outputs when they finish: memoized steps and tasks served from the cache, HTTP and plugin steps and tasks, and suspend steps and tasks resumed with `argo resume`. The entrypoint template exports its own `globalName` outputs to `workflow.status.outputs`, for both DAG and Steps templates. When a task in an entrypoint DAG sets a global output with the same name, the DAG's own output overwrites it when the DAG finishes. The outputs of a DAG or Steps template can refer to `workflow.outputs`, for example `valueFrom.expression: workflow.outputs.parameters.g` or `from: "{{workflow.outputs.artifacts.a}}"`. ### Exit Handler | Variable | Description| |----------|------------| | `workflow.status` | Workflow status. One of: `Succeeded`, `Failed`, `Error` | | `workflow.failures` | A list of JSON objects containing information about nodes that failed or errored during execution. Available fields: `displayName`, `message`, `templateName`, `phase`, `podName`, and `finishedAt`. The list does not include `TaskGroup` nodes. It includes the failed items of an expanded step or task. | ### Knowing where you are The idea with creating a `WorkflowTemplate` is that they are reusable bits of code you will use in many actual Workflows. Sometimes it is useful to know which workflow you are part of. `workflow.mainEntrypoint` is one way you can do this. If each of your actual workflows has a differing entrypoint, you can identify the workflow you're part of. Given this use in a `WorkflowTemplate`: ```yaml apiVersion: argoproj.io/v1alpha1 kind: WorkflowTemplate metadata: name: say-main-entrypoint spec: entrypoint: echo templates: - name: echo container: image: alpine command: [echo] args: ["{{workflow.mainEntrypoint}}"] ``` I can distinguish my caller: ```yaml apiVersion: argoproj.io/v1alpha1 kind: Workflow metadata: generateName: foo- spec: entrypoint: foo templates: - name: foo steps: - - name: step templateRef: name: say-main-entrypoint template: echo ``` results in a log of `foo` ```yaml apiVersion: argoproj.io/v1alpha1 kind: Workflow metadata: generateName: bar- spec: entrypoint: bar templates: - name: bar steps: - - name: step templateRef: name: say-main-entrypoint template: echo ``` results in a log of `bar` This shouldn't be that helpful in logging, you should be able to identify workflows through other labels in your cluster's log tool, but can be helpful when generating metrics for the workflow for example.