Trigger policy
Create complex workflows using trigger policies

Purpose

Frequently, your infrastructure consists of a number of projects (stacks in Spacelift parlance) that are connected in some way - either depend logically on one another, or must be deployed in a particular order for some other reason - for example, a rolling deploy in multiple regions.
Enter trigger policies. Trigger policies are evaluated at the end of each stack-blocking run (which includes tracked runs and tasks) and allow you to decide if some tracked Runs should be triggered. This is a very powerful feature, effectively turning Spacelift into a Turing machine.
Note that in order to support various use cases this policy type is currently evaluated every time a blocking Run reaches a terminal state, which includes states like Canceled, Discarded, Stopped or Failed in addition to the more obvious Finished. This allows for very interesting and complex workflows (eg. automated retry logic) but please be aware of that when writing your own policies.
All runs triggered - directly or indirectly - by trigger policies as a result of the same initial run are grouped into a so-called workflow. In the trigger policy you can access all other runs in the same workflow as the currently finished run, regardless of their Stack. This lets you coordinate executions of multiple Stacks and build workflows which require multiple runs to finish in order to commence to the next stage (and trigger another Stack).

Data input

This is the schema of the data input that each policy request will receive:
1
{
2
"run": {
3
"changes": [
4
{
5
"action": "string enum - added | changed | deleted",
6
"entity": {
7
"address": "string - full address of the entity",
8
"name": "string - name of the entity",
9
"type": "string - full resource type or \"output\" for outputs",
10
"entity_vendor": "string - terraform or pulumi",
11
"entity_type": "string - resource, output or module for Terraform; resource, output or stack for Pulumi",
12
"data": "object - detailed information about the entity, shape depends on the vendor and type"
13
},
14
"phase": "string enum - plan | apply"
15
}
16
],
17
"created_at": "number - creation Unix timestamp in nanoseconds",
18
"id": "Unique ID of the Run",
19
"runtime_config": {
20
"before_init": ["string - command to run before run initialization"],
21
"project_root": "string - root of the Terraform project",
22
"runner_image": "string - Docker image used to execute the run",
23
"terraform_version": "string - Terraform version used to for the run"
24
},
25
"state": "one of the terminal states of the Run",
26
"triggered_by": "string or null - user or trigger policy who triggered the run, if applicable",
27
"type": "string - TRACKED or TASK",
28
"updated_at": "number - last update Unix timestamp in nanoseconds",
29
"user_provided_metadata": ["string - blobs of metadata provided using spacectl or the API when interacting with this run"]
30
},
31
"stack": {
32
"administrative": "boolean - is the stack administrative",
33
"autodeploy": "boolean - is the stack currently set to autodeploy",
34
"branch": "string - tracked branch of the stack",
35
"id": "string - unique stack identifier",
36
"labels": ["string - list of arbitrary, user-defined selectors"],
37
"locked_by": "optional string - if the stack is locked, this is the name of the user who did it",
38
"name": "string - name of the stack",
39
"namespace": "string - repository namespace, only relevant to GitLab repositories",
40
"project_root": "optional string - project root as set on the Stack, if any",
41
"repository": "string - name of the source GitHub repository",
42
"state": "string - current state of the stack",
43
"terraform_version": "string or null - last Terraform version used to apply changes"
44
},
45
"stacks": [{
46
"administrative": "boolean - is the stack administrative",
47
"autodeploy": "boolean - is the stack currently set to autodeploy",
48
"branch": "string - tracked branch of the stack",
49
"id": "string - unique stack identifier",
50
"labels": ["string - list of arbitrary, user-defined selectors"],
51
"locked_by": "optional string - if the stack is locked, this is the name of the user who did it",
52
"name": "string - name of the stack",
53
"namespace": "string - repository namespace, only relevant to GitLab repositories",
54
"project_root": "optional string - project root as set on the Stack, if any",
55
"repository": "string - name of the source GitHub repository",
56
"state": "string - current state of the stack",
57
"terraform_version": "string or null - last Terraform version used to apply changes"
58
}],
59
"workflow": [{
60
"id": "string - Unique ID of the Run",
61
"stack_id": "string - unique stack identifier",
62
"state": "state - one of the states of the Run",
63
"type": "string - TRACKED or TASK"
64
}]
65
}
Copied!
Note the presence of two similar keys: stack and stacks. The former is the Stack that the newly finished Run belongs to. The other is a list of all Stacks in the account. The schema for both is the same.

Use cases

Since trigger policies turn Spacelift into a Turing machine, you could probably use them to implement Conway's Game of Life, but there are a few more obvious use cases. Let's have a look at two of them - interdependent Stacks and automated retries.

Interdependent stacks

