条件
为任何步骤或动作附加条件,以决定它在运行时是否应该运行。条件是一个 mustache 表达式,可以引用先前步骤的输出、工作流变量或执行上下文中的任何其他数据。
使用条件,您可以通过断言值、阈值或特定状态来引入决策机制到工作流中。
简单的 if 条件
yaml
actions:
- name: notify-slack
if: "{{ alert.cpu_load }} == '70'"
provider:
type: slack
config: "{{ providers.slack }}"
with:
message: "The CPU load exceeded the threshold!"注意
变量值在求值时会被引号包裹。例如,如果 alert.cpu_load 是 70,它将解析为 '70'(带单引号的数字)。
在条件中使用其他步骤的结果
yaml
workflow:
id: query-and-alert
description: "Query a database and notify only if a threshold is met"
steps:
- name: get-disk-usage
provider:
type: mysql
config: "{{ providers.mysql-prod }}"
with:
query: "SELECT disk_usage FROM metrics WHERE server = 'db1'"
single_row: true
actions:
- name: notify-slack
if: "{{ steps.get-disk-usage.results.disk_usage }} > 90"
provider:
type: slack
config: "{{ providers.slack }}"
with:
message: "Disk usage is critical: {{ steps.get-disk-usage.results.disk_usage }}%"复杂逻辑
yaml
actions:
- name: create-incident
if: "{{ steps.get-alert.results.severity }} == 'critical' and {{ steps.get-alert.results.source }} == 'datadog'"
provider:
type: servicenow
config: "{{ providers.servicenow }}"
with:
table_name: INCIDENT
payload:
short_description: "Critical Datadog alert received"带 foreach 的条件
yaml
actions:
- name: process-pods
foreach: "{{ steps.get-pods.results }}"
if: "{{ foreach.value.status.phase }} == 'Failed'"
provider:
type: slack
with:
message: "Pod {{ foreach.value.metadata.name }} has failed!"带常量的条件
yaml
consts:
max_load: 70
actions:
- name: process-pods
if: "{{ alert.cpu_load }} > {{ consts.max_load }}"
provider:
type: slack
with:
message: "Pod {{ foreach.value.metadata.name }} has failed!"显式条件块(已弃用)
注意
显式条件块已弃用并将停止使用。请改用 if 语法。
assert(已弃用)
检查特定断言是否为真。
yaml
condition:
- name: assert-condition
type: assert
assert: "{{ steps.get-data.results.value }} == 'expected'"threshold(已弃用)
使用运算符(如 > (gt) 和 < (lt))将值与阈值进行比较,默认为 > (gt)。
yaml
condition:
- name: threshold-condition
type: threshold
value: "{{ steps.get-data.results.value }}"
compare_to: 100
compare_type: gt