The purpose here is to create a complex workflow that spans multiple Stacks. We will want to trigger a predefined list of Stacks when a Run finishes successfully. Here's our first take:
1
package spacelift
2
3
trigger["stack-one"] { finished }
4
trigger["stack-two"] { finished }
5
trigger["stack-three"] { finished }
6
7
finished {
8
input.run.state == "FINISHED"
9
input.run.type == "TRACKED"
10
}
11
Copied!
Here's a minimal example of this rule in the Rego playground. But it's far from ideal. We can't be guaranteed that stacks with these IDs still exist in this account. Spacelift will handle that just fine, but you'll likely find if confusing. Also, for any new Stack that appears you will need to explicitly add it to the list. That's annoying.
We can do better, and to do that, we'll use Stack labels. Labels are completely arbitrary strings that you can attach to individual Stacks, and we can use them to do something magical - have "client" Stacks "subscribe" to "parent" ones.
So how's that:
1
package spacelift
2
3
trigger[stack.id] {
4
stack := input.stacks[_]
5
input.run.state == "FINISHED"
6
input.run.type == "TRACKED"
7
stack.labels[_] == concat("", ["depends-on:", input.stack.id])
8
}
Copied!
Here's a minimal example of this rule in the Rego playground. The benefit of this policy is that you can attach it to all your stacks, and it will just work for your entire organization.
Can we do better? Sure, we can even have stacks use labels to decide which types of runs or state changes they care about. Here's a mind-bending example:
1
package spacelift
2
3
trigger[stack.id] {
4
stack := input.stacks[_]
5
input.run.type == "TRACKED"
6
stack.labels[_] == concat("", [
7
"depends-on:", input.stack.id,
8
"|state:", input.run.state],
9
)
10
}
Copied!
Another Rego example to play with. Now, how cool is that?

Automated retries

Here's another use case - sometimes Terraform or Pulumi deployments fail for a reason that has nothing to do with the code - think eventual consistency between various cloud subsystems, transient API errors etc. It would be great if you could restart the failed run. Oh, and let's make sure new runs are not created in a crazy loop - since policy-triggered runs trigger another policy evaluation:
1
package spacelift
2
3
trigger[stack.id] {
4
stack := input.stack
5
input.run.state == "FAILED"
6
input.run.type == "TRACKED"
7
is_null(input.run.triggered_by)
8
}
Copied!
Note that this will also prevent user-triggered runs from being retried. Which is usually what you want in the first place, because a triggering human is probably already babysitting the Stack anyway.

Diamond Problem

The diamond problem happens when you're stacks and their dependencies form a shape like in the following diagram:
1
┌────┐
2
┌─►│ 2a ├─┐
3
│ └────┘ │
4
┌───┐ │ │ ┌───┐
5
│ 1 ├──┤ ├──►│ 3 │
6
└───┘ │ │ └───┘
7
│ ┌────┐ │
8
└─►│ 2b ├─┘
9
└────┘
Copied!
Which means that Stack 1 trigger both Stack 2a and 2b, and we only want to trigger Stack 3 when both predecessors finish. This can be elegantly solved using workflows.
First we'll have to create a trigger policy for Stack 1:
1
package spacelift
2
3
trigger["stack-2a"] {
4
tracked_and_finished
5
}
6
7
trigger["stack-2b"] {
8
tracked_and_finished
9
}
10
11
tracked_and_finished {
12
input.run.state == "FINISHED"
13
input.run.type == "TRACKED"
14
}
Copied!
This will trigger both Stack 2a and 2b whenever a run finishes on Stack 1.
Now onto a trigger policy for Stack 2a and 2b:
1
package spacelift
2
3
trigger["stack-3"] {
4
run_a := input.workflow[_]
5
run_b := input.workflow[_]
6
run_a.stack_id == "stack-2a"
7
run_b.stack_id == "stack-2b"
8
run_a.state == "FINISHED"
9
run_b.state == "FINISHED"
10
}
Copied!
Here we trigger Stack 3, whenever the runs in Stack 2a and 2b are both finished.
You can also easily extend this to work with a label-based approach, so that you could define Stack 3's dependencies by attaching a depends-on:stack-2a,stack-2blabel to it:
1
package spacelift
2
3
# Helper with stack_id's of workflow runs which have already finished.
4
already_finished[run.stack_id] {
5
run := input.workflow[_]
6
run.state == "FINISHED"
7
}
8
9
trigger[stack.id] {
10
input.run.state == "FINISHED"
11
input.run.type == "TRACKED"
12
13
# For each Stack which has a depends-on label,
14
# get a list of its dependencies.
15
stack := input.stacks[_]
16
label := stack.labels[_]
17
startswith(label, "depends-on:")
18
dependencies := split(trim_prefix(label, "depends-on:"), ",")
19
20
# The current Stack is one of the dependencies.
21
input.stack.id == dependencies[_]
22
23
finished_dependencies := [dependency |
24
dependency := dependencies[_]
25
already_finished[dependency]]
26
27
# Check if all dependencies have finished.
28
count(finished_dependencies) == count(dependencies)
29
}
Copied!
Last modified 1mo ago