Actions reference
This guide covers the concept of actions within MintPress, how to develop standalone and resource specific actions, how they integrate with the API server and options for utilising additional packages that are not in the standard OpsChain runner container.
After reading this guide you should understand:
- what an action is
- how to use the OpsChain logger
- how to define
- actions
- controllers
- resource types
- resources
- resource actions
- composite resource types and resources
Defining standalone actions
Actions are defined in the actions.rb file in the root directory of a Git repository. If required, actions can also be defined in separate files and required into the actions.rb.
When your Git repository is used by an asset template, the template's actions.rb is loaded from its named folder, and any property files placed in that same folder are loaded automatically - see template folder properties.
The action definition extends the Rake task definition, so standard Rake features can be used. In its simplest form, an action requires a name, and the instructions to perform when it is executed (between the do and end keywords). The term "block" will be used to describe these instructions throughout the MintPress documentation.
require 'opschain'
action :hello_world do
log.info "hello world!"
end
In the example above, the action's name is hello_world, and the action's block instructs MintPress to log "hello world" as an informational message using the MintPress Logger.
If you're running the script outside of MintPress, you must include a require 'opschain' line at the top of your actions.rb file and require it in your repository's Gemfile to allow you to use the features described in this reference guide. That is not needed if your code will run only as part of a MintPress change, given the opschain gem is already included by default.
Change step naming
By default, the step running an action will use the action name as its name (e.g. hello_world in the example above). If you would like to provide a more user-friendly name for your action, the step_name: option can be used when defining the action, for example:
action :hello_world, step_name: 'Hello world action' do
log.info "hello world!"
end
In the example above, the action's name is hello_world, but the step name that will be displayed in the MintPress GUI when the action is run will be "Hello world action".
Alternatively, you can declare the action directly with a human-readable name — including spaces and capitalisation. MintPress slugifies the name into a valid task name (used when referencing the action, for example on the command line) while retaining the original as the step name displayed in the GUI:
action 'Hello world action' do
log.info "hello world!"
end
In the example above, the action is registered under the slugified task name hello_world_action, and "Hello world action" is used as the step name. Prerequisite actions can reference the friendly name too. Existing actions defined with a plain name continue to work unchanged.
Two rules apply to step names:
- A step name must be unique within its namespace. Defining two actions with the same step name is an error, reported when the template's actions are derived and naming both actions and where each was defined. Names are compared ignoring case, so
Install binariesandInstall Binariescount as the same name. - A step name occupies exactly one segment of a step's path. A
/in the name is replaced with_when the path is built, so a step namedDeploy A/Bappears in the step tree atDeploy A_Brather than as a stepBnested under a stepA. The name itself is displayed unchanged. - An action name and a step name can each be at most 2,000 bytes. The limit is measured in bytes rather than characters, so a name written in non-ASCII text reaches it in fewer characters. A step whose action or step name is longer is rejected with
cannot exceed 2000 bytes, as it forms a database index key.
GUI display
When your Git repository (and included actions.rb) are used by an asset template the actions that have a description will be displayed in the GUI. To add a description to an action, include the description: option when defining the action, for example:
action :hello_world, description: 'An action that logs "hello world"' do
log.info "hello world!"
end
A description can span multiple sentences; the full description is retained and carried through onto the steps of a change, not just the first sentence.
Actions without a description can still be run via the GUI however the user will need to specify the action manually in the run change dialog.
Extending an action
By default, MintPress will raise an error when multiple actions with the same name are defined. You can disable this by setting the ignore_defined kwarg to true when defining the action, for example:
action :hello_world do
log.info "This is the first hello world action"
end
action :hello_world, ignore_defined: true do
log.info "This is the second hello world action"
end
In the example above, both actions will be defined and the second action will extend the first one. Running the hello_world action will output:
This is the first hello world action
This is the second hello world action
An extension cannot change the action's step name. Supplying a step_name: that differs from the one the action was defined with is an error, and ignore_defined does not waive the rule that a step name must be unique within its namespace.
Ignoring an action failure
Whenever an action raises an unhandled exception, the step (and subsequently the change) status will be set to error. You can ignore an action failure by setting the ignore_failure option to true when defining the action, for example:
action :hello_world, ignore_failure: true do
raise "This action will always fail"
end
In the example above, the action will fail, but the change will continue normally and the step finishes in the warning state rather than success. The GUI shows it as completed with warnings. The warning is passed up to the step's parents and the change, which also finish warning — see the change & step lifecycle.
A failure ignored by one of the action's prerequisites, or by an action it runs with run_action, also makes the step warning, because these run in the same step runner as the action.
Action timeouts
You can limit how long an action's block may run by setting the timeout option to a number of seconds when defining the action, for example:
action :deploy, timeout: 300 do
exec_command './bin/deploy.sh'
end
In the example above, if the block is still running after 300 seconds MintPress stops it, kills the processes it started and fails the step with:
Action "deploy" exceeded its timeout of 300 seconds
The step finishes in the error state. Combine timeout with ignore_failure: true to have the step finish warning instead, and the change continue. A rescue in the block, including rescue StandardError, does not catch the timeout. A rescue Exception does catch it and lets the block run on, but the step still fails with the timeout once the block finishes.
The timeout must be a positive whole number of seconds. 0, a negative number, a fraction or a string such as '5m' is reported as an error when actions.rb is loaded. So is a timeout on an action without a block, such as one that only runs child steps or prerequisites, as it has no logic of its own to limit. Because timeout is an option, actions.rb cannot declare prerequisites for an action named timeout (action timeout: [...]).
The GUI shows the timeout as a badge, e.g. Timeout 5m, on the step in the change step tree and in the asset's action tree.
Time spent in the action's prerequisites and child steps is not counted. Each prerequisite needs its own timeout, and each child step is a separate step limited by its own action's timeout:
action deploy: ['build'], steps: ['smoke_test'], timeout: 300 do
exec_command './bin/deploy.sh'
end
action :build, timeout: 600 do
exec_command './bin/build.sh'
end
action :smoke_test, timeout: 60 do
exec_command './bin/smoke_test.sh'
end
In the example above, build may run for up to 600 seconds before deploy's own block starts its 300 seconds, and smoke_test then runs as a child step limited to 60 seconds.
When the timeout is reached, MintPress kills every process the step runner started for the action that is still running, including one a prerequisite or an earlier action started and did not wait for. Some work is not stopped:
- a background process (e.g. started with
setsidornohup … &) whose parent process has already exited - a process running as another user, such as one started with
sudo, or a process it keeps starting while MintPress stops the others - a Ruby thread started in the block
The step still fails with the timeout in each case.
Reloading actions.rb for a step
MintPress reads a change's actions.rb once and reuses it for every step of the change, so code at the top level of the file is evaluated before the first step runs and keeps that value for the rest of the change — see runner.reuse_actions_rb. An action whose top level reads something a previous step produced, such as a property it set or a file it wrote, therefore sees the state as it was when the change started.
Setting the reload_actions option to true when defining an action makes that step read actions.rb again before it runs, so the top level of the file is evaluated with the current state, for example:
hosts = OpsChain.properties.dig('inventory', 'hosts') || []
action :discover_hosts do
# store the hosts that were discovered in the change's properties
end
action :configure_hosts, reload_actions: true do
log.info "Configuring #{hosts.size} hosts"
end
In the example above configure_hosts sees the hosts discover_hosts stored. Without reload_actions it would see the hosts as they were before the change started.
Only the step the option is set on reads the file again — every other step of the change continues to use the copy loaded at the start. The option is not inherited, so mark each action that needs it, including child steps of an action that is already marked.
Reloading is not free. The step evaluates the whole of actions.rb before it starts, which is noticeable for a repository with a large file or expensive top-level code, so set the option only on the actions that need it.
The option makes no difference where a step already reads actions.rb for itself — a change running each step in its own container, via pod_per_change_step, or an instance with runner.reuse_actions_rb set to false.
A controller action is marked with the desc declaration above the method in a base controller, through its available_actions entry — where the resource type declares the controller, or where a resource re-declares its available actions — or with the reload_actions DSL method in the resource definition. Where a resource re-declares its available actions, that list is what applies: an entry that omits reload_actions leaves the action unmarked, as it does for ignore_failure and step_name.
The actions MintPress generates for you — the step wrappers and MintModel actions — cannot be marked this way.
Sequencing actions
In addition to the action name, MintPress's DSL allows you to specify prerequisite actions (to run before the action's block) and child steps (to run after the action's block). In this way you can describe a sequence of actions to perform.
Referencing actions by name or step name
Wherever an action is referenced — in an action's steps: list, in its prerequisites, as the action passed to opschain-action, or as the action a change runs — it can be named by its action name or its step name. MintPress resolves the reference to the real action name: an exact match is tried first, then a case-insensitive match against every action's name and step name.
A reference that matches more than one action is rejected with an ambiguity error. Two actions cannot share a step name, but an action's own name can still collide with another action's step name — MintPress warns about such a pair when it loads your actions, and rejects the reference if you write it.
A child step that matches no action is treated as a MintModel action. A prerequisite cannot be satisfied by a MintModel action, so a prerequisite that matches nothing is reported as an error while your actions are loaded.
Every other place an action is named is matched the same way, so the capitalisation you use is never significant. This includes skip_steps patterns and starting_step, the rule that allows only one change with a given action name to run at a time for a project, environment or asset (see change execution options), event filter rules that match on an action or step name, and authorisation rules whose resource path targets an action.
Sibling steps whose names differ only by capitalisation are treated as colliding, and are given distinct step paths in the same way as exact duplicates. Child steps named stop, STOP and Stop under a provision step become provision/stop, provision/STOP-1 and provision/Stop-2 — each keeps the capitalisation it was defined with.
Prerequisite actions
Prerequisite actions will run in the same step runner as the requested action. These behave like standard Rake prerequisites.
action go_to_work: ['wake_up', 'get_dressed'] do
# this optional block will run after get_dressed
end
action :wake_up do
# this block will run before get_dressed
end
action :get_dressed do
# this block will run after wake_up
end
In the example above, all actions would run in the same step runner, in this order:
wake_upget_dressedgo_to_work
An action's timeout does not include the time its prerequisites take. Give each prerequisite its own timeout to limit it.
In the action name: [...] form, the name is a Ruby keyword argument, so it can't be one of the options action itself takes: description, steps, run_as, ignore_defined, generated, generated_group, input_arguments, requires_approval_from, ignore_failure, reload_actions, step_name or timeout. MintPress fails to load an action named like this and reports the keyword, as described in troubleshooting. To keep such a name, write it as a string, such as action 'timeout' => ['wake_up'], or give the action another name.
Combining actions on a single step runner
As noted in the prerequisite actions example above, an action with prerequisites (or child steps) need not include a block and can be specified as:
action holiday: ['wake_up', 'get_dressed']
Running the holiday action will execute the wake_up and get_dressed actions in a single step runner.
Grouping actions on a single step runner comes with some advantages and disadvantages:
Advantages
- Improved performance - as there is an overhead to building and launching each step runner, grouping actions can improve overall change performance
- De-isolation - passing data between actions running in their own step runners requires you to store the data in MintPress's properties (or in a data store accessible to both runners). Grouping actions on a single step runner means the actions have access to the same file system and memory. This removes the need to store sensitive (or single use) information in properties
Disadvantages
- Execution visibility - prerequisite steps are not displayed in MintPress's change step tree. This reduces the visibility of their start and stop times, making it harder to follow the change's progress. Similarly, when viewing the change logs, there is no separator in the logs between each prerequisite action's log messages nor with the grouping action's log messages (if any)
- De-isolation - While it can be an advantage (as described above), care must be taken when deciding to combine actions on a single step runner. The modifications to the file system or memory that one action makes may have unintended effects if subsequent actions have been designed with an expectation that they will run in a "clean" step runner
Running other actions within another action
MintPress actions can also be run from within an another action via MintPress's run_action method (OpsChain.run_action). This can be useful for running actions conditionally.
action :go_to_work do
OpsChain.run_action(:get_dressed) unless OpsChain.properties.dressed_already
end
action :get_dressed do
# this block is run from the go_to_work action
end
This will run the action in same step as the current step. See here for more details about the trade-offs involved.
See dynamic child steps for an alternative approach for conditionally running actions, but in separate steps (and hence will be shown separately in the GUI).
Child steps
An action definition can include a list of other actions to run as child steps. After the parent's block has completed, these child steps will be added to the queue of actions to run. When an OpsChain worker becomes available, it will build and launch a step runner to run the next action in the queue.
The steps: argument accepts:
- A single action name - e.g.
steps: 'the_next_step' - A list of actions - e.g.
steps: ['first_child', 'second_child'] - A Ruby method/proc that returns a single or list of actions - e.g.
steps: generate_step_list
Actions can be specified as strings or Ruby symbols.
action :do_something, steps: ['do_something_after', :do_something_else_after] do
# this will run before steps
end
action :do_something_after do
# runs after do_something and before do_something_else_after
end
action :do_something_else_after do
# runs after do_something_after
end
In the example above each action will run in its own step runner, in this order:
do_somethingdo_something_afterdo_something_else_after
Dynamic child steps
MintPress allows you to dynamically alter a parent's child steps from within the action's block.
- the
append_child_stepsandreplace_child_stepsmethods accept any value that can be supplied via thesteps:argument when defining an action (see the valid argument values under child steps)
A step added this way is shown in the change's step tree with the same detail as one declared up front — its step name, description, prerequisites and, for a wait step or an input step, the arguments it asks the user for.
Append child steps
The append_child_steps method allows you to append additional children into the queue of steps the OpsChain workers will process. E.g.
action :do_something, steps: 'do_something_after' do
if Time.now.strftime("%a") == 'Tue'
OpsChain.append_child_steps('do_something_on_tuesdays')
end
end
action :do_something_after do
# runs after do_something
end
action :do_something_on_tuesdays do
# runs after do_something_after - on Tuesdays
log.info "It's Tuesday!"
end
In the example above actions would run in this order:
do_somethingdo_something_afterdo_something_on_tuesdays(if the change is run on a Tuesday)
Replace child steps
If you wish to replace the list of child steps, it can be overwritten by assigning the new value(s) to OpsChain.child_steps. E.g.
action :replace_child_steps, steps: ['do_something_after', 'do_something_else'] do
OpsChain.child_steps = ['do_a_different_thing', 'do_another_thing']
end
In the example above actions would run in this order:
replace_child_stepsdo_a_different_thingdo_another_thing
Care must be taken when directly modifying the child_steps value, as this will override all standard MintPress step handling functionality for the current step runner and may have unintended consequences.
Accessing child steps
MintPress stores the list of actions to run in child steps as a Set. It is available from within your action blocks via OpsChain.child_steps. E.g.
action check_for_child_step: ['prereq_with_conditional_step'] do
if OpsChain.child_steps.include?('conditional_step')
log.info '"prereq_with_conditional_step" added "conditional_step" to the child steps'
end
end
In the example above, check_for_child_step will log an informational message if the prereq_with_conditional_step prerequisite has added the conditional_step action into the child steps of check_for_child_step
Modifying the child steps list via any method other than the append and replace methods described above is not supported.
Running MintModel actions as child steps
An actions.rb can also invoke steps defined in the asset's MintModel by adding them as child steps. The MintModel action path is the action name for top-level steps (e.g. Binaries), or for a nested step, the path includes each parent action name separated by / (e.g. Binaries/Install Software Binaries/Install Binaries/Install jdk Binaries). The easiest way to find this value is from the asset's actions tab in the GUI — copy it from the Run or schedule a change dialogue.
The example below shows how the Binaries step from a MintModel could be run as part of an actions.rb change.
action :infra_provision do
...
end
action full_provision: ['infra_provision', 'Binaries']
The following example uses a nested MintModel step path instead:
action :infra_provision do
...
end
action provision_jdk: ['infra_provision', 'Binaries/Install Software Binaries/Install Binaries/Install jdk Binaries']
When a step name contains /, MintPress resolves it by full path rather than by name. This ensures a nested MintModel action is correctly targeted even when a wrapper step (such as one created by OpsChain.step or OpsChain.ignore_failure_step) has the same name. A / written in a step name rather than a path is not a separator — it occupies a single segment, with the / replaced by _.
Name collisions between actions.rb and MintModel actions
An asset's available actions combine the actions defined in its actions.rb with the actions from its MintModel. If an actions.rb action has the same name as a MintModel action at the same position in the tree, the actions.rb action takes precedence — it is the action listed for the asset (or the child step, if nested), and the action that runs when a change reaches that name. The MintModel action of the same name is not listed or run separately.
This precedence applies at any depth, not just to top-level actions: a nested actions.rb action (one reached via another action's child steps) takes precedence over a same-named MintModel action just as a top-level one does. It also holds when the colliding action is a change's root step, including when starting a change partway through at a nested override.
Collisions are matched case-insensitively, the same as referencing an action: Binaries and binaries collide with each other just as an exact match would, and the actions.rb action still wins.
This precedence only applies to a real, locally-defined actions.rb action. Directly running a MintModel action as a child step — a steps: entry that names a MintModel path rather than another action defined in actions.rb — is not a name collision, so it is unaffected: the MintModel step still runs, exactly as documented above.
Reading an asset's MintModel actions
mintmodel_actions returns the actions the asset's MintModel contributes, so an actions.rb can build its step tree from what the MintModel actually contains rather than naming a single MintModel path and leaving MintPress to graft the subtree in.
It returns an array of hashes, one per top-level MintModel action, in the same shape the asset's actions endpoint serves. The keys an actions.rb is likely to want are:
| Key | Description |
|---|---|
:action | The action name, as it appears in the asset's action list. |
:step_name | The name the step is given in a change, where the MintModel sets one. |
:description | The action's description, where the MintModel supplies one. |
:full_path | The action's path from the root of the MintModel, with each parent action name separated by /. This is the value to use when running a MintModel action as a child step. |
:children | The action's child actions, each with the same keys. |
:child_execution_strategy | sequential or parallel. |
:mintpress_ctl_cmdline | The MintPress command line the action runs, for an action that runs one. |
The example below defines an action that runs every top-level MintModel action in the order the MintModel lists them, and one that runs only those that drive MintPress:
action provision_all: mintmodel_actions.map { |mintmodel_action| mintmodel_action[:full_path] }
action provision_mintpress: mintmodel_actions.select { |mintmodel_action| mintmodel_action[:mintpress_ctl_cmdline] }
.map { |mintmodel_action| mintmodel_action[:full_path] }
Refer to a MintModel action by its :full_path rather than by its :action, so a nested action is targeted unambiguously. Naming your own action after a MintModel one takes precedence over it instead of running it — see name collisions between actions.rb and MintModel actions.
The keyword is available at the top level of your actions.rb, in a resource definition and in a controller. OpsChain.mintmodel_actions reaches it as well.
An asset with no MintModel gets an empty array, as does a project, an environment or an agent — so a shared actions.rb can call the keyword across a template's assets whether or not each one has a MintModel.
While a change runs, the catalog is the one pinned to the change when it was created, so every step of the change sees the set its step tree was built from.
An actions.rb that calls mintmodel_actions builds actions MintPress cannot reconstruct from the template's actions plus the current MintModel. Its generated actions are therefore not reused by another asset assigned the same template version at the same commit — those actions are derived again for each asset.
If the MintModel's actions cannot be determined while an asset's actions are being generated — its MintModel has not been concretised, or concretising it failed — the generation continues with an empty catalog and a warn:mintmodel:actions_unavailable event records why, so an actions.rb that saw nothing can be told apart from one that asked for nothing.
Child execution strategy
The action definition includes an optional run_as: parameter. By default, it is set to sequential, meaning the action's child steps will run sequentially across the OpsChain workers.
Only sequential and parallel (as strings or Ruby symbols) are valid values for the run_as: parameter.
Parallel child step execution
To run child steps in parallel, include the run_as: :parallel option in your action definition.
action :do_something, steps: ['do_something_after', 'do_something_else_after'], run_as: :parallel do
# this will run before steps
end
action :do_something_after do
# runs after do_something
end
action :do_something_else_after do
# runs at the same time as do_something_after (providing there is a free worker)
end
In the example above actions would run in this order:
do_somethingdo_something_afteranddo_something_else_after
- Parallel task execution is limited by the number of available OpsChain workers
- Care must be taken when modifying properties from within parallel steps. See the changing properties in parallel steps section of the OpsChain properties guide for more information
Mixing parallel and sequential child steps
An action's run_as: applies to all of its direct child steps, so a single action cannot by itself run some children in parallel and others sequentially. To mix strategies within one action, nest a group of steps using OpsChain.steps:
action :deploy, steps: [
'prepare',
OpsChain.steps(['deploy_app_1', 'deploy_app_2'], run_as: :parallel, step_name: 'Deploy apps'),
'verify',
] do
# this runs before the child steps
end
OpsChain.steps(steps, run_as:, step_name:) defines a group carrying its own execution strategy and returns its name for embedding in a steps: list. Because each group carries its own run_as:, independent of its parent and siblings, the example above runs prepare, then deploy_app_1 and deploy_app_2 in parallel, then verify — a sequential sequence with a parallel group nested inside it.
The group is shown in the step tree as a single step, labelled by step_name: when given, or Parallel children / Sequential children otherwise.
Modifying the child execution strategy
When using dynamic child steps, it may be necessary to override the child step execution strategy. This is performed by assigning the new value to MintPress's child_execution_strategy property.
The override value will be used as the execution strategy for all child steps of the action.
action :conditional_strategy, steps: ['do_something_after', 'do_something_else_after'], run_as: :parallel do
if some_condition
OpsChain.append_child_steps('do_the_final_thing')
OpsChain.child_execution_strategy = :sequential
end
end
In the example above, conditional_strategy has two possible outcomes:
- If "some_condition" is true, the
do_the_final_thingaction will be added to the child steps ofdo_something. As this action performs the "final thing", we want it to run afterdo_something_afteranddo_something_else_afterhave completed. To do this, the child execution strategy fordo_somethingis altered to run all of its children sequentially and the actions would run in this order:conditional_strategydo_something_afterdo_something_else_afterdo_another_thing
- If "some_condition" is false, the actions would run in this order:
conditional_strategydo_something_afteranddo_something_else_after
Accessing child execution strategy
The strategy that will be used to run the current action's child steps is available via OpsChain.child_execution_strategy.
action check_strategy: ['conditional_strategy'], steps: ['child1', 'child2'], run_as: :parallel do
if OpsChain.child_execution_strategy == :sequential
log.info "conditional_strategy changed the strategy to sequential"
end
end
In the example above, check_strategy executes conditional_strategy (from the modifying the child execution strategy example) as a prerequisite. Using OpsChain.child_execution_strategy, check_strategy can detect if conditional_strategy altered the child execution strategy from parallel to sequential.
Ignoring child step failure
By default, if any child step fails, the parent step will also be marked as failed. To ignore a child step failure, the ignore_failure option can be set to true when defining the child action, for example:
action :destroy_vms, steps: ['destroy_vm1', 'destroy_vm2', 'destroy_vm3'], run_as: :parallel, ignore_failure: true
In the example above, the destroy_vm children have been written such that they will error if they cannot find the vm to destroy. As this is a "non-error", as our goal was to remove the vm anyway, setting ignore_failure: true on the destroy_vms parent means it does not fail when a child step fails. Instead it finishes in the warning state, and the change carries on. If every child step succeeds, the parent finishes success, unless a child itself finished warning, in which case the parent finishes warning too.
With ignore_failure set to true, and run_as set to parallel, all child steps will be performed regardless of their success or failure. If run-as was set to sequential (or not specified), then the child steps will abort at the failing step and the destroy_vms parent will be marked as warning.
A group made with OpsChain.steps takes ignore_failure: true too, and finishes warning when one of its steps fails: OpsChain.steps(['destroy_vm1', 'destroy_vm2'], run_as: :parallel, ignore_failure: true, step_name: 'Destroy VMs').
An action or group that sets ignore_failure: true cannot also have handler steps (on_failure:, on_success:, always: or on_cancel:). To ignore the failure of a group that has handlers, wrap it in a sequential group that ignores failure, or set ignore_failure on the child steps whose failure should be ignored:
action :patch, steps: [
OpsChain.steps([OpsChain.steps(['apply_patch'], on_success: ['notify'], always: ['clean_up'])], ignore_failure: true, step_name: 'Patch, ignoring failure')
]
Branching
Some terms used in this section:
- A group is a list of steps with options, such as
run_as:: anOpsChain.stepscall, or an action withsteps:. - A group's main steps are the steps in its
steps:list. They run first. - An arm is a named list of steps that runs only in some cases.
- A handler is an arm that runs depending on how the main steps finished:
on_failure:,on_success:oralways:. - A selector is what picks the arm: the block of
OpsChain.branch_stepor the person answering a step withchoices:. - A step is skipped on request when you skip it with
skip_stepsor by starting the change partway, and not taken when it belongs to an arm that did not run. The step tree shows which.
A branch step is a group with more than one possible path. Each path is an arm. Every arm is part of the action's step tree from the moment the change is created, so the step tree shows each one before the change starts, and afterwards shows which arms ran and why the others did not.
For a change on a project or environment whose actions come from its Git remote, the step tree is discovered when the first step runs, so the tree shows Discovering steps… until then, and every arm after that.
| Method | What runs |
|---|---|
OpsChain.steps with on_failure:, on_success: or always: | Its steps, then a handler arm depending on how they finished. |
OpsChain.branch_step | One of several named arms:, picked by the value its block returns. |
OpsChain.wait_step or OpsChain.approval_step with choices: | One of several named choices, picked by a person when the change reaches the step. |
run_if: on OpsChain.step, OpsChain.steps or an action | The step or group, only when its condition holds. |
Handlers are options on a group of steps, like run_as:, so they go on OpsChain.steps or on an action with steps:. OpsChain.branch_step and steps with choices: are a different kind of step, so they have their own methods. Use OpsChain.branch_step and choices: for these; OpsChain.steps accepts the same options.
Arms are not the same as the branches of an input step that fans out. A fan out runs the same steps once for each value supplied; a branch step runs one arm instead of another.
This action patches a WebLogic domain with a rollback, checks its health, and either promotes it, asks for a decision, or rolls it back:
action :patch_weblogic, steps: [
'stop_servers',
OpsChain.steps(
['apply_patch', 'start_servers'],
on_failure: ['restore_backup', 'start_servers'],
always: ['notify'],
step_name: 'Patch with rollback',
),
'check_health',
OpsChain.branch_step(
arms: {
healthy: ['promote'],
degraded: [
OpsChain.approval_step(
choices: { promote: ['promote'], rollback: ['rollback'] },
requires_approval_from: [{ ldap_groups: %w[ops-leads] }],
step_name: 'Degraded: promote anyway?',
),
],
unhealthy: ['rollback'],
},
default: :unhealthy,
step_name: 'Health?',
) { OpsChain.properties.health_status },
]
Rolling back when a group fails
Give a group of steps handlers to run an extra arm depending on how its steps finished:
OpsChain.steps(
['apply_patch', 'start_servers'],
on_failure: ['restore_backup', 'start_servers'],
always: ['notify'],
step_name: 'Patch and restart',
)
The first argument is the group's steps: list, which runs first, following the group's run_as:. If one of those steps fails, the on_failure: arm runs once the failed step's siblings have finished, as described in behaviour when a child step fails. If they all succeed, the on_success: arm runs instead. The always: arm runs last in either case. Each arm runs its steps one at a time; to run an arm's steps in parallel, nest an OpsChain.steps group with run_as: :parallel inside it.
The same options work on a named action with steps:. The action's own block runs before its steps:, as it does for any action with child steps:
action :patch_and_restart,
steps: ['apply_patch', 'start_servers'],
on_failure: ['restore_backup', 'start_servers'],
always: ['notify'] do
log.info 'Taking a backup before patching'
end
How a group with handlers finishes
| What happens | Then | The group ends in |
|---|---|---|
All of steps: succeed | on_success:, then always: | success |
A step in steps: fails | on_failure:, then always: | error, or warning with recover: true |
A step in on_failure: fails | always: | error |
A step in on_success: or always: fails | Nothing else. on_failure: covers steps: only. The arms after it are set to aborted and show Not run: on_success failed | error |
A rejected approval or a cancelled step in steps: | As for a failed step, unless abort_on_reject: or abort_on_cancel: is set | error, or aborted when one of those is set: no handlers run, and they are set to aborted too |
| The change is cancelled | on_cancel: only, once the steps that were running have stopped. Cancelling again stops it | cancelled |
When groups with handlers are nested, they finish from the inside out: the inner group's on_failure: and always: arms run first, and then, unless the inner group recovered, the outer group's.
A step in a handler arm that fails, is rejected or is cancelled on its own fails that arm like any other step.
Cleaning up after a cancel
Give a group on_cancel: steps to tidy up when the change is cancelled while the group is running, for example to take a server back out of maintenance mode.
action :patch_with_cleanup,
steps: %i[enter_maintenance apply_patch leave_maintenance],
on_failure: %i[restore_backup leave_maintenance],
on_cancel: [:leave_maintenance]
When you cancel the change:
- The steps that are running are cancelled and the steps still to run are aborted, as for any cancel. The group's
on_failure:,on_success:andalways:steps do not run, and are set toaborted. - Their actions are stopped before the
on_cancel:steps start. - Each group that was running and has
on_cancel:steps then runs them, and so do the groups that contain it, from the inside out: an outer group'son_cancel:steps wait until the inner group's have finished. - A group that was already running its
on_failure:,on_success:oralways:steps still runs itson_cancel:steps; the handler steps that were running are cancelled first. A group that had already finished does not. - The change keeps running while the
on_cancel:steps run, then ends incancelled, even if anon_cancel:step fails. Until then the GUI shows it as Cancelling – cleaning up, and itscancel_requestedattribute in the API istrue. Its history records the cancel against the user who cancelled it. - Cancelling the change again stops the
on_cancel:steps too, and the change ends incancelledstraight away. - Cancelling a paused change does not wait for it to be resumed: the
on_cancel:steps run straight away. Resuming the change afterwards only clears the pause.
on_cancel: runs only when the whole change is cancelled. A step in the group that is cancelled on its own counts as a failure (see when an approval is rejected or a step is cancelled), so on_failure: runs, not on_cancel:. If you retry a cancelled change, the group runs from the start as for any other retry, and its on_cancel: steps are ready to run again.
In a workflow, a step that runs a change or a child workflow run is cancelled at once as well. The child is told to cancel, and its own on_cancel steps may still be running after the parent workflow run has finished as cancelled.
Carrying on after a successful rollback
By default a group whose steps failed ends in error even when its on_failure: steps succeed, so the change stops there and its remaining steps are set to aborted. A rolled-back patch is still a failed patch, and the change status says so.
To carry on with the rest of the change once on_failure: has put things right, add recover: true:
OpsChain.steps(
['apply_patch'],
on_failure: ['restore_backup'],
recover: true,
step_name: 'Patch if possible',
)
With recover: true the group ends in warning when its on_failure: steps succeed, and the change carries on. The step that failed keeps its error status, so the step tree still shows what went wrong, and the change records that it recovered. The warning passes up to the group's parents and the change, so a change that recovered finishes warning, not success. Notification subscriptions and event filters on success no longer match it. Subscribe to warning as well as success to be told about it. If an on_failure: step fails too, or none of the on_failure: steps runs, for example because they were all skipped, the group ends in error whatever recover: is set to. When none of them ran, the on_failure: arm shows Recovered nothing: none of its steps ran.
recover: and ignore_failureignore_failure lets the change carry on after a failure and runs nothing extra. A group cannot set both ignore_failure and a handler such as on_failure:; use on_failure: with recover: true when a failure needs steps of its own before the change can carry on.
When an approval is rejected or a step is cancelled
By default, a rejected approval among a group's steps, or one of its steps cancelled on its own, makes the group fail, so its on_failure: and always: steps run. Set abort_on_reject: true or abort_on_cancel: true on the group to stop it instead, with no handler steps. Cancelling the whole change is different: only on_cancel: steps run.
OpsChain.steps(
['apply_patch', OpsChain.approval_step(requires_approval_from: [{ ldap_groups: %w[ops-leads] }])],
on_failure: ['restore_backup'],
abort_on_reject: true,
step_name: 'Patch with sign-off',
)
- A rejected approval counts wherever it sits among the group's steps, including inside a plain stage.
abort_on_cancel:reacts only to a step of the group that was cancelled on its own, not to one nested deeper in a group with handlers of its own. A nested group with handlers decides its own outcome.- A rejection inside a handler arm is an ordinary failure of that arm, so
abort_on_reject:concerns only the group's own steps. - A group that aborts this way ends in
aborted, and itson_failure:,on_success:andalways:arms are set toabortedwithout running. Its parent fails, so the change ends inerror.
Choosing an arm in your action
OpsChain.branch_step takes named arms: instead of a list of steps, and runs the one whose name its block returns. Here an earlier check_health step records the asset's health in a property, and the branch step reads it:
action :release, steps: [
'check_health',
OpsChain.branch_step(
arms: {
healthy: ['promote'],
degraded: ['notify_on_call', 'promote'],
unhealthy: ['rollback'],
},
default: :unhealthy,
step_name: 'Release health?',
) { OpsChain.properties.health_status },
]
The block runs when the change reaches the branch step, and can do anything an action can: read properties, including ones set by earlier steps in the change, call other systems or run commands. Return the arm's name as a symbol or a string. The block cannot add or replace child steps; doing so fails the step.
A named action takes the same options, with its block as the selector:
action :health_branch,
arms: { healthy: ['promote'], unhealthy: ['rollback'] },
default: :unhealthy do
OpsChain.properties.health_status
end
If the block returns a name that is not one of the arms, the default: arm runs. A warning:steps:arm_defaulted event records it, and the arm shows the value the block returned, for example Default: block returned nil. Without a default:, the step fails with an error that names the value, for example Health? returned :maintenance, which is not one of its arms (healthy, degraded, unhealthy), and it has no default:, and the same happens when the property is not set.
The arms that do not run are set to skipped, and the step tree shows why, for example Not taken: took :degraded (block returned "degraded").
Each arm is a list of steps like any other steps: list, and can be empty.
Running a step only when a condition holds
Give a step a run_if: condition to run it only when the condition holds:
action :migrate, steps: [
OpsChain.step('migrate_sas_to_sql', run_if: -> { OpsChain.properties.needs_migration }),
'validate_sql',
]
The condition is checked when the change reaches the step. When it is false the step is set to skipped and shows Not taken: condition returned false. An action takes run_if: too: action :migrate_sas_to_sql, run_if: -> { … } do … end.
A group takes run_if: too, including a group with handlers. When the condition is false, the group's steps and all its arms are skipped:
OpsChain.steps(
['apply_patch'],
on_failure: ['rollback_patch'],
run_if: -> { OpsChain.properties.needs_patch },
step_name: 'Patch if needed',
)
run_if: cannot be used on a wait, approval or input step, as its condition would never be checked. Put the condition on a group that contains the step instead.
To run a step only once, have it set a property when it finishes and test that property in run_if:
action :migrate_sas_to_sql do
exec_command('migrate-sas-to-sql')
OpsChain.properties_for(:asset).needs_migration = false
end
A run_if: lambda is false when it returns nil, false, "" or "false", and true for anything else.
Letting a person choose
Give a wait step or an approval step choices: to pause the change and let a person pick which steps run next:
OpsChain.approval_step(
choices: {
promote: { label: 'Promote now', steps: ['promote'] },
rollback: ['rollback'],
},
requires_approval_from: [{ ldap_groups: %w[ops-leads] }],
step_name: 'Promote despite warnings?',
)
When the change reaches the step it pauses, and the step shows a button for each choice: the choice's label:, or its name with underscores replaced by spaces and a capital first letter, such as Rollback. Picking one continues the change and runs that choice's steps; the other choices are set to skipped. On an approval step, only the approvers can choose, and they can reject the step instead. On a wait step, anyone who can continue a wait step in the change can choose.
When an approval step needs several approvers, each approver's choice is checked when they approve, and an unknown choice is refused with the list of valid ones. The choice made by the approver whose approval completes the step decides which arm runs. Each approver's choice is kept in their audit event.
Each choice is recorded like any continued or approved step, with the choice made, and as an info:steps:arm_taken event.
Choosing without the step's buttons
To choose through the API, pass the choice's name as the choice attribute when continuing or approving the step:
curl --user 'opschain:password' -X POST "http://localhost:3000/api/steps/$STEP_ID/approve" \
-H 'Content-Type: application/vnd.api+json' \
-d '{"data": {"attributes": {"choice": "promote"}}}'
Use /continue in place of /approve for a wait step. For a workflow step, post to /api/workflow_steps/$STEP_ID/approve or /api/workflow_steps/$STEP_ID/continue with the same body.
From the CLI, pass --choice <name> to mintpress changes continue or mintpress changes approve, or for a workflow step to mintpress workflows runs steps continue or mintpress workflows runs steps approve. Choice names are matched exactly, including case. A request with an unknown choice, or with no choice, is rejected with a list of the step's choices, unless the step names a default: choice and the request gives no choice:
OpsChain.wait_step(
choices: { continue_rollout: ['deploy_prod'], stop_here: [] },
default: :continue_rollout,
step_name: 'Carry on to production?',
)
The default: choice is also what automatically continuing wait steps and Continue selected in manage activity use. A choices step without a default: is never continued automatically or in bulk; it waits for someone to choose.
Branches in the step tree
A branch step shows its arms as child steps, each titled by its key: on_failure:, on_success: or always:, or arms: :healthy and choices: :promote for a named arm. A group's own steps: are not an arm, and show directly under the group. Arms that were not taken stay in the tree, greyed out, with the reason they were not chosen. See branches for hiding them once a change has finished.
Each arm taken is recorded as an info:steps:arm_taken event, naming the step, the arm, why it was taken and, for a choice, who chose it. An arm skipped with skip_steps by a pattern that names it, such as **/on_failure, did not run, so it is not recorded. A pattern such as **/on_failure/** skips only the steps inside the arm, so the arm still runs, empty, and is recorded as taken. The change's header and its notifications summarise the arms taken, for example Warning · recovered 'Patch with rollback' · chose :promote. To find the changes that took an arm, filter the activities through the API with filter[arm_taken_eq]=on_failure (see API filtering). The filter matches the arm's key, such as on_failure or promote, not its label:. The activity lists in the GUI do not offer this filter.
Each arm's key is a segment in the full_path of the steps inside it. The group's own steps: add no segment:
patch_weblogic/Patch with rollback/apply_patch
patch_weblogic/Patch with rollback/on_failure/restore_backup
patch_weblogic/Health?/degraded/Degraded: promote anyway?/rollback/rollback
Adding handlers to a group therefore leaves the paths of the steps already in it unchanged, so existing skip_steps patterns, scheduled activities, authorisation rules and starting steps keep working. The steps in a new arm get the arm's key in their path. A step in a group's own steps: cannot be named on_failure, on_success, always or on_cancel when the group has handlers, because its path would clash with the arm. Such an action fails to load.
You can name an arm in skip_steps to skip everything in it, for example **/on_failure to run a change without its rollback steps. A pattern that names a group also covers every step inside it. In a change whose step tree is known when it is created, such as an asset or templated change, starting_step can name any step, including one inside an arm. A change on a project or environment whose actions come from its Git remote cannot start partway. Starting inside an arm makes that arm the one taken: its branch step's block is not run and nobody is asked to choose. Starting inside an on_failure: arm counts as a failure of its group: once the arm has run, the group ends in error and the change stops, or, with recover: true, the group ends in warning and the change carries on.
Skipping and starting partway never get a change past an approval step. When a step is skipped, or lies before the starting step, the steps inside it are skipped as requested, apart from approval steps:
- A
run_ifcondition or arm selection on the way to an approval is still evaluated, which runs that step's own action. Everything else in the skipped steps is skipped, including plain wait and input steps, whether named inskip_stepsdirectly or inside a skipped group. A wait step withchoiceswhose choice leads to an approval still asks for the choice. - An approval inside an arm or condition that is not taken is skipped as not taken.
- When a group runs only to reach an approval inside a skipped region, its
on_success:andalways:arms are skipped too, unless they hold an approval step, and are not listed as arms taken. - If the approval step is one of another step's own
choices:, the step offers only that choice, with Reject, so approving it runs the arm you started in. - A step above the starting step shows what happened to the steps inside it. When anything inside it ran, it shows its real outcome. Only a step none of whose steps ran shows as skipped, as requested.
A plain wait or input step named in skip_steps is skipped, and a pattern that names a group skips everything inside it. See skipping steps.
Retrying a change with branches
When a change with branch steps is retried, each branch step keeps the arm it took, unless reset_on_retry is true for it and a step that failed is inside the step or in one of its siblings. Then its block runs again, or the person is asked to choose again. If it picks a different arm, the new arm runs, and an arm that succeeded in the original change keeps its status and times, so the step tree still shows the steps that ran. A step that failed in an on_success: or always: arm does not count; only a failed step in the group's own steps: does. A sibling counts as failed if it ended in error, was cancelled or aborted, or never finished.
| Step | reset_on_retry default |
|---|---|
| Wait or approval step | false |
Wait or approval step with choices: | true |
OpsChain.branch_step or run_if: | false |
To have a branch step check again on retry, set it:
OpsChain.branch_step(
arms: { healthy: ['promote'], unhealthy: ['rollback'] },
reset_on_retry: true,
step_name: 'Recheck health?',
) { OpsChain.properties.health_status }
reset_on_retry: can only be set on wait and approval steps, and on steps that choose with arms:, choices: or run_if:. Elsewhere the action fails to load.
Retrying a failed step, a fan-out target or a stage in place keeps the answers already given to choices: approvals beside the failure. Only retrying the change again asks them again.
A group whose on_failure: arm ran has usually undone the steps that succeeded before the failure, so by default a retry runs the group again from its first step. This reruns steps that succeeded, unlike the rest of a retried change. To restart at the step that failed instead, set retry_from: :failed_step. A group with recover: true that recovered is treated as done: retrying the change for a later failure does not run the group or its on_failure: steps again. A step cannot be retried in place once handler arms above it, or anywhere below it, have started; retry the change instead.
Branching in a fan out
Inside an input step that fans out, every branching feature is decided separately for each target: run_if:, arms and default:, handlers with recover:, and wait and approval choices:. Two targets can take different arms of the same branch step. A condition can read the target with OpsChain.fan_out_target. A run_if: on a step also works when a change starts at an action nested inside the fan out. Starting a change partway at a step inside a target is rejected. The filter[arm_taken_eq] filter on activities matches a change if any target took the arm.
Passing a result between steps in a target
To have one step of a target decide whether a later step in the same target runs, write the result to a property under a key named after OpsChain.fan_out_target, and read it back in the later step's run_if:. Each target then writes a different property, so the branches can save their results while they run in parallel without clashing (see modifying different properties):
action :patch_servers, steps: [
:reset_health,
OpsChain.input_step(
step_name: 'Servers to patch',
input_arguments: [servers: { path: '/patching', type: :array, fan_out: true }],
steps: [
:check_health,
OpsChain.step('apply_patch', run_if: -> { OpsChain.properties.health[OpsChain.fan_out_target] == 'unhealthy' }),
],
),
]
action :reset_health do
OpsChain.properties_for(:project).health = {}
end
action :check_health do
result = exec_command('check-health', OpsChain.fan_out_target, abort_on_failure: false)
OpsChain.properties_for(:project).health[OpsChain.fan_out_target] = result.failed? ? 'unhealthy' : 'healthy'
end
Properties written this way outlive the change. A later change that skips check_health, or starts after it, reads the result an earlier change left behind. Clear the results at the start of the change, as reset_health does, before the fan out. Creating the health property there, before the branches start, also stops one branch's result replacing another's: each branch adds its own key to a property that already exists.
Branch rules
MintPress checks these rules when it loads your actions, and reports a broken one as an error on the action:
- A group has either
steps:(the first argument toOpsChain.steps) orarms:/choices:, never both. on_failure:,on_success:,always:andon_cancel:needsteps:, andrecover:andretry_from:needon_failure:.abort_on_reject:andabort_on_cancel:needsteps:.- A group cannot set both
ignore_failureand a handler (on_failure:,on_success:,always:oron_cancel:), or bothignore_failureandarms:. See ignoring child step failure for how to nest them instead. default:must name one of the group's arms or choices. Arm names cannot be blank or differ only in case.run_as:applies to the steps inside an arm. Arms never run in parallel with each other.choices:can only be used on a wait step or approval step, and not on a timed wait step.- Action names that start with
opschain_are reserved for actions MintPress generates. For now such an action still loads, with a warning in the change log; a later release will reject it. - Step names must be unique. Two actions, or two wait or approval steps, with the same
step_namefail to load with… cannot use the step name "Degraded: promote anyway?" as it is already the step name of … - step names must be unique. - A plain group, one with
steps:and none of the branching options, runs as a hidden action named after its step name, lower-cased with spaces and punctuation as underscores. That name must not match another action's name, whatever the case. A group with handlers, arms,run_if:, choices or any other branching option does not have this restriction. - Neither
skip_stepsnorstarting_stepcan get a change past an approval step, including one whosechoices:hold the arm a change starts in.
For example, this step name matches the action patch_with_rollback:
action :patch_with_rollback do
exec_command('echo', 'patch')
end
action :patch, steps: [OpsChain.steps(%w[apply_patch], step_name: 'Patch with rollback')]
Loading fails with:
The step name "Patch with rollback" of the group defined at "actions.rb:5" clashes with the action "patch_with_rollback" defined at "actions.rb:1" - the group runs as an action named after its step name, so rename the step.
Rename the step, or add a branching option such as on_failure: if the group needs one.
Wait steps
A MintPress wait step can be used to make a MintPress change pause at a step and wait for a user to continue the change.
This can be useful to allow for manual verification after some steps have completed, but before subsequent steps start. It also allows a user to undertake manual activities as part of a change - for example steps that can't be automated.
Anyone able to run the change can continue a wait step. When only particular people should be able to release the step, use an approval step instead.
An OpsChain wait step can only be added as part of a step's child steps, for example:
action :do_something, steps: [:do_something_before_waiting, OpsChain.wait_step, :do_something_else_after_waiting]
Another useful scenario for wait steps is when a scheduled change is used to create a change automatically, but a team member should then allow the change to proceed manually. To achieve this the MintPress wait step can be used as the first child step of an action:
action :do_something, steps: [:do_something_after] do
# this will run before steps
end
action :do_something_with_acknowledgement, steps: [OpsChain.wait_step, :do_something]
All the sibling steps of a wait step will run immediately when using run_as: :parallel - the change will not continue on subsequently until it is manually continued. See the troubleshooting guide for more info.
OpsChain wait steps use the naming convention opschain_wait_step_{{unique id}} - do not use this naming convention in your steps unless you intend to create an OpsChain wait step.
Step continuation auditing
Information about step continuation can be viewed by using the events endpoint. The continue action will be recorded with the type audit:steps:continue (these can be fetched via the API by requesting api/events?filter[type_eq]=audit:steps:continue). The username of the user who continued the step is available in the API response.
Please let us know if you would like to suggest improvements in this area.
Timed wait steps
OpsChain wait steps can be created with a specified duration, for example:
action :do_something, steps: [:do_something_before_waiting, OpsChain.wait_step(seconds: 90), :do_something_else_after_waiting]
In this example, the step will sleep for 90 seconds before automatically continuing to the next step. The seconds must be a number that is zero or more: any other value, such as a negative number, a string or Float::INFINITY, is reported as an error when your actions are loaded, before the change can start. The sleep is executed like any other action's code block and so may pause the change for longer than the 90 seconds while it waits for an image build (in pod_per_step mode) and a worker to become available.
Marking a change as errored
In order for a step (and subsequently the change) status to be set to error, the action must raise an Exception.
User-friendly naming
The default action name for a wait step (e.g. opschain_wait_step_1) does not provide the user with any information of why the change is waiting and whether it might be safe to continue it. To make it easier for users to understand the reason for the wait and whether they can continue the change, a custom name can be supplied when creating the wait step, for example:
action :do_something, steps: [:do_something_before_waiting, OpsChain.wait_step(step_name: 'Wait for network team'), :do_something_else_after_waiting]
This will add a step with the name Wait for network team into the change's step tree, making it easier for users to understand why the change is waiting and whether they can continue it.
The step_name argument can also be included when creating timed wait steps, for example: OpsChain.wait_step(seconds: 90, step_name: 'Wait for server restart')
Automatically continuing wait steps
A change can be configured to continue its wait steps automatically, rather than pausing for a user. This is useful when you want the structure of a wait step in a change (for example so it can optionally be paused), but do not always need manual intervention. With this option enabled, a wait step that does not require approval continues automatically.
An input step does not need the option. It continues automatically, whether or not the change was created with it, when:
- it does not require approval, and
- every required input argument has a value — a
default_value, or one supplied with the change. An optional argument that nobody answered does not hold the step up.
Wait steps that require approval, plain wait steps on a change without the option, and input steps still missing a required value pause and wait for a user. Each automatically continued step is recorded in the change's audit history, with the reason it was continued.
Where a step could not be continued automatically, the reason is written to the change log immediately above the line reporting that the step is waiting. A value that could not be applied to the change's properties, or a refused transition, is always logged. An input step held up by required arguments with no value is explained only when the change was created with the option, and the log then names every reason the step could not continue — including any supplied values that would not have been accepted.
The option can be set when running, scheduling, or repeating a change from the GUI — see the run change dialog.
Nesting child steps under a wait step
A wait step can be given its own child steps via the steps: option, rather than being used only as a sibling within an outer action's steps: list. Steps nested this way do not start until the wait step itself is continued or approved — if the wait step is rejected, times out, or errors, they never run.
action :destroy, steps: [
OpsChain.wait_step(step_name: 'Confirm destroy', steps: ['Shutdown']),
'infra_destroy'
]
In this example, the change pauses at the "Confirm destroy" wait step; Shutdown only starts once it is continued, and infra_destroy runs after Shutdown completes as before.
OpsChain.wait_step also accepts ignore_failure: alongside steps: — as with OpsChain.step, this means a nested child step's failure does not fail the wait step itself. The wait step finishes warning instead.
Waiting again when a change is retried
By default, a wait step that was continued before a change failed is not presented again when the change is retried. Set reset_on_retry: true to have the retried change wait at the step again, as it would in a workflow:
action :deploy, steps: [OpsChain.wait_step(step_name: 'Check the load balancer', reset_on_retry: true), 'switch_traffic']
The step waits again only when the step that failed is inside it or in one of its siblings. A wait step whose parent finished successfully is not reset. A wait or approval step with choices: defaults to reset_on_retry: true; every other wait and approval step in a change defaults to false.
Input steps
A MintPress input step can be used to pause a MintPress change and wait for a user to provide input before continuing the change. As part of defining the input step, you must include the arguments you expect from the user. e.g.
action :do_something,
steps: [
:do_something_before_input,
OpsChain.input_step(
step_name: 'Server details',
input_arguments: [
:comments,
server_name: { path: '/database/server', gui_name: 'Server name', description: 'Name of the server to restart' },
patch_number: { path: '/patches', gui_name: 'Patch number', description: 'Optional patch to apply before restart', required: false },
restart_after_hours: { path: '/restart_after_hours', gui_name: 'Restart after hours', required: true, type: :boolean, default_value: true }
]
),
:do_something_with_input
]
In the example above, the do_something action has an input step as a child step. When the change runs and reaches the input step, it will pause and display a form to the user with the fields "Comments", "Server name", "Patch number" and "Restart after hours". The user must fill in the required fields and can optionally fill in the patch number field before submitting the form to continue the change.
Argument options
Each input argument can accept the following options:
| Parameter | Description | Default |
|---|---|---|
default_value | The default value to be displayed to the user for the input argument. It is converted to the argument's type and, if valid_values are supplied, it must be one of them - or, for an :array argument, every element must be one of them. It is replaced by a value supplied when the change is started. Omit it when the argument has no default: a nil or blank default (an empty or whitespace-only string, or an empty array or hash) is reported as an error when your actions are loaded. false is a valid default for a :boolean argument. | none |
description | A description to be displayed to the user for the input argument. | nil |
fan_out | Whether the step runs its child steps once for each value of this argument. Only one :array argument on a step can set it — see fanning out an input step. | false |
gui_name | The name to be displayed to the user for the input argument. | The argument's name in title case (e.g. "Server name" for server_name) |
overwrite | Whether the value provided by the user may replace a value already configured on the project, environment, asset or template version at the specified path. Left false, the user can still supply the value that is already stored — only a value that would change it is rejected — and can always replace a value supplied when the change was started. | false |
path | The path in the change override properties that the value will be nested under, by the argument's name. E.g. in the example above, if the user supplied 'db1' for the server_name argument, MintPress will update the change override properties to include { database: { server: { server_name: 'db1' } } }. | / (the root path) |
required | Whether the user must provide a value for the input argument before they can submit the form to continue the change. An empty array or hash, or a blank string, does not count as a value, but false does. Only required arguments hold up a step that is continuing automatically. | true |
type | The data type of the input argument. Available options are :boolean, :date, :float, :integer, :string, :array, :hash, :sensitive. See sensitive input arguments for the :sensitive type. | :string |
valid_values | The list of values the user can select from for the input argument, displayed as a list of choices rather than a free text field. For the :array type, the user can select any number of the values. Available for the :array, :boolean, :date, :float, :integer and :string types. | nil |
The input arguments must be supplied as an array. Each element of the array is either an argument name, or a hash of argument names and their options. In the example above, the comments argument assumes default values for the various parameters, and has no default value. e.g.
comments: { description: nil, gui_name: 'Comments', overwrite: false, path: '/', required: true, type: :string }
The remaining arguments in the example override these defaults as needed. For example the restart_after_hours argument will require a boolean response from the user rather than a string.
Arguments are free to share a path — each value is nested under it by the argument's own name, so nothing is overwritten. What must be unique is the argument name, and a name cannot contain a /. Both are reported as an error while your actions are loaded, naming the offending argument and the actions.rb line the input arguments were declared on.
Every part of an argument's path above the argument must be an object, or not yet exist, in the change's property overrides. If one is a string, number, boolean, array or null, the value is refused with Input argument <name> cannot be written to <path> because <parent path> in the change properties is <type>, not an object. Continuing the step fails, and a step continuing automatically stays waiting with that reason in the change log. A - can only be the last part of a path.
Restricting the values a user can supply
Supplying valid_values for an input argument limits the user to a fixed set of values. Rather than being able to type any value, the user selects one of the values you have listed. e.g.
action :deploy,
steps: [
OpsChain.input_step(
step_name: 'Deployment options',
input_arguments: [
target: { path: '/deploy', gui_name: 'Target environment', valid_values: %w[development test production], default_value: 'test' },
replicas: { path: '/deploy', type: :integer, valid_values: [1, 2, 4, 8] },
cutover_date: { path: '/deploy', type: :date, valid_values: ['2026-06-30', '2026-09-30'], required: false },
regions: { path: '/deploy', type: :array, valid_values: %w[sydney melbourne perth], default_value: %w[sydney] }
]
),
:deploy_application
]
Valid values:
- must be supplied as a non empty array
- can only be supplied for the
:array,:boolean,:date,:float,:integerand:stringtypes — the:hashand:sensitivetypes do not support them - are converted to the argument's
type, with any duplicates removed — e.g.valid_values: ['1', 1, 2]for an:integerargument becomes[1, 2]. An:arrayargument's values are not converted — see selecting several values - must include the argument's
default_value, if one is supplied
Selecting several values
An :array argument with valid_values lets the user select any number of the listed values. In the example above, regions is presented with sydney already selected, and the user can add melbourne, perth, or both.
The valid values of an :array argument are the elements the array may hold, and they work differently from those of the other types:
- each value must be a string, number or boolean — a Ruby symbol is accepted and becomes a string, so
%i[sydney melbourne]is equivalent to%w[sydney melbourne]. Arrays, hashes andnilare rejected - values are kept as written rather than converted to a type, so a list can mix types, e.g.
[1, 2, 'all'] - two values that display the same are rejected, as the user could not tell them apart — e.g.
[1, '1'],[true, 'true'],[1, 1.0]or['a', ' a'] - every element of the
default_valuemust be one of the values
When the step is continued, each element of the submitted array must be one of the valid values, compared by type as well as value — 1 and '1' are different values, while 2 and 2.0 are the same. The step reports every element that is not one of them. Any duplicate elements are removed, so selecting a value twice records it once. An :array argument without valid_values keeps its duplicates.
Input argument value conversion
The default_value and valid_values you supply do not need to be written in the argument's type — MintPress converts them when it loads your actions.rb. e.g. an :integer argument with default_value: '10' presents a default of 10, and a :boolean argument with default_value: 'yes' presents a default of true.
Values that cannot be converted without losing information are rejected as the actions are loaded, allowing you to find the problem before the change reaches the input step. e.g. default_value: 1.5 for an :integer argument, or valid_values: %w[yes no maybe] for a :boolean argument, will report an error identifying the argument and the offending value.
Sensitive input arguments
Give an argument type: :sensitive when you are asking for a password, token or other secret:
action :rotate_credentials,
steps: [
OpsChain.input_step(
step_name: 'Database credentials',
input_arguments: [
db_username: { path: '/database', gui_name: 'Username' },
db_password: { path: '/database', gui_name: 'Password', type: :sensitive, description: 'Password for the service account' }
]
),
:apply_credentials
]
MintPress encrypts the value as the step is continued and stores only the encrypted form in the change's property overrides. The plaintext is never written to the database, and the events recording the step's continuation show {{hidden}} in place of the value.
Your action reads the argument like any other property. OpsChain.properties.database.db_password returns the plaintext — MintPress decrypts the value as the property is read and registers it with the logging data masker at the same time, so a value that reaches the step log is replaced with asterisks.
A sensitive argument is always a free text field, and the value is always treated as a string:
- it cannot declare a
default_value— there is nowhere to put a secret in youractions.rbthat would not be committed to your repository - it cannot declare
valid_values— a secret is not chosen from a list
Both are reported as an error while your actions are loaded, naming the offending argument.
A workflow answers a sensitive argument through a placeholder rather than a literal — see supplying a sensitive input argument.
Encryption protects the value at rest and in the OpsChain API. It does not hide the value from the change itself — any action in the change can read the decrypted value from the properties the argument writes to.
Answering input arguments when starting a change
An input step's arguments can be answered when the change is created, rather than only once the change has stopped at the step. Supply each value in the change's property overrides at the path the argument writes to, under the argument's own name. When the step starts waiting, the value found there becomes that argument's default_value, so the form the step presents to the user opens with it already filled in.
For the server_name argument in the example above, whose path is /database/server, the value belongs at /database/server/server_name:
{ "database": { "server": { "server_name": "db1" } } }
Answering every required argument this way lets a change run through its input steps without stopping — an input step that does not require approval continues automatically once every required argument has a value.
A sensitive argument can be answered this way too. A change that knows its steps as it is created — a change against an asset, or one created from a template — encrypts the value as part of creating the change. A change against a project or environment reads its steps from your repository as it runs, so the value you supply is stored unencrypted until the change reaches the input step. MintPress encrypts it at that point, encrypts the earlier property versions holding it, and masks it in the event recording the change's creation.
A value supplied this way is converted to the argument's type, the same as a default_value declared in your actions.rb. A value that cannot be converted without changing it, such as 1.5 for an :integer argument, 5 for a :date argument or maybe for a :boolean argument, leaves the argument with no default at all — the declared default is not used in its place — so the step stops rather than continuing with a value the user did not ask for, and the reason is written to the change log.
A null at the argument's path, or anywhere above it, in the change's property overrides leaves the argument with no default, and its declared default_value is not used in its place.
Each rejected value is reported against its own argument as well, naming the argument, its type and the path the value was read from, so you can tell which of a step's arguments was refused.
An argument's valid_values are not checked when the change is started. A step earlier in the change can rewrite them before the input step is reached, so the list in force at the step is not necessarily the one recorded when the actions were loaded — a value is checked against the list the step itself presents. The GUI's Input step arguments panel offers valid_values as suggestions rather than a closed list for the same reason. A :boolean argument, whose list cannot change, keeps its picker.
An input step is allowed to replace a value the change itself supplied, whatever the argument's overwrite setting says. overwrite governs the properties configured on the project, environment, asset or template version; a value the user put in the change's own overrides is their input for this run, and the step that asks for it can change it.
The change's property overrides are not the only way an argument gets a value. An input step earlier in the same change writes its answers to those same properties, so it can answer a later step's argument. Retrying a change carries the overrides across, including the answers its input steps merged in, so the retried change continues those steps on the answers already given rather than asking for them again.
In the GUI, the run change dialog's Input step arguments panel lists the arguments of every input step in the chosen action and writes the answers into the change's property overrides for you — see answering input steps up front.
Nesting child steps under an input step
Like wait steps, an input step can be given its own child steps via the steps: option. Nested steps do not start until the input step is submitted — they never run if the input step is rejected, times out, or errors while still waiting.
action :do_something, steps: [
OpsChain.input_step(
step_name: 'Server details',
input_arguments: [:server_name],
steps: ['do_something_with_input']
)
]
OpsChain.input_step also accepts ignore_failure: alongside steps:, with the same semantics as OpsChain.step. It also accepts run_as:, which sets how its child steps run, as for any action.
Fanning out an input step
An input step can run its child steps once for each value the user supplies. Mark an :array argument with fan_out: true, and when the step is continued it splits into one branch per value. Every branch runs its own copy of the input step's child steps, and the steps in a branch can read which value they are running for.
Use this when the same steps have to be repeated across a list that is only known when the change runs — the servers to patch, the regions to deploy to, the databases to upgrade.
action :patch_servers,
steps: [
:prepare_patch,
OpsChain.input_step(
step_name: 'Servers to patch',
run_as: :sequential,
input_arguments: [
servers: { path: '/patching', type: :array, fan_out: true, description: 'The servers to apply the patch to' }
],
steps: %i[stop_server apply_patch start_server]
),
:notify_complete
]
action :stop_server do
exec_command('ssh', OpsChain.fan_out_target, 'systemctl stop myapp')
end
When the change reaches Servers to patch it waits for a list of servers. If the user supplies db1, db2 and web1, the step continues into three branches. Each branch runs stop_server, apply_patch and start_server for its own server, and the three branches run at the same time. notify_complete starts once every branch has finished.
Declaring the argument that fans out
The argument that fans out:
- must have
type: :array - must be required —
required: falseis rejected - must be the only argument on the step with
fan_out: true - can only have a
default_valuemade up of non-blank strings, numbers and booleans
These rules are checked as your actions are loaded, and a breach is reported naming the argument. The argument's other options work as they do for any :array argument: its value is written to the change's property overrides at its path, and valid_values turn it into a list the user picks targets from.
The step can have other input arguments alongside the one that fans out. Their values are written to the properties as usual, and every branch sees the same value.
Reading the branch's target
OpsChain.fan_out_target returns the value the current branch is running for. Any step inside the branch can call it, however deeply nested.
action :apply_patch do
OpsChain.logger.info "Patching #{OpsChain.fan_out_target}"
end
The value keeps the type it was supplied with. A target supplied as 2 is returned as the integer 2, and one supplied as true as the boolean true. OpsChain.fan_out_target returns nil outside a fan out, so an action that calls it can also be used on its own.
How the branches run
The branches always run in parallel. The input step's run_as: sets how the steps inside each branch run: with run_as: :sequential (the default) each branch runs its steps one after another, and with run_as: :parallel they all start at once.
When the step is continued, MintPress adds two levels of steps beneath it: an opschain_fan_out_stage step that holds the branches, and one step per target, named after the target. For the example above the step tree becomes:
patch_servers
├── prepare_patch
├── Servers to patch
│ └── opschain_fan_out_stage
│ ├── db1
│ │ ├── stop_server
│ │ ├── apply_patch
│ │ └── start_server
│ ├── db2
│ │ └── ...
│ └── web1
│ └── ...
└── notify_complete
A step inside a branch has a path such as patch_servers/Servers to patch/opschain_fan_out_stage/db2/apply_patch. The stage and target steps only group the branches — they do not run an action of their own.
A branch's steps are those the input step had when it was continued. Until then the change's step tree shows the input step with its child steps listed once.
opschain_fan_out_stage is reserved for fan outs. Do not give an action or a step that name.
Supplying the targets
The targets are supplied like any other input argument: when continuing the step, or when the change is started. Each target must be a non-blank string, a number or a boolean.
- Duplicate values are removed, keeping the first.
['a', 2, true, 'a']fans out into three branches,a,2andtrue. - A step can fan out into at most 100 branches.
- An empty list is not a value, because the argument is required.
Continuing the step with a list that breaks one of these rules is refused, and the error names the argument and the values that were not accepted. Nothing has fanned out at that point, so you can continue the step again with a corrected list.
Like any input step, a step that fans out continues automatically when every required argument already has a value — from its default_value, or from the change's property overrides. If the value from the property overrides is not a list of strings, numbers and booleans, it is not used: the step waits for someone to continue it, and the reason is written to the change log.
Each branch's step takes its name from its target, and so does its path, with any / in a target replaced by _. Two targets that would give the same path — SYD and syd, or a/b and a_b — still run as separate branches, and the second one's path ends in -1. OpsChain.fan_out_target returns the target as it was supplied, so a branch whose path is a_b still reads a/b.
Fanning out with OpsChain.step
The step wrapper builds an input step from input_arguments:, so it fans out in the same way. Each branch runs the wrapped action:
action :restart_all, steps: [
OpsChain.step(:restart_server, input_arguments: [servers: { path: '/restart', type: :array, fan_out: true }])
]
Steps inside a branch
A branch can hold any step a change can — including wait steps, input steps and approval steps. An approval step in a branch is approved separately in each branch, so a change that fans out into three branches stops at three approval steps. While any step in a branch is waiting, the change shows as waiting.
A fan out cannot be nested inside another. An input step inside a branch can ask for input, but it cannot have a fan_out: true argument of its own. A nested fan out is reported when MintPress builds the action's step tree, or at the latest when the inner input step is continued, which is refused.
A branch that fails fails the fan out, unless its failure is ignored. Use ignore_failure: on a step inside the branch, as you would anywhere else, to let the other steps carry on. The other branches keep running whether or not one fails.
Skipping steps in a fan out
The targets are not known when the change is created, so steps to skip are written against the input step's child steps as your actions define them, without the stage and target steps. In the example above, patch_servers/Servers to patch/start_server skips start_server in every branch.
A path written against the template, as above, skips that step in every target. A path that names a target skips it in that target only. To leave a whole target out, do not include it in the input step's answer.
Starting a change partway through a fan out
A change can start at an input step that fans out, but not at a step inside one. Starting at a step inside a fan out is refused with '<step>' is inside a fan out - start the change at the input step that fans out instead.
Retrying a change that fanned out
A retried change keeps the branches of the change it retries, with the same targets — a retry cannot supply new answers to an input step. Branches that completed are not rerun; only the steps that failed or did not finish run again.
When the Git revision is re-resolved on retry (refresh_sha), the branches are still kept as they were. The steps that run again use the code from the new revision, but a step you have since added to or removed from the input step's child steps is not added to or removed from branches that already exist. To fan out over a different list of targets, or with a changed set of child steps, start a new change.
Approval steps
An OpsChain approval step pauses a change until the people you nominate approve it. A wait step can be continued by anyone able to run the change; an approval step can only be released by the users and LDAP group members named on it, and they can reject it as well as approve it.
Like a wait step, an approval step can only be added as part of a step's child steps:
action :deploy, steps: [
:build,
OpsChain.approval_step(
step_name: 'Production sign-off',
requires_approval_from: [
{ ldap_groups: %w[release-managers] },
{ user_names: %w[alice], ldap_groups: %w[security-officers] }
]
),
:deploy_application
]
The change pauses at the "Production sign-off" step once build completes. deploy_application starts when the step is approved. If the step is rejected, the change ends and deploy_application never runs.
Approvers respond from the GUI — the step's "triple dot" menu in the change's step tree, or the approval tab of manage activity — or via the API's POST /api/steps/{id}/approve and POST /api/steps/{id}/reject endpoints.
OpsChain approval steps use the opschain_wait_step_{{unique id}} naming convention, the same as wait steps - do not use this naming convention in your steps unless you intend to create one.
Workflow approval steps are a separate feature, configured in the workflow definition rather than in your actions.rb. This section covers approval steps within a change.
Naming who can approve
requires_approval_from takes an array of requirements. Each requirement is a hash with a user_names array, an ldap_groups array, or both.
Every requirement must be approved before the step continues. Within a single requirement, any one of the listed users, or any member of any of the listed groups, satisfies it. The example above needs two approvals: one from a member of release-managers, and one from either alice or a member of security-officers.
Each approval is recorded as it arrives — one that still leaves a requirement outstanding is noted in the step's log, and the step keeps waiting until the last one is met.
To require two different people to approve a step, give it two requirements rather than listing both people in one — a single requirement is satisfied by the first of its approvers to respond. The requires_approval_from setting works the same way.
Rejecting an approval step
Rejecting an approval step aborts it. Its child steps never run, its parent step fails, and the change finishes in the error state rather than continuing. ignore_failure: on the parent applies as it does to any other child step failure.
The rejected step itself reports the rejected status rather than aborted, so filter on rejected to find it — aborted does not match.
Approvals and rejections are recorded as audit:steps:approve and audit:steps:reject events, naming who responded and any message they supplied. An approval or rejection attempted by someone who is not an approver is refused and recorded as audit:steps:approve:denied or audit:steps:reject:denied.
A step that requires approval cannot be continued — continuing it is refused with You are not permitted to continue this step and recorded as an audit:steps:continue:denied event, and a change created with automatic continuation of wait steps leaves its approval steps waiting for their approvers.
Naming an approval step
An approval step appears in the step tree as Approval step unless you name it. Supply step_name: to say what is being approved — worth doing whenever a change has more than one gate:
OpsChain.approval_step(step_name: 'Production sign-off', requires_approval_from: [{ ldap_groups: %w[release-managers] }])
Nesting child steps under an approval step
Like wait steps and input steps, an approval step can be given its own child steps via the steps: option. Nested steps do not start until the approval step is approved, and never run if it is rejected.
action :destroy, steps: [
OpsChain.approval_step(
step_name: 'Confirm destroy',
requires_approval_from: [{ ldap_groups: %w[ops-team] }],
steps: ['Shutdown']
),
'infra_destroy'
]
OpsChain.approval_step also accepts ignore_failure: alongside steps:, with the same semantics as OpsChain.step.
Approver names are checked when your actions are loaded
Each name you supply is checked against the MintPress users and the LDAP directory as your actions.rb is read. A name that matches neither is reported in the change or task log and recorded as a warn:approval_identity_unresolved event, so a misspelled approver surfaces as your actions are loaded rather than only when a change reaches the step.
Your actions still load and the step still runs — a name that matches nothing cannot approve. If every name on a requirement is unmatched, nobody can release the step. The names are checked again as the step starts waiting, and any that still match nothing are named in a warning in the step's log, beneath the approvers the step is waiting for.
If the LDAP directory cannot be reached the names are accepted as supplied, the log records that they could not be validated, and a warn:approval_identity_validation_skipped event is created.
Approver names are compared without regard to case, so a name that differs from the directory only in capitalisation still identifies the same person or group. The equivalent checks for the requires_approval_from setting happen when the settings are saved.
Approval steps and the requires_approval_from setting
An approval step declared in your actions.rb is independent of the requires_approval_from setting an administrator configures on a project, environment or asset. A change subject to both stops twice — once at the change's own approval step, and again at the step you declared — and each gate needs its own approvers. The two approver lists are not merged: being named in the setting does not allow someone to approve a step declared in your actions, or the other way around.
They also differ over the person who created the change. A setting rule that the creator satisfies is dropped rather than applied, because nobody is asked to approve their own change. An approval step you declare is not — name the creator on one and they must approve it themselves.
See approving a change for what the change level gate looks like.
Ignore failure steps
OpsChain.ignore_failure_step is designed for MintModel actions used as child steps. MintModel step definitions cannot set ignore_failure: true directly, so this helper creates a thin wrapper action around the named step with ignore_failure: true applied, allowing the change to continue even if the MintModel step fails.
action :destroy, steps: [
OpsChain.ignore_failure_step('Shutdown'),
'infra_destroy'
]
In this example Shutdown will run, but if it raises an error the change continues to completion rather than being marked as failed. The wrapper step, and the change, finish in the warning state.
Step wrapper
OpsChain.step is a convenience helper that combines wait, input, approval and ignore failure behaviours around an existing action in a single call. It takes the name of an existing action and one or more options:
| Option | Default | Description |
|---|---|---|
ignore_failure: | false | If true, the change will continue even if the wrapped action fails. |
wait: | false | If true, the wrapped action becomes a child of a new wait step — the change pauses for manual continuation before the wrapped action starts. Pass a number to sleep for that many seconds instead. Mutually exclusive with input_arguments: and requires_approval_from:. |
input_arguments: | nil | The wrapped action becomes a child of a new input step — the change pauses and prompts the user for input before the wrapped action starts. Mutually exclusive with wait: and requires_approval_from:. |
requires_approval_from: | nil | The wrapped action becomes a child of a new approval step — the change pauses until the nominated users or LDAP group members approve it before the wrapped action starts. Mutually exclusive with wait: and input_arguments:. |
step_name: | nil | A custom display name for the resulting step — the wait, input or approval step when wait:/input_arguments:/requires_approval_from: is used, or the wrapper step otherwise. |
wait_step_name: | nil | A custom display name for the wait, input or approval step specifically. Only relevant alongside wait:/input_arguments:/requires_approval_from:; takes precedence over step_name: if both are given. |
run_if: | nil | A lambda. The wrapped action runs only when it holds; otherwise the step is set to skipped. Cannot be combined with wait:, input_arguments: or requires_approval_from:. See running a step only when a condition holds. |
action :destroy, steps: [
OpsChain.step('Shutdown', wait: true, ignore_failure: true),
'infra_destroy'
]
In this example the change pauses at a wait step, with Shutdown nested as its child — Shutdown only starts once the wait step is continued or approved. If the wait step itself is rejected, times out, or errors, Shutdown never runs, regardless of ignore_failure:. ignore_failure: here applies to Shutdown's own outcome: if Shutdown runs but fails, the wait step finishes warning rather than failing, and the change continues to infra_destroy.
Pass a number of seconds to wait: for a timed wait:
OpsChain.step('Shutdown', wait: 90, ignore_failure: true)
Use requires_approval_from: to put an approval step in front of the wrapped action instead, so that only the people you name can release it:
action :destroy, steps: [
OpsChain.step('Shutdown', requires_approval_from: [{ ldap_groups: %w[ops-team] }]),
'infra_destroy'
]
If no behavioural options are provided, OpsChain.step returns the action name unchanged — no wrapper is created.
OpsChain.step('Shutdown') # returns 'Shutdown' — safe no-op
When wait:, input_arguments: or requires_approval_from: is used, OpsChain.step returns the wait, input or approval step itself (with the wrapped action nested as its child) rather than a separate wrapper step. Its default display name is derived from the wrapped action name and the active options, for example Run "Shutdown" waiting for explicit continue, ignoring failures or Run "Shutdown" after approval.
With none of wait:, input_arguments: or requires_approval_from: (i.e. ignore_failure: alone), OpsChain.step still creates a separate wrapper step around the wrapped action, named the same way; subsequent calls with the same action name and options append an incrementing suffix (Run "Shutdown" ignoring failures 2, etc.).
Neither OpsChain.step nor OpsChain.ignore_failure_step accepts a timeout:, as the step they create only runs the wrapped action. Set the timeout on the wrapped action instead.
To store a build artifact for a later action or change to load - including one running on a different site in a highly available deployment - see artifacts.
Defining resource types & resources
If this is the first time you've looked at MintPress resource types and resources, our tutorial on implementing resource types could be a better place to start.
Resource types can be defined using the resource_type keyword:
resource_type :city do
property :name
property :weather
desc 'Output how the weather looks in the city'
action :report_weather do
puts "The weather in #{name} looks #{weather}"
end
end
The city resource type can now be used to create city resources:
city :melbourne do
name 'Melbourne'
weather 'cold'
end
These resources will automatically include the name and weather properties, as well as a report_weather action. In this example a melbourne resource will be created with a melbourne:report_weather action. Running this action will output:
The weather in Melbourne looks cold
- The resource type name (
city) and resource name (melbourne) should conform to ruby variable naming standards. This means the name can include alphanumeric characters and the underscore character however it cannot start with a number or a capital letter. This ensures it can be easily referenced from other ruby code or the command line. - The action description assigned via the
desckeyword in the example above is optional.
Property value types
Resource properties can accept any valid Ruby value, including strings, numbers, booleans, arrays, and hashes.
String and simple value properties
Simple string and numeric properties are set directly:
database :app_database do
host 'db.example.com'
port 5432
encrypted true
end
Array properties
Arrays can be passed directly as property values:
server :web_server do
name 'web1'
allowed_ports [80, 443, 8080]
end
Hash properties
To pass a hash (dictionary) as a property value, wrap the hash in parentheses using the property method name as a method call. The parentheses are required — without them Ruby will interpret the braces as a block rather than a hash literal, which causes an error.
ssh_host :prod_server do
host 'prod.example.com'
# Correct — with parentheses:
host_options({'final_user' => 'oracle', 'connect_user' => 'root', 'keys' => ['/opt/opschain/prod_key']})
# Incorrect — without parentheses (causes an error):
# host_options {'final_user' => 'oracle', ...} # ✗ Error: unexpected block
end
In the example above, host_options is a hash with three keys: final_user, connect_user, and keys (which contains an array of key file paths).
Within your actions, hash properties are accessed using dot or bracket notation, just like any other property:
action :connect do
options = controller.host_options
final_user = options['final_user'] # or options.final_user
connect_user = options['connect_user']
keys = options['keys']
end
Lazy property evaluation
By default, property values are assigned to resources when the actions.rb is first loaded. If a property's value is slow to resolve, (e.g. the result of an API response) then this can have a dramatic effect on the actions.rb evaluation time - which is done during every step in a change.
For example, to resolve the city resources in the actions.rb below, MintPress will need to make two calls to the weather bureau API (to derive the weather for Sydney and Melbourne):
city :melbourne do
name 'Melbourne'
weather WeatherBureauAPI.get_melbourne_weather
end
city :sydney do
name 'Sydney'
weather WeatherBureauAPI.get_sydney_weather
end
The two API calls will be made irrespective of what action is being run from the file. To avoid calling the API unnecessarily, MintPress provides the lazy keyword to instruct MintPress to derive the property value when the property is first used:
city :melbourne do
name 'Melbourne'
weather lazy { WeatherBureauAPI.get_melbourne_weather }
end
city :sydney do
name 'Sydney'
weather lazy { WeatherBureauAPI.get_sydney_weather }
end
Now a call to the weather bureau API for a city's weather will only be made if an action requests the value of its weather property.
The is_a?, kind_of? and instance_of? Ruby methods allow you to test the class of an object. Prior to resolving the lazy property's value, these will all respond with true when supplied the argument LazyPropertyValue e.g.
weather.is_a?(LazyPropertyValue) # => true
weather.is_a?(String) # => false
Once the lazy property has been resolved (by calling any other method on the lazy property), the is_a?, kind_of? and instance_of? methods will apply to the resolved value.
whether.nil?
weather.is_a?(LazyPropertyValue) # => false
weather.is_a?(String) # => true
The OpsChain keywords in a resource definition
A resource type definition, a resource definition, an each_child block, an inline action body and a lazy property value are all evaluated against the resource being built, so the OpsChain keywords are called directly, without the OpsChain. prefix:
| Logging and commands | log, opschain_cli |
| Change data | properties_for, repository_properties, repository_properties_for, context, dry_run? |
| The API and secrets | query, secret_vault |
| The asset's MintModel | mintmodel_actions |
| Other resources | ref (or resource) |
| Property values | lazy |
This lets a resource work out its own properties from MintPress itself. Doing so inside a lazy block is usually what you want, so the lookup only happens when an action asks for the value:
weblogic_domain :wls do
region lazy { query(:mintmodel, project: 'demo', environment: 'dev', asset: 'wls')[:region] }
admin_password lazy { secret_vault.get('demo/wls', 'admin_password') }
debug lazy { context.parents.environment.code == 'dev' }
end
Each behaves exactly as it does at the top level of your actions.rb, and each is documented in its own section of this guide. query, secret_vault, context, dry_run?, mintmodel_actions, properties_for, repository_properties and repository_properties_for can still be written with the OpsChain. prefix, so an existing resource definition does not have to be rewritten. log and opschain_cli have no prefixed form — their full paths are OpsChain.logger and OpsChain::Dsl::CliCommand.execute.
Keywords a resource definition does not have
exec_command, send_email and create_event, and the keywords that add child steps or store files — step, steps, wait_step, input_step, approval_step, ignore_failure_step, append_child_steps, child_steps, child_execution_strategy, run_action, store_file! and remove_file! — are deliberately unavailable in a resource definition.
Your actions.rb is read in full every time MintPress needs it: once for every step of a change, and again while MintPress works out the change's step tree and the actions a template offers. A keyword that acts on something outside MintPress, or that adds to the step tree, would therefore run far more often than you intend. Call these from an action or a controller method instead, which run only when the step runs.
properties is not the change's properties here either — in a resource definition it is the bulk property setter. Read the change's properties with OpsChain.properties.
When a property has the same name as a keyword
A property always wins. A resource type that declares property :query, or a resource that inherits a context property from its composite parent, keeps that property — the keyword of the same name is not available in that resource, and OpsChain.query or OpsChain.context reaches the keyword instead.
A resource or resource type named after one of these keywords is the other way around: the keyword wins, and the resource is reached with ref — ref(:secret_vault) — or given another name.
A controller can declare a property named after one of these keywords too. Doing so costs the controller that keyword for the whole of the class, so MintPress logs a warning naming the property when it happens.
Controller
Defining inline actions as in the example above limits your ability to adequately test the action code. Moving the code into a controller class allows the code to more readily be tested and reduces the need to change your resource type definition to change its action logic.
A controller is a Ruby class. MintPress builds one instance of it per resource, hands it that resource's properties, and exposes the methods you nominate as actions on the resource.
A controller that inherits from OpsChain::Dsl::BaseController gets its constructor, the OpsChain keywords inside its methods, and its actions and properties derived from the class itself. Writing a controller without the base class is still supported, and is what you need when your controller already has a superclass of its own.
The base controller
Re-writing the example above using the base controller:
class CityController < OpsChain::Dsl::BaseController
property :name
property :weather, default: 'unknown'
desc 'Output how the weather looks in the city'
def report_weather
log.info "The weather in #{name} looks #{weather}"
end
end
resource_type :city do
controller CityController
end
That is the whole definition. The properties and the action are declared once, in the class, so the resource_type block has nothing to repeat, there is no constructor to write, and log is called without the OpsChain. prefix.
The city resource type is used exactly as before:
city :melbourne do
name 'Melbourne'
end
Running the resulting melbourne:report_weather action logs The weather in Melbourne looks unknown.
OpsChain::Dsl::BaseController comes from the opschain gem. If your code runs outside MintPress you need require 'opschain' at the top of the file, as described under defining standalone actions.
Controller properties
The property class method declares a property the resource accepts and, at the same time, defines a private reader for it on the controller:
class DatabaseController < OpsChain::Dsl::BaseController
property :host
property :port, default: 5432
property :url, default: -> { "postgres://#{host}:#{port}" }
end
- Each declared property is reported to MintPress as a resource type property, so a resource can set it without the resource type having to repeat
property :hostitself. MintPress reads that list from the class'sresource_type_propertiesmethod, which the base controller derives from yourpropertydeclarations. A controller written without the base class writes the method by hand. - A
default:applies when the resource does not set the property, or sets it tonil- unless the property is declaredkeep_nil: true, described below. - A
default:that responds tocallis evaluated against the controller when the property is read, so it can build its value from the other properties. It is evaluated on every read rather than being remembered after the first. - A
coerce:normalises every value the reader returns, whether the resource supplied it or it came from thedefault:. It is evaluated against the controller, so it can build its result from the other properties, and it is checked where it is declared rather than on the first read: it must be callable and accept the property value as its only argument. - A coercion is never handed a
nil, and one that returnsnillets thedefault:take over. That is how a controller reads a blank value as an absent one. keep_nil: truetells the reader that anilthe resource set deliberately is a value of its own, so thedefault:applies only to a property the resource never set at all. It is the value the resource set that has to benil, not merely the key that has to be present, and anila coercion produced is still an absent value.required: trueraisesOpsChain::MissingPropertyErrorwhen the property still reads as missing once the coercion and the default have been applied. Missing meansnil, or empty - an empty run list is no more use to a controller than no run list at all - so a value that cannot be empty,falseincluded, is a value. The message names the property, asAn "environment" property is required.- The readers are private, because they are part of your controller's implementation rather than actions on the resource.
Together they let a controller state what it needs, rather than checking for it at every call site:
class ChefNodeController < OpsChain::Dsl::BaseController
property :environment, required: true
property :run_list, coerce: ->(value) { Array(value).reject(&:empty?) }, required: true
property :store_in, default: '/chef/result', keep_nil: true
end
environmentis reported as missing the first time the controller reads it, rather than failing further in with whatever anilenvironment does next.run_listaccepts a single recipe as a string and reads it as a one element list. A list of blank entries coerces to an empty list, whichrequired: truethen reports as missing.store_inwrites to/chef/resultunless the resource says otherwise, and a resource that setsstore_in nilturns the write back off rather than getting the default.
A property name has to be one a resource can actually set, and one that does not collide with your controller's own code, so property rejects three kinds of name as the class is defined:
| Rejected name | Example | Why |
|---|---|---|
| An OpsChain keyword the controller relies on | property :log | The keyword would no longer be callable inside your methods |
| A resource keyword | property :controller | A resource definition could never set it — the name already means something else there |
| A method the controller already defines | def host above property :host | The reader would replace your method |
Declaring a property a superclass already declared, to give it a different default, is not a collision.
The declared properties are reported as the controller's dry_run_properties as well, so they are also available while MintPress is discovering what your actions are rather than running one of them, and a resource definition that sets them is valid in both cases.
Properties shared by a family of controllers
Controllers built around the same tool usually share properties - where the tool's configuration file lives, where the result is written back into OpsChain properties. Declaring them in a module that extends OpsChain::Mixins::SharedControllerProperties declares them once, and every controller that includes the module gets them:
module ChefProperties
extend OpsChain::Mixins::SharedControllerProperties
property :knife_config, default: '/etc/chef/knife.rb'
property :store_in, keep_nil: true
end
class ChefNodeController < OpsChain::Dsl::BaseController
include ChefProperties
property :name, required: true
end
ChefNodeController accepts knife_config, store_in and name, and reports all three as its resource type properties.
- The properties arrive with every option the module declared them with, the coercions and the
keep_nilincluded. - Each declaration is still validated against the controller that receives it, so a name that collides with something in the including controller is reported against that controller as the class is defined.
- The receiving class only has to be one that takes
propertydeclarations, so a controller built from the modules rather than fromOpsChain::Dsl::BaseControlleraccepts a shared properties module too. - Including the module in a class that does not take
propertydeclarations at all raises as that class is defined, naming the module it is missing rather than leaving the properties silently undeclared.
The controller properties hash
Whatever the resource sets is also available as a whole, through controller_properties:
class DatabaseController < OpsChain::Dsl::BaseController
property :host
def report
log.info "#{resource_name} connects to #{controller_properties[:host]}"
end
end
controller_properties is the hash MintPress builds the controller with. It holds every property the resource carries — those declared with property, and any the resource sets in bulk with properties — plus opschain_resource_name, the name of the resource the controller was built for, which is also available directly as resource_name. Keys can be read as symbols or strings.
properties and controller_properties are different thingsInside a controller, properties is the change's properties document — the same thing OpsChain.properties returns at the top level of your actions.rb. controller_properties is the resource's own properties. To read the resource's host use host or controller_properties[:host], never properties[:host].
Read the properties when you need them rather than in a constructor. Resource properties can be lazy, and reading one resolves it, so touching them all up front does work the action may never need. Declaring them with property gives you this for free.
Controller actions
The base controller derives the resource's actions from the class itself: every public instance method that can be called without arguments becomes an action on the resource.
| Method | An action? | Why |
|---|---|---|
def report_weather | yes | public, takes no arguments |
def deploy(force = false) | yes | can be called without arguments |
def deploy(*args) | yes | can be called without arguments |
def deploy(force) | no | requires an argument |
def deploy(force:) | no | requires a keyword argument |
def resolve_host under private | no | not public |
def run_during_dry_run | no | reserved by MintPress |
a method named after a declared property | no | that name is the property's reader — MintPress warns that the method shadows it |
the methods of Object and of the base class | no | not methods you defined |
A method your controller inherits from your own intermediate class, or picks up from a module it includes, counts as one of yours, so a hierarchy of controllers and a module of shared actions both contribute actions to the resource.
MintPress reads the derived list from the class's resource_type_actions method, the counterpart of resource_type_properties above. A controller written without the base class writes that method by hand too.
The action list is read when the controller line in your resource_type block runs, so the class must be complete by that point. Define the controller — or require the file that defines it — above the resource_type that uses it. A method added to the class after that line has run is not an action.
Describing a controller action
Every derived action carries a description, defaulting to the method's own name. The desc class method supplies a better one, and applies to the next method defined after it:
class CityController < OpsChain::Dsl::BaseController
desc 'Output how the weather looks in the city'
def report_weather
...
end
desc 'Send a postcard from the city', step_name: 'Send a postcard', ignore_failure: true
def send_postcard
...
end
def internal_action
...
end
end
desc accepts the description as its first argument, followed by any of the same options an available_actions: entry accepts:
| Option | Purpose |
|---|---|
step_name: | The step name shown in the GUI, in place of the method name |
ignore_failure: | Continue the change when the action raises, rather than failing the step — see ignoring an action failure |
reload_actions: | Read actions.rb again before the action's step runs |
timeout: | Fail the step when the action runs longer than this many seconds — see action timeouts |
A description can be omitted when you only want the options — desc step_name: 'Send a postcard' is valid.
An action defined without a desc is described by its own method name, so internal_action above is listed and offered in the GUI as internal_action.
Because desc applies to the next method defined, it must be immediately followed by a method definition. A property, a not_actions, an include, prepend or extend, or a second desc between the two is an error, raised as the class is defined, rather than the description quietly attaching itself to a later method:
Unable to use "not_actions" here - the preceding desc can only annotate a controller action method
Other code between the two is not rejected — a constant assignment, say — and the desc still annotates whichever method is defined next, so keep a desc and the method it describes together.
A desc written above a def self. class method has nothing it can annotate, and MintPress logs a warning for it as the class is defined. A desc left dangling at the end of the class body is warned about later, when MintPress works out the resource's actions.
The description is desc's first argument rather than a keyword, so write desc 'Deploy the server' and not desc description: 'Deploy the server'.
Hiding a controller action from the action list
Some actions only make sense as part of another action, and should not be offered for a user to run on their own. Declare them with desc listed: false:
class RepositoryController < OpsChain::Dsl::BaseController
desc 'Commit the changes and push them to the remote'
def publish
...
run_action("#{resource_name}:push")
end
desc listed: false
def push
...
end
end
push is left out of the asset's actions in the GUI and the API, and out of opschain-action -T, but it is still an action: another action can run it with run_action or name it as a prerequisite.
listed: false combines with the other desc options, e.g. desc listed: false, ignore_failure: true. It does not take a description, because an unlisted action's description is never shown, and MintPress raises an error for one:
Unable to describe an action that is not listed - remove the description or the listed: false option
Omitting the desc does not hide an action, and neither does desc nil — a nil description is an error, so a description held in a variable that turns out to be nil does not silently list the action under its method name:
Unable to use a nil description - to keep an action runnable but leave it out of the action list use desc listed: false
To hide an action on one resource rather than on every resource of the type, leave it out of that resource's available_actions: instead.
Excluding a public method from the actions
A public method that is a helper rather than an action can be excluded with not_actions:
class CityController < OpsChain::Dsl::BaseController
desc 'Output how the weather looks in the city'
def report_weather
log.info "The weather in #{name} looks #{weather} (#{formatted_coordinates})"
end
def formatted_coordinates
...
end
not_actions :formatted_coordinates
end
not_actions takes any number of method names and can appear anywhere in the class body — before or after the methods it names — except directly below a desc, which has to annotate a method. Its exclusions are inherited by subclasses.
Making the method private has the same effect on the action list, so reach for not_actions when the method has to stay public — because another controller, a resource type action or a test calls it.
A method excluded with not_actions is not an action at all, so run_action and prerequisites cannot reach it either. To keep an action runnable but out of the action list, declare it with desc listed: false instead.
The OpsChain keywords in a controller
Inside a base controller the OpsChain keywords are called directly, without the OpsChain. prefix:
| Logging and commands | log, exec_command, opschain_cli |
| The resource | controller_properties, resource_name |
| Change data | properties, properties_for, repository_properties, repository_properties_for, context, dry_run? |
| Files | store_file!, remove_file! |
| Child steps | append_child_steps, child_steps, child_execution_strategy, step, steps, wait_step, input_step, approval_step, ignore_failure_step, run_action |
| The API and secrets | query, send_email, create_event, secret_vault |
| The asset's MintModel | mintmodel_actions |
| Other resources | ref (or resource) |
Each behaves exactly as it does at the top level of your actions.rb, and each is documented in its own section of this guide. The OpsChain. prefixed form keeps working everywhere, so an existing controller does not have to be rewritten to inherit from the base class.
child_stepschild_steps and child_execution_strategy can be assigned as well as read, and the assignment needs an explicit self.:
self.child_steps = ['do_a_different_thing']
Without it, Ruby reads child_steps = ... as a new local variable and nothing is assigned. This is a rule of the Ruby language rather than something specific to MintPress.
action and resource_type are deliberately not available in a controller. A controller carries out a resource's work; it does not declare resources or resource types. Declare those in your actions.rb or resources.rb, as described in defining resource types & resources.
Adding the base controller behaviour to an existing class
When a controller already has a superclass it cannot inherit from OpsChain::Dsl::BaseController, so the base class's behaviour is also published as three modules that can be adopted separately:
| Module | Adopted with | Provides |
|---|---|---|
OpsChain::Mixins::ControllerKeywords | include | The OpsChain keywords, as private methods |
OpsChain::Mixins::ControllerActions | extend | desc, not_actions, and the derived resource_type_actions |
OpsChain::Mixins::ControllerProperties | extend | property, and the derived resource_type_properties |
OpsChain::Mixins::SharedControllerProperties | extend, in a module of your own | property, declared once and replayed into every controller that includes your module. See properties shared by a family of controllers |
class CityController < OurCompany::BaseThing
include OpsChain::Mixins::ControllerKeywords
extend OpsChain::Mixins::ControllerActions
extend OpsChain::Mixins::ControllerProperties
def initialize(controller_properties)
@controller_properties = controller_properties
end
private
attr_reader :controller_properties
end
ControllerKeywords and ControllerProperties expect the controller properties to be readable as controller_properties, so a class that adopts them supplies the constructor and reader shown above — which is all OpsChain::Dsl::BaseController adds on top of the three modules.
A class built this way is a controller in every respect that matters to the modules: it takes property declarations with all of their options, contributes actions from the modules it includes, and accepts a shared properties module exactly as a class inheriting from the base controller does.
Writing a controller without the base class
A controller does not have to inherit from the base class, or use any of its modules. Any class works, provided it takes the resource's properties as a single argument and MintPress is told which of its methods are actions:
class CityController
def initialize(options)
@options = options
end
def report_weather
puts "The weather in #{name} looks #{weather}"
end
private
def name = @options[:name]
def weather = @options[:weather]
end
resource_type :city do
controller CityController, available_actions: [:report_weather]
property :name
property :weather
end
Resources created from this city resource type have the same actions, and produce the same output, as those created from the base controller definition above.
- The class constructor must accept a single Ruby hash parameter, which will include each of the resource properties defined on the resource. This hash is the resource's
propertiesat the time the controller is constructed. - The action methods must not require parameters.
- The resource type has to declare each property itself, because the class does not tell MintPress about them.
To improve performance, it's best to avoid using the options passed to the controller until they are needed (i.e. do @options = options, not @name = options[:name]).
Controller actions and properties
Rather than listing the actions on the resource type, a controller can name its own actions and properties through the resource_type_actions and resource_type_properties class methods. These are what the base controller derives for you; a class that does not use the base class can define them by hand:
class CityController
def self.resource_type_properties
%i[name weather]
end
def self.resource_type_actions
%i[report_weather]
end
def initialize(options)
@name = options[:name]
@weather = options[:weather]
end
def report_weather
puts "The weather in #{name} looks #{weather}"
end
private
attr_reader :name, :weather
end
resource_type :city do
controller CityController
end
Once again, resources created from this city resource type would have the same actions (and same action output) as those created from the earlier type definitions.
resource_type_actions can return a mixture of plain action names and the descriptive hashes described under available actions. E.g.
def self.resource_type_actions
[{ name: :action_with_description, description: 'An action with a description', step_name: 'GUI step name' }, :action_without_description]
end
A controller can also define dry_run_properties to declare the properties a resource may set while MintPress is discovering what your actions are. The base controller derives this from the declared properties; a class that does not use the base class and omits it will find those resource properties undefined during discovery.
Controller action method validation
MintPress validates that the controller defines all the methods that the resource type references (either via available_actions or resource_type_actions), and if the method does not exist it will report an error, e.g. CityController does not define the action method magic.
If using method_missing with a MintPress controller class then the corresponding respond_to_missing? method should be implemented.
If the class defines methods dynamically (or shouldn't be validated for another reason) the self.validate_action_methods? method can be defined on the controller class to modify this behaviour:
class CityController
def self.validate_action_methods?
false
end
def initialize(options)
define_singleton_method(:magic) do
puts "Who doesn't like magic?"
end
end
end
resource_type :city do
controller CityController, available_actions: [:magic]
end
Available actions
The available_actions: kwarg on controller selects which of the controller's actions are described — and so which are listed by opschain-action --tasks and offered in the GUI — and lets you set each one's description and options from the resource type rather than the controller class.
resource_type :city do
controller CityController, available_actions: [{ name: :report_weather, description: 'Output how the weather looks in the city' }]
end
available_actions:will expose each controller method supplied to it as an action on the resource.- An entry can be a plain method name, or a Ruby hash carrying that method's description. E.g.
available_actions: [{ name: :report_weather, description: 'Output how the weather looks in the city' }]. - Names and descriptive hashes can be mixed as required. E.g.
available_actions: [{ name: :report_weather, description: 'Output how the weather looks in the city' }, :action_without_description] - In addition to a custom description, each action hash can include the optional
step_name:,ignore_failure:,reload_actions:andtimeout:keys.step_name:overrides the step name displayed in the MintPress GUI.ignore_failure:(boolean) marks the action to continue the change on failure.reload_actions:(boolean) makes the action's step readactions.rbagain before it runs.timeout:(positive whole number of seconds) sets the action's timeout. E.g.available_actions: [{ name: :report_weather, description: 'Output how the weather looks in the city', step_name: 'Report the weather', ignore_failure: true }] - Alternatively,
available_actions:can be supplied as a hash where each key is an action name and the value is its description. E.g.available_actions: { report_weather: 'Output how the weather looks in the city' }.
available_actions: is optional. Omitted, the resource exposes whatever the controller reports through resource_type_actions — which, for a base controller, is derived from the class with the descriptions its desc declarations supply.
available_actions: replaces a desc rather than adding to itAn entry in available_actions: is the definition of that action, so it supplies the description and options in place of the controller's desc. Naming an action by its method name alone therefore leaves it with that name as its description and the default options:
class DeployController < OpsChain::Dsl::BaseController
desc 'Deploy the app', step_name: 'Deployment', ignore_failure: true, timeout: 600
def deploy
...
end
end
resource_type :app do
# deploy is described as 'deploy', with no step name, ignore_failure false and no timeout
controller DeployController, available_actions: [:deploy]
end
Leave available_actions: off to keep what the controller declares, or restate the description and options in the entry. Narrowing the actions on a resource behaves differently: it reconciles with what the controller declared instead of replacing it.
Supplying available_actions: does not remove the controller's other actions. An action the controller reports through resource_type_actions but available_actions: leaves out is still defined and can still be run; it has no description, so it is hidden from opschain-action --tasks and from the GUI.
This matters most for a base controller, where the action list is derived rather than written out: every public no-argument method is an action whether or not available_actions: mentions it. To make sure a method is not an action at all, keep it private or name it in not_actions.
Overriding controller actions on a resource
When a resource type defines a controller with available_actions:, each resource created from that type will expose all of those controller actions by default. The available_actions DSL method can be called within a resource definition to override which controller actions are visible for that specific resource, and optionally change their descriptions.
resource_type :server do
controller ServerController, available_actions: {
deploy: 'Deploy the server',
restart: 'Restart the server',
shutdown: 'Shutdown the server'
}
property :hostname
end
server :production do
hostname 'prod-server'
# Only expose deploy and restart for the production server
available_actions(
deploy: 'Deploy the production server',
restart: 'Restart the production server'
)
end
server :staging do
hostname 'staging-server'
# No override — all three actions (deploy, restart, shutdown) remain available
end
The available_actions method accepts arguments in the same formats as the available_actions: kwarg on controller (see available actions):
- A symbol or string:
available_actions :deploy, :restart - A key-value hash of name → description:
available_actions(deploy: 'Deploy the server', restart: 'Restart the server') - An array of hashes with a
name:key (supportsdescription:,step_name:,ignore_failure:,reload_actions:andtimeout:):available_actions({ name: :deploy, description: 'Deploy the server', step_name: 'Run deployment' }) - Any mixture of the above formats
Calling available_actions on a resource replaces the set of visible controller actions for that resource. In the example above, production exposes only deploy and restart, even though the resource type also defines shutdown.
Narrowing the actions on a resource does not discard the options a base controller's desc declarations supply — an entry overrides only the options it states. The description behaves differently: naming an action on its own keeps the description the controller declared, but a hash entry supplies the description of the action it names, so an entry carrying no description: leaves that action without one — and so hidden from opschain-action --tasks and the GUI — exactly as an explicit description: nil would.
Taking the DeployController above, whose deploy is declared desc 'Deploy the app', step_name: 'Deployment', ignore_failure: true, timeout: 600:
| On the resource | Description | step_name: | ignore_failure: | timeout: |
|---|---|---|---|---|
available_actions :deploy | Deploy the app | Deployment | true | 600 |
available_actions({ name: :deploy, description: 'Deploy production' }) | Deploy production | Deployment | true | 600 |
available_actions({ name: :deploy, ignore_failure: false }) | none | Deployment | false | 600 |
available_actions({ name: :deploy, description: 'Deploy production', timeout: 1200 }) | Deploy production | Deployment | true | 1200 |
To change one option for a single resource without listing the actions it can run, and without taking their descriptions away, use ignore_failures or reload_actions instead. Those mark an action in place, leaving its description and its other options as they were. There is no such method for timeout, so change an action's timeout on a resource with a timeout: key in its available_actions entry.
Ignoring controller action failures on a resource
The ignore_failures DSL method can be called within a resource definition to mark specific controller actions as non-fatal. When one of those actions raises an exception, MintPress logs a warning and continues the change rather than marking the step as failed. The step finishes in the warning state.
server :staging do
hostname 'staging-server'
available_actions(
deploy: 'Deploy the staging server',
restart: 'Restart the staging server'
)
# If restart fails on staging, log a warning but continue the change
ignore_failures :restart
end
Multiple actions can be marked at once: ignore_failures :restart, :shutdown.
ignore_failures can only reference actions that are present in available_actions. If the specified action name does not exist in the resource's available actions, MintPress will raise an error.
ignore_failure can also be specified inline within an available_actions entry, avoiding a separate ignore_failures call:
server :staging do
hostname 'staging-server'
available_actions(
:deploy,
{ name: :restart, description: 'Restart the staging server', ignore_failure: true }
)
end
This is equivalent to the previous example.
Reloading actions.rb for a controller action on a resource
The reload_actions DSL method can be called within a resource definition to make specific controller actions read actions.rb again before they run.
server :staging do
hostname 'staging-server'
available_actions(
deploy: 'Deploy the staging server',
restart: 'Restart the staging server'
)
# Read actions.rb again before restart runs, so its top level sees what deploy produced
reload_actions :restart
end
Multiple actions can be marked at once: reload_actions :restart, :shutdown. As with ignore_failures, the action must be present in available_actions, and the option can be specified inline in an available_actions entry instead:
server :staging do
hostname 'staging-server'
available_actions(
:deploy,
{ name: :restart, description: 'Restart the staging server', reload_actions: true }
)
end
Defining resource type actions
Any combination of controller actions and locally defined actions can be used within a resource or resource type.
resource_type :city do
controller CityController
action :send_postcard do
puts "Sending postcard from #{name}"
end
end
Using this city resource type, resources will include the report_weather and send_postcard actions.
If you define a resource type action with the same name as a controller action_method, MintPress will run the controller action, then the resource_type action.
Accessing the controller
If a controller class was configured with the controller keyword on the resource type, the actions on the resource or resource type can reference the supporting controller instance to invoke methods.
resource_type :city do
controller CityController
action :send_postcard do |action|
action.controller.buy_stamp # this method doesn't actually exist in our example, it is just for illustration
puts "Sending postcard from #{name}"
end
end
The send_postcard action defined on the city resource type will invoke the controller's buy_stamp method. This method needs to be public, and could optionally be exposed as an action by the controller - but it does not need to be.
Using namespaces to separate resources and actions
You can nest namespaces to organise your resources. Namespaces also allow the same resource name to be used multiple times. You can open the same namespace multiple times and the results will be combined:
namespace :earth do
namespace :australia do
city :perth do
name 'Perth'
weather 'sunny'
end
end
namespace :scotland do
city :perth do
name 'Perth'
weather 'gloomy'
end
end
end
namespace :earth do
namespace :australia do
city :sydney do
name 'Sydney'
weather 'nice'
end
end
end
This would define the following actions:
earth:australia:perth:report_weatherearth:australia:perth:send_postcardearth:australia:sydney:report_weatherearth:australia:sydney:send_postcardearth:scotland:perth:report_weatherearth:scotland:perth:send_postcard
Referencing resources
Assigning resources to properties
Previously defined resources (in the same actions.rb or files required previously) can be referenced by name when setting properties in other resources.
namespace :australia do
city :sydney do
name 'Sydney'
end
namespace :victoria do
city :melbourne do
name 'Melbourne'
# MintPress will search for the 'sydney' resource in the current namespace, then in
# each parent namespace until the resource is found.
rival sydney
end
end
end
If the property value being assigned (in this case the sydney resource) is another resource (technically, if it responds to the controller method), the property will be assigned the result of the controller method. Note: if the controller method returns nil, the property will be nil.
Accessing resource properties
The resource properties from previously defined resources can be referenced when setting properties in subsequent resources by using the properties keyword:
namespace :australia do
city :sydney do
name 'Sydney'
end
namespace :victoria do
city :melbourne do
name 'Melbourne'
rival "#{name}'s biggest rival is #{sydney.properties.name}."
end
end
end
The ref (or resource) method
As shown in the previous examples, referencing a resource by name is often sufficient to resolve it. However, when the required resource is defined in an alternate namespace, or where resources with the same name exist, the ref method can be used to more explicitly specify the required resource:
namespace :australia do
city :capital do
name 'Canberra'
end
namespace :victoria do
city :capital do
name 'Melbourne'
end
end
namespace :new_south_wales do
city :capital do
name 'Sydney'
end
namespace :hunter_valley do
city :newcastle do
state_capital capital
country_capital ref('^australia:capital')
victorian_capital ref('victoria:capital') # or ref('^australia:victoria:capital')
end
end
end
end
The properties associated with newcastle highlight the various ways to access other resources in the actions.rb.
-state_capital uses the default "by name" feature of the DSL causing the following search sequence:
australia:new_south_wales:hunter_valley:capitalaustralia:new_south_wales:capital
-country_capital prefixes the resource path with the ^ symbol to instruct ref to start its search in the root namespace:
australia:capital
-victorian_capital includes a namespace in the resource path, causing the following search sequence:
australia:new_south_wales:hunter_valley:victoria:capitalaustralia:new_south_wales:victoria:capitalaustralia:victoria:capital
It also includes an alternative path, using the ^ prefix to request the Victorian capital directly.
The ref name is also available as resource to make it more explicit. E.g. country_capital resource('^australia:capital').
Using resources in actions
Before executing a resource action, MintPress parses the entire actions.rb file. For this reason, resource actions can refer to any resource in the actions.rb or the files it requires. In the example below, the state_capital action refers to the melbourne resource, even though its definition appears after it in the file.
namespace :victoria do
city :bacchus_marsh do
name 'Bacchus Marsh'
action :state_capital do
puts "The capital of Victoria is #{melbourne.properties.name}."
melbourne.controller.report_weather
end
end
city :melbourne do
name 'Melbourne'
end
end
The state_capital action uses:
- the
propertieskeyword to incorporate the value of themelbourneresource'snameproperty in the message - the
controllerkeyword to call thereport_weathermethod onmelbourne's controller
Within an action block, MintPress does not allow calling other resource's actions directly (e.g. melbourne.send_postcard can not be used from the state_capital action above). If the state_capital action is required from other resources, it should be moved to a method in the resource type's controller, making it accessible via the controller keyword.
To handle the case where variables are used to define resource names, MintPress resolves the controller or properties on a string (or symbol) variable that matches the name of a resource. For example the following code would work:
capital = 'melbourne' # or :melbourne
namespace :victoria do
action :state_capital do
puts "The capital of Victoria is #{capital.properties.name}."
capital.controller.report_weather
end
city capital do
name 'Melbourne'
weather 'good'
end
end
Note: The only fields that are looked up automatically are controller and properties.
Setting multiple properties
Multiple resource properties can be assigned values in a single step by taking advantage of the OpsChain properties feature. Assuming the OpsChain properties JSON was set to:
{
"melbourne_resource": {
"name": "Melbourne",
"weather": "cold"
}
}
The melbourne city resource could be created as follows:
city :melbourne do
properties OpsChain.properties.melbourne_resource
end
If the dynamic nature of OpsChain properties is not required, you can directly supply a hash containing the property values, keyed with their property names.
city :melbourne do
properties({ name: 'Melbourne', weather: 'cold' })
end
If the properties are expensive to compute, they can be provided with the lazy keyword.
city :melbourne do
properties(lazy do
YAML.safe_load(Net::HTTP.get(URI.parse('http://some-server:8000/config.yaml')))
end)
end
Property setting override behaviour
Any combination of individually set properties and calls to properties can be used to construct the final set of values used to construct the resource's controller. The set of properties used will follow this behaviour:
- successive calls to
propertieswill deep merge into any previously set via that method - individually set properties will override any set via
properties - successive calls to set an individual property will override any previous values set
first_props = {
name: {
a: 'complex value'
},
weather: {
temp: 'a bit cold',
wind: 'a bit'
}
}
second_props = {
weather: {
temp: 'ok'
}
}
city :melbourne do
name 'coffee capital'
name 'Melbs'
properties first_props
properties second_props
end
The example above would result in the creation of a controller with these properties:
{
name: 'Melbs',
weather: {
temp: 'ok',
wind: 'a bit'
}
}
Defining resource actions
In addition to controller actions and resource type actions, you can also define actions specific to an individual resource:
city :melbourne do
name 'Melbourne'
action :welcome do |action|
puts "Welcome to #{action.controller.name}"
end
end
These actions can have prerequisites and initiate subsequent steps like normal actions:
city :melbourne do
name 'Melbourne'
action :get_coffee do
puts 'getting coffee'
end
action :see_music do
puts 'seeing music'
end
action :visit, steps: ['get_coffee', 'see_music']
end
Any actions defined within a resource will run after controller and resource type actions with the same name. The following code can be used to demonstrate:
class CityController
... # omitted for simplicity
def report_weather
puts "The controller weather in #{name} looks #{weather}"
end
end
resource_type :city do
controller CityController, available_actions: [:report_weather]
action :report_weather do
puts "The resource_type weather in #{name} looks #{weather}"
end
end
city :melbourne do
name 'Melbourne'
weather 'perfect'
action :report_weather do
puts "The resource weather in #{name} looks #{weather}"
end
end
This example will output the controller weather, then the resource_type weather, then the resource weather. The name and weather properties will be the same in all three messages.
The following code creates a database resource type with three actions: copy_installer, install_and_startup and startup. (database_controller is a hypothetical file containing a DatabaseController class.)
require 'database_controller'
resource_type :database do
controller DatabaseController, available_actions: [:copy_installer, :startup]
property :host
property :source_path
action install_and_startup: [:copy_installer], steps: [:startup] do |action|
action.controller.install
end
end
The install_and_startup action will:
- in the current step runner, execute the
copy_installerpre-requisite action (to execute thecopy_installercontroller method) - in the current step runner, execute the
installcontroller method (manually called from within the action body) - request the
startupaction be run as a child step (to execute thestartupcontroller method) - this child step will be started after the contents of this step complete and will be run in a new step runner
Defining composite resources & resource types
You can define a composite resource that manages child resources.
childrenspecifies the children to be iterated over, it is supplied when creating a resource. It is either a hash whose keys, the child names, are strings or symbols, or a list, of hashes that each have anameor of names. A hash item is that child's properties,nameincluded, and a name on its own gives the child empty properties. A list keeps its order, and each name must be distinct. Anything else, such as a hash with numbers as keys or a list item without aname, fails with an error naming the resource.each_childdefines a namespace for each child and defines a copy of any configured actions and resources in that namespacechild_actions('<resource type>:<action>')returns that action of every child resource of the given type, for use as steps. Use the child resource's type (teambelow), not its name (local_team). Addaction_regexp:to keep only the child actions whose full name matches, e.g.child_actions('team:barrack', action_regexp: /richmond/). This is useful for actions defined at the parent composite resource (or resource type) level that run these child actions as steps
These can be used in a resource definition to create child resources specific to that resource. More commonly, they can be used in a resource type definition to create child resources for each resource of this type.
suburb_properties = {
richmond: {
football_team: 'tigers'
},
collingwood: {
football_team: 'magpies'
}
}
resource_type :team
resource_type :city do
property :country
each_child do |suburb, properties|
team :local_team do
properties properties
action :barrack do
puts "Go #{suburb} #{properties[:football_team]} - the best team in #{country}!"
end
end
end
action :barrack_all, steps: child_actions('team:barrack')
end
city :melbourne do
country 'Australia'
children suburb_properties
end
This would define the following actions:
melbourne:richmond:local_team:barrackmelbourne:collingwood:local_team:barrackmelbourne:barrack_all- this will call thebarrackaction of eachteamresource in thecitycomposite's children (richmondandcollingwood).
- Each team's
barrackaction makes use of thecountryproperty defined on the parentcitycomposite resource type actionscan't be created directly inside theeach_childblock, and instead must be on a resource- A composite whose
childrenis empty defines no child resources, and itschild_actionssteps run nothing
OpsChain exec_command
MintPress's DSL provides an exec_command method to execute shell commands with fine-grained control over environment variables, output streaming, error handling and logging. This is particularly useful for running scripts, system commands or external tools that are not available in the default runner image.
exec_command is available wherever the other OpsChain keywords are, including inside a base controller — with the exception of a resource definition, which deliberately does not have it. A class that does not inherit from the base controller — or include ControllerKeywords — reaches it through its full path, OpsChain::Dsl::ExecCommand.execute.
Command arguments
The command you want to execute can be passed in two ways:
Multiple arguments (recommended for programmatic use) — each argument is passed to the command exactly as supplied, so a value containing spaces or quotes needs no escaping:
exec_command('docker', 'run', '-it', 'ubuntu', 'bash')
exec_command('git', 'commit', '-m', "Release #{version}, built from #{branch}")
Single string — parsed into separate arguments, keeping quoted text together:
exec_command('docker run -it ubuntu bash')
# These are equivalent:
exec_command('echo', 'hello world', 'quoted text')
exec_command('echo "hello world" "quoted text"')
Quotes are removed wherever they appear in an argument, as a shell removes them, so exec_command('./run.sh --name="my table"') passes --name=my table to the command.
Only a command supplied as a single string is parsed. To build a command from a string of options held elsewhere, split it yourself — exec_command('./run.sh', *options.shellsplit).
A single string containing ${ is run through a shell exactly as written, so the variable is expanded and the string's quoting is kept. When the command is supplied as multiple arguments, ${ is passed to the command literally.
A single string with an unmatched quote, such as "echo it's fine", raises an error rather than running a different command. Close the quote, or pass the command and its arguments as separate strings. A blank command raises exec_command was given no command to run.
The command's standard input is closed, so a command that prompts for input, such as terraform apply without -auto-approve, reads the end of its input instead of waiting for an answer that never comes. Pass the command the option that answers its prompt.
Keyword Arguments
env: (Hash, default: {})
Set environment variables for the command you want to execute.
exec_command('printenv', 'MY_VAR', 'ANOTHER_VAR', env: { MY_VAR: 'hello', ANOTHER_VAR: 'world' })
The environment variables provided in the opschain.env section of the properties are already decrypted and ready for use for all the commands run via exec_command.
options: (Hash, default: {})
Pass options to Open3.popen3, such as changing the working directory before executing the command.
exec_command('pwd', options: { chdir: '/tmp' })
log_command: (Boolean, default: true)
Whether to log the command being executed to the change logs.
# Default, will add a log line with the command `pwd` to the change logs
exec_command('pwd')
# Suppress the command from being logged to the change logs
exec_command('pwd', log_command: false)
live_stream: (Boolean, default: true)
Whether to log stdout output in real-time as the command runs.
# Stream output to the logger as it happens
exec_command('long-running-command', live_stream: true)
# Suppress live output (still captured in the returned result.stdout)
result = exec_command('curl https://example.com', live_stream: false)
logger: (Logger-like object, default: OpsChain.logger or $stdout)
Specify a custom logger. The logger should respond to .info() and .debug() methods (or .puts() as fallback):
# This is just an example, this class does not actually exist
require 'custom-logger'
custom_logger = CustomLogger.new('command.log')
exec_command('rake test', logger: custom_logger)
The logs shown for a change are any lines emitted to the runner's STDOUT and STDERR. If your custom logger sends the output elsewhere, these will not be shown in the change logs.
abort_on_failure: (Boolean, default: true)
Whether to raise a RuntimeError if the command fails (non-zero exit code):
# Raises RuntimeError if command fails (default)
exec_command('fake_command', abort_on_failure: true)
# Returns result with failed? == true, no exception
result = exec_command('fake_command', abort_on_failure: false)
puts result.failed? # => true
Output
The exec_command method returns a CommandResult object with:
stdout- String containing all stdout outputstderr- String containing all stderr outputstatus- aProcess::Statusobject with exit information. See the Process::Status documentation for more details.success?/succeeded?- Returnstrueif exit code is 0failed?- Returnstrueif exit code is non-zeroexitstatus- Integer exit codepid- Process ID- Other methods delegated to the status object:
coredump?,stopped?,stopsig
Error handling
When a command fails (non-zero exit code) and abort_on_failure is true (default):
- a
RuntimeErroris raised with a message like:Command "fake_command" failed with exit status 1 - if
live_streamistrue, stderr is logged before raising the error. - if
live_streamisfalse, stderr is logged only when the command fails - the step will be marked as failed if the exception is uncaught
When abort_on_failure is false:
- No exception is raised
- Check
result.failed?orresult.success?to determine the outcome of the command - Access
result.stderrto see the error messages
OpsChain logger
MintPress provides a logger for use in your actions. The OpsChain logger is based on the standard Ruby Logger object. By default, the logger is configured to log all INFO severity (and higher) messages to STDOUT. You can use the OpsChain logger from anywhere in your actions.rb or project code:
log.info 'Informational message'
log.warn 'Warning message'
log.error 'Error message'
log.fatal 'Fatal message'
If required, the logger can be set to also display DEBUG level messages as follows:
log.level = ::Logger::DEBUG
log.debug 'Debug message'
log is available at the top level of your actions.rb, within the action and resource_type blocks you define there, and inside a base controller. If you'd like to alias the log object to something else — or you are writing a class that is not a base controller — you can refer to the OpsChain logger using the full path to it, for example:
OpsChain.logger.info 'Informational message'
The OpsChain logger supports the following log levels:
DEBUGINFOWARNERRORFATAL
Each log level is more severe than the last, so DEBUG is the least severe and FATAL is the most severe.
Set the log level for a change
The OPSCHAIN_LOG_LEVEL environment variable sets the level the OpsChain logger starts at. Set it to debug, info, warn, error or fatal, in either case. The level is info when the variable is not set or holds any other value.
Set it under opschain.env, as you would any other environment variable:
{
"opschain": {
"env": {
"OPSCHAIN_LOG_LEVEL": "debug"
}
}
}
Where you set it decides which changes it applies to:
- In the properties of a project, environment or asset, it applies to every change run against that node and the nodes below it.
- In a change's property overrides, it applies to that change alone. Use the GUI's Environment variables panel, or the CLI's
--property-overridesflag:
mintpress changes create \
-E dev \
-A web_server \
-a deploy \
--property-overrides '{"opschain":{"env":{"OPSCHAIN_LOG_LEVEL":"debug"}}}'
Setting log.level in your actions.rb replaces the starting level for the rest of the step.
Show where each log line came from
Set the OPSCHAIN_LOG_SOURCE environment variable to true to prefix each line written by the OpsChain logger with the action that was running and the method that wrote it:
[deploy_app | actions.rb:45] Starting the deployment
[web:deploy | DeployController#deploy] Deploying web-01
[web:deploy | AuditTrail#record] Recorded the deployment of web-01
Set it in the same places as OPSCHAIN_LOG_LEVEL: in a project, environment or asset's properties, or in a change's property overrides to turn it on for one change. It is off by default. true, yes or 1, in any case, turn it on; any other value leaves it off.
mintpress changes create \
-E dev \
-A web_server \
-a deploy \
--property-overrides '{"opschain":{"env":{"OPSCHAIN_LOG_SOURCE":"true"}}}'
The prefix takes these forms:
[web:deploy | DeployController#deploy]- logged in an instance method, in youractions.rbor project code.[web:deploy | AuditTrail.record]- logged in a class or module method.[deploy_app | actions.rb:45]- logged directly in an action block, or in a block outside any method. The prefix names the file and line.[actions.rb:8]- logged at the top level ofactions.rbwhile it loads, outside any action.[web:deploy]- logged by code outside your repository, such as a gem or code invendor/.
A line logged inside a block or a child thread is credited to the method the block is written in. If you pass a program name to the logger, it replaces the method part of the prefix:
log.info('audit') { 'Recorded the deployment' } # [web:deploy | audit] Recorded the deployment
Only the OpsChain logger's lines are prefixed. Output from puts and from commands your actions run appears as it is.
Trace the methods an action calls
When OPSCHAIN_LOG_SOURCE is true and OPSCHAIN_LOG_LEVEL is debug, MintPress also logs a line each time an action enters and leaves one of your methods:
[web:deploy | DeployController#deploy] --> ENTER
[web:deploy | DeployController#deploy] Deploying web-01
[web:deploy | AuditTrail#record] --> ENTER
[web:deploy | AuditTrail#record] Recorded the deployment of web-01
[web:deploy | AuditTrail#record] <-- EXIT
[web:deploy | DeployController#deploy] <-- EXIT
Only methods defined in your repository are traced. Methods in MintPress, in gems and in vendor/ are not, and neither is initialize, so creating an object adds no lines. Tracing starts when an action begins, so the methods actions.rb calls while it loads are not traced, nor are methods run in a thread the action starts.
Every method call adds two lines, so a traced change's log can grow large. Turn tracing on for a single change with its property overrides rather than for a whole project or environment:
mintpress changes create \
-E dev \
-A web_server \
-a deploy \
--property-overrides '{"opschain":{"env":{"OPSCHAIN_LOG_LEVEL":"debug","OPSCHAIN_LOG_SOURCE":"true"}}}'
OpsChain secret vault
MintPress allows you to interact with a secret vault to securely manage sensitive information. The secret vault is accessible from within your actions via MintPress's secret_vault property (OpsChain.secret_vault). Inside a base controller or a resource definition it is reached as secret_vault, without the prefix.
A change holds no secret vault credentials of its own. Each OpsChain.secret_vault call is sent to the OpsChain API, which reads or writes the vault on the change's behalf, so every call is one round trip to the API. If the API is restarting when a call is made, for example during an upgrade, the call is retried for up to about two and a half minutes. The API uses the vault settings the change started with, and limits the change to them. MintPress assumes nothing between the change's pods and the OpsChain API, such as an HTTP proxy or a service mesh sidecar, inspects or rewrites these requests.
The API supports get, get_password, remove and remove_path. Any other secret vault method fails with SecretVault#<method> is not available through the OpsChain API secret vault proxy - only get, get_password, remove and remove_path are supported there.
When you develop actions locally with OPSCHAIN_VAULT_ADDRESS set, the calls go straight to that vault instead, using the vault settings you supply.
OpsChain.secret_vault.get
The get method allows you to generate, store and retrieve secrets from the secret vault. In its simplest form the get method requires two arguments:
- the path where the secret is (to be) stored.
- the key the secret is stored under in this path.
E.g.
The following example shows a terraform resource being defined. The result of the secret vault get request is being assigned to the resource's password variable.
terraform_config :terraform do
vars(
namespace: 'opschain-terraform',
external_port: 8080
password: OpsChain.secret_vault.get('vault/path/to/secrets', 'secret_key')
)
end
In this form, if a secret has been stored in the vault for this path and key combination it will be returned. If no secret exists for this path and key combination then a new secret will be generated, stored in the vault, and then returned.
Customising the secret get
The following keyword arguments can be supplied to customise the get request:
| Argument | Default value | Description |
|---|---|---|
auto_create: | true | whether to automatically create the secret if it does not exist in the vault |
default: | nil | The default value to assign to the secret if one does not exist or override is true |
include_chars: | true | whether to include alphabetic characters in the generated secret value |
include_numbers: | true | whether to include numeric characters in the generated secret value |
include_symbols: | true | whether to include special characters in the generated secret value |
length: | 14 | the number of characters to generate for the secret value |
must_start_with_char: | true | whether the generated secret value must start with an alphabetic character |
override: | false | whether to overwrite the secret value if it already exists in the secret vault |
symbols: | '-#_^$%*' | the special characters to include in the secret value |
decrypt_vault_value: | false | whether to decrypt the secret value when fetching it. This is only applicable when using double encryption. |
For example: OpsChain.secret_vault.get('vault/path/to/secrets', 'secret_key', length: 20, include_numbers: false). If the secret does not exist, a new 20 character long secret will be generated that does not include any numeric characters. If the secret already exists, these keyword arguments will be ignored and the existing secret returned.
With auto_create: false, a secret that does not exist, or that holds an empty value, is returned as the default: value when one is given. Without a default:, the call fails with the secret vault has no value for the key <key> in <path> - the key does not exist and auto_create is false, or it holds an empty value. A default: value is stored in the vault when the secret does not exist, so later calls return it.
OpsChain.secret_vault.get_password
get_password works like get, but takes the default value as an optional third argument rather than as default::
OpsChain.secret_vault.get_password('vault/path/to/secrets', 'secret_key', 'initial-value', length: 20)
The other keyword arguments are the same as for get.
OpsChain.secret_vault.remove
The remove method allows you to remove a secret from the secret vault. It requires two arguments:
- the path where the secret is stored.
- the key the secret is stored under in this path.
The example remove_secret action below will remove a secret from the secret vault:
action :remove_secret do
OpsChain.secret_vault.remove('vault/path/to/secrets', 'secret_key')
end
OpsChain.secret_vault.remove_path
The remove_path method allows you to remove a path and all of its children from the secret vault.
The example cleanup_vault action below will remove the vault/path/to/secrets path (including all secrets and child paths) from the secret vault:
action :cleanup_vault do
OpsChain.secret_vault.remove_path('vault/path/to/secrets')
end
Care should be taken using the remove_path method as there is no way to undo the path removal other than to recover from vault backup or manually recreate the paths and contents.
remove_path refuses to remove the root of the vault: remove_path('') and remove_path('/') fail with cannot remove the root of the secret vault. For every secret vault method, a path with an empty, . or .. segment is rejected, so a path cannot reach outside the vault's mount. One leading and one trailing / are ignored.
Querying the API
Action code can read live data from the OpsChain API server while a change is running using the query keyword. This is useful when an action needs information about another node — for example the properties of a related environment, the converged settings of an asset, or the MintModel generated for an asset.
query(endpoint_type, **kwargs)
The first argument is the type of resource to query and the keyword arguments identify the node (or template version) to query. The supported endpoint types are:
| Endpoint type | Required arguments | Optional arguments | Returns |
|---|---|---|---|
:node | project | environment, asset, agent, list | The project, environment, asset, or agent resource, including its id, type, and attributes — or, when list is supplied, an array of the child node resources. |
:mintmodel | project, asset | environment | The data of the asset's MintModel. |
:properties | one of the node combinations below | The converged properties document for the node (or template version). | |
:settings | one of the node combinations below | The converged settings document for the node (or template version). |
Like the other OpsChain keywords, query is available at the top level of your actions.rb and resources.rb files, within the action and resource_type blocks you define there, and inside a base controller. Code in a class that does not inherit from the base controller — or include ControllerKeywords — must use the full path to it, OpsChain.query. The two are equivalent.
Every argument that identifies a node must be supplied with a value. Passing nil — environment: OpsChain.environment_code in a project level change, for example — raises an error rather than querying the parent node.
Authentication
query authenticates using a short-lived API key that MintPress injects into the step context. The key is supplied automatically and needs no configuration.
It inherits the permissions of the user that created the change, started the agent, or triggered the derivation of an asset's actions, so a query only succeeds for the nodes that user is authorised to view. Each key is revoked as soon as the change, agent or actions derivation that owns it finishes.
Querying while your actions are being discovered
MintPress loads your actions for two different reasons: to run a step, and to discover what your actions are without running any of them — when it derives an asset's actions from its template version, or builds a change's step tree.
A query made while your actions are being discovered is skipped by default. It returns an empty result — {} for a :node, :mintmodel, :properties or :settings query, and [] for a list query — so the surrounding code has something of the expected shape to work with, and MintPress logs a warning naming the actions.rb line that made the call, the arguments it was given, and what was returned in its place.
Skipping it avoids issuing a request for data that discovery has no intention of using, and avoids failing discovery for a reason that has nothing to do with the actions being discovered. Supply run_in_dry_run: true when the answer shapes the actions or the step tree, and the query runs at this point as well:
query(:node, project: 'demo', list: :environments, run_in_dry_run: true).each do |environment|
action :"deploy_#{environment.dig(:attributes, :code)}" do
OpsChain.logger.info("Deploying #{environment.dig(:attributes, :code)}")
end
end
The arguments are validated whether or not the query runs, so a malformed query is reported while your actions are being discovered rather than only when a step runs.
Querying a node
Supplying the :node endpoint type returns the requested node's resource. Provide just the project to query a project, add an environment and/or asset to query nested nodes:
action :show_environment do
environment = query(:node, project: 'demo', environment: 'dev')
OpsChain.logger.info("Environment name: #{environment[:attributes][:name]}")
end
The arguments supplied must identify a node in the project's node hierarchy, so they must form one of the following combinations:
projectproject,environmentproject,assetproject,environment,assetproject,agent
Any other combination raises an error — supplying an agent alongside an environment, for example, as agents belong directly to a project.
Listing child nodes
Adding the list argument returns every child node of the requested type rather than a single node. This lets action code discover the nodes that exist rather than hard coding their codes:
action :show_environments do
environments = query(:node, project: 'demo', list: :environments)
codes = environments.map { |environment| environment.dig(:attributes, :code) }
OpsChain.logger.info("Environment codes: #{codes.join(', ')}")
end
The list argument accepts :environments, :assets, or :agents, and the arguments supplied alongside it must identify the parent node:
| Arguments | Returns |
|---|---|
project, list: :environments | Every environment in the project. |
project, list: :assets | Every asset that belongs directly to the project. |
project, environment, list: :assets | Every asset in the environment. |
project, list: :agents | Every agent in the project. |
Any other combination raises an error — supplying an environment alongside list: :environments, for example.
Each element of the returned array is a node resource with its own id, type, and attributes, in the same form as the single node query returns. A parent with no children of that type returns an empty array.
project with list: :assets returns only the assets that belong directly to the project. Assets that belong to an environment are returned by supplying that environment as well.
Querying properties and settings
The :properties and :settings endpoint types return the fully converged document for a node, with all inherited values resolved exactly as they would be when running a change against that node.
action :read_related_properties do
properties = query(:properties, project: 'demo', environment: 'dev', asset: 'wls')
database_host = properties.dig(:database, :host)
settings = query(:settings, project: 'demo', environment: 'dev')
OpsChain.logger.info("pod_per_change_step: #{settings[:pod_per_change_step]}")
end
A :settings query includes the settings the node inherits from the global settings, so your action sees the value it runs with even when no project, environment or asset overrides it. Of those inherited values, only the documented settings that can be set on a project or below are returned, and anything secret is left out, such as passwords, tokens and encrypted values. A setting that is overridden below the global level is returned as the node has it.
To get only the settings overridden below the global level, supply include_global: false in query_args:
action :show_overridden_settings do
overrides = query(:settings, project: 'demo', environment: 'dev', query_args: { include_global: false })
OpsChain.logger.info("Overridden settings: #{overrides.keys.join(', ')}")
end
Node argument combinations
The :properties and :settings endpoint types accept any one of the following keyword argument combinations:
projectproject,agentproject,assetproject,environmentproject,environment,assetproject,template,version
When template and version are supplied, MintPress looks up the named template within the project to resolve it and returns the converged document for that template version:
action :read_template_properties do
properties = query(:properties, project: 'demo', template: 'web', version: '1.0.0')
end
Querying a MintModel
The :mintmodel endpoint type returns the data of the MintModel generated for an asset. The project and asset are required, and an environment can be supplied to query the asset within a specific environment:
action :read_mintmodel do
mintmodel = query(:mintmodel, project: 'demo', environment: 'dev', asset: 'wls')
OpsChain.logger.info("MintModel region: #{mintmodel[:region]}")
end
Error handling
query raises an ArgumentError when the supplied keyword arguments do not form a valid combination for the endpoint type (for example a missing required argument, an unexpected argument, or an incomplete :properties/:settings combination).
If the request reaches the API server but no matching record is found, or the API request itself fails (for example a network error or an authentication failure), an OpsChain::Core::Api::Request::Error is raised. The response code and body are written to the change logs to help with troubleshooting.
By default query connects to the OpsChain API server at http://opschain-api:3000. This can be overridden with the OPSCHAIN_API_URL environment variable, though the default is correct for actions running inside the MintPress cluster.
Sending email
Action code can send an email while a change or agent is running using the send_email keyword. This is useful when an action needs to reach someone outside the people who have subscribed to notifications — for example emailing a generated report to a distribution list, or telling a downstream team that an environment is ready for them.
send_email(subject:, body:, to:, cc:, bcc:, from:, content_type:, attachments:)
The email is sent using the server settings of the default email channel, so an administrator must have configured one — and left it enabled — before actions can send email. Like query, send_email authenticates with the short-lived API key MintPress injects into the step context, is available wherever the other OpsChain keywords are — including inside a base controller, but excluding a resource definition, which deliberately does not have it — and can be reached from a class that is not one using its full path, OpsChain.send_email. Only the step context's key can send email this way; a personal API key cannot.
| Argument | Required | Description |
|---|---|---|
subject | yes | the subject line |
body | yes | the body of the email |
to, cc, bcc | at least one | the recipients — each accepts a single address or an array of addresses |
from | no | the sender address — defaults to the MintPress no-reply address |
content_type | no | text/plain (the default) or text/html |
attachments | no | the files to attach — see attaching files below |
from accepts any address. MintPress does not check that it belongs to your organisation, and the email is relayed by the default email channel whichever change or agent sent it. Where the sender address matters, restrict it at the SMTP server MintPress relays through rather than relying on action code to be well behaved.
When from is omitted, MintPress's own no-reply address is used. The from address configured on the default email channel applies to notifications only — it is not used for email sent from action code.
action :notify_release_team do
send_email(
subject: "#{OpsChain.context.parents.project.name} deploy complete",
body: 'The deploy action completed successfully.',
to: 'release-team@example.com',
cc: ['ops@example.com', 'audit@example.com']
)
end
Supplying content_type: 'text/html' sends the body as HTML rather than plain text:
action :notify_with_summary do
send_email(
subject: 'Nightly refresh summary',
body: '<h1>Nightly refresh</h1><p>All assets converged.</p>',
content_type: 'text/html',
to: 'ops@example.com'
)
end
send_email returns the details of the sent message — its from, to, cc, bcc, subject, attachment_filenames and sent_at:
action :notify_and_log do
email = send_email(subject: 'Deploy complete', body: 'Done.', to: 'ops@example.com')
OpsChain.logger.info("Notified #{email[:attributes][:to].join(', ')} at #{email[:attributes][:sent_at]}")
end
Linking to the change
The change_url and step_url keywords return links to the running change and step in the MintPress GUI — the same links that appear in notification emails. step_url opens the change's step tree at the running step. Both are built from the gui_base_url in the step context, and both return nil when the step is not running as part of a change, for example in an agent.
action :notify do
send_email(
subject: "Change #{OpsChain.context.change.id}",
body: "Change: #{change_url}\nStep: #{step_url}",
to: 'ops@example.com'
)
end
Like the other keywords, they can be reached from a class that is not an action using their full paths, OpsChain.change_url and OpsChain.step_url.
Attaching files
Each attachment is supplied as a hash with a filename and the file's content, and may optionally supply a content_type telling the recipient's mail client what sort of file it is. The content is supplied as read from disk — MintPress encodes it for transport, so there is no need to encode it yourself:
action :email_converged_properties do
send_email(
subject: 'Converged properties',
body: 'The converged properties are attached.',
to: 'ops@example.com',
attachments: [
{ filename: 'properties.json', content: File.read('properties.json'), content_type: 'application/json' },
{ filename: 'summary.csv', content: File.read('summary.csv') }
]
)
end
The combined size of all attachments on a single email must not exceed 5MB.
A filename cannot contain a path separator, a quote character or a control character. A message carrying such an attachment cannot be assembled into a form the recipient's mail client can read, so MintPress rejects the email rather than delivering a message with the attachment silently missing.
Handling failures
send_email raises an ArgumentError before contacting the API server when the supplied keyword arguments are incomplete or unrecognised — a missing subject or body, an unexpected argument, none of to, cc and bcc being supplied, an unsupported content_type, or an attachment that is missing its filename or content.
If the request reaches the API server but the email cannot be sent, an OpsChain::Core::Api::Request::Error is raised. The response code and body are written to the change logs to help with troubleshooting. The most common causes are no default email channel having been configured or enabled, attachments exceeding the size limit, an unusable attachment filename, and the SMTP server rejecting the message.
Audit trail
Every email sent from action code is recorded as an api:email:create event, attributed to the user who started the change or agent. The event captures the address the message was actually sent from, the recipients, the subject, and each attachment's filename and size. The message body and the attachment content are never recorded.
If the message cannot be delivered, an api:notification:error event records the same addresses and subject along with the reason the send failed, so an operator can tell which message was lost without needing the change logs.
Raising events
Action code can record its own event while a change or agent is running using the create_event keyword. Use it to mark a milestone other tools care about — a release reaching production, a backup finishing — so that event filters and subscribers can react to it, or so it shows in the events list alongside MintPress's own events.
create_event(type:, data:, source:)
| Argument | Required | Description |
|---|---|---|
type | yes | the event type, up to 75 characters — for example myapp:deploy:finished |
data | no | a hash of details to store with the event |
source | no | a hash naming the resource the event is about — for example { node_path: '/projects/web/environments/prod/assets/app' } — using the same <source>_id and <source>_path keys as the events API. Defaults to the running step |
action :deploy do
# ...
create_event(type: 'myapp:deploy:finished', data: { version: '1.2.3', target: 'production' })
end
action :patch do
# ...
create_event(type: 'patch_application:success', source: { node_path: '/projects/web/environments/prod/assets/app' }, data: { patch: '36912345' })
end
Without a source, the event is linked to the running step, or to nothing when the code is not running in a step. The event is attributed to the user who started the change or agent, and its data is stored exactly as supplied, even when a key such as change_id matches a source name. Like send_email, create_event authenticates with the short-lived API key MintPress injects into the step context, so it needs no authorisation rule on /events, but the user who started the change must be able to view the source. It is available wherever the other OpsChain keywords are, except a resource definition, and can be reached from a class that is not an action using its full path, OpsChain.create_event.
create_event returns the created event, so its ID is available as create_event(...)[:id].
An event raised by an action is processed like any other, so an event filter that matches it can start a change. If that change runs the same action, it raises the event again. Every event an action raises counts toward its change's place in that chain, whatever it is linked to, and MintPress stops delivering events to subscribers once the chain is more than 10 levels deep. Even so, raise events for meaningful milestones rather than for every log line.
create_event raises an ArgumentError before contacting the API server when type is missing, blank or not a string, data or source is not a hash, or an unexpected argument is supplied. If the API server rejects the event — for example because type is longer than 75 characters, the source does not exist or cannot be viewed, or the source uses a key that cannot link an event, such as asset_path (the error lists the keys that can) — an OpsChain::Core::Api::Request::Error is raised.
Running the MintPress CLI
Action code can run the MintPress CLI while a change or agent is running using the opschain_cli keyword. This is useful when an action needs to alter something in MintPress rather than just read from it — starting a change on another node, updating a node's properties, or creating an asset from a template version.
action :promote_to_staging do
opschain_cli('changes', 'create', '-P', 'demo', '-E', 'staging', '-A', 'store', '-a', 'deploy', '-w')
end
The arguments are passed to the opschain executable in the runner image exactly as supplied, so a value such as a description or a JSON document can contain spaces and quotes. Like exec_command, a single string is parsed into separate arguments, so opschain_cli('projects list') and opschain_cli('projects', 'list') are equivalent. opschain_cli accepts the same keyword arguments — env, options, log_command, live_stream, logger and abort_on_failure — and returns the same CommandResult.
Like the other OpsChain keywords, opschain_cli is available at the top level of your actions.rb and resources.rb files, within the action and resource_type blocks you define there, and inside a base controller. Code in a class that does not inherit from the base controller — or include ControllerKeywords — must use the full path to it, OpsChain::Dsl::CliCommand.execute. The two are equivalent.
Authenticating the CLI
opschain_cli gives the CLI the credentials and the server address it needs, so a runner requires no config file, profile or login step. It authenticates with the same short-lived API key as query, supplying it to the CLI as OPSCHAIN_TOKEN, and points the CLI at the OpsChain API server with OPSCHAIN_API_URL.
The key carries the permissions of the user who created the change or started the agent, and the CLI can use it to alter MintPress as well as read from it. Your project's action code therefore acts with that user's authority, so treat it as privileged automation: review what lands in the project's git repository, and be deliberate about the values you interpolate into a CLI argument.
A command supplied as a single string that contains ${ is run through a shell, so a property value holding shell syntax can change the command that is executed. Pass values you do not control as separate arguments, which are never interpreted by a shell.
Anything supplied in env takes precedence over both variables. Supplying your own OPSCHAIN_TOKEN — an API key token held in the secret vault, for example — runs the command as that token's owner instead of as the change's user.
Non-interactive commands only
A step has no terminal attached, so a subcommand that asks for confirmation never receives an answer and the step waits indefinitely. Pass --force to the subcommands that prompt, such as admin pods delete and tokens delete-all.
Using the command output
The CLI writes human-readable tables by default. Pass -o json when the action needs to work with the result, and read it from the returned result's stdout:
action :log_environment_codes do
result = opschain_cli('environments', 'list', '-P', 'demo', '-o', 'json', live_stream: false)
JSON.parse(result.stdout).each do |environment|
OpsChain.logger.info("Environment: #{environment.dig('attributes', 'code')}")
end
end
See output formats in the CLI guide for the formats available.
Running the CLI while your actions are being discovered
A command issued while your actions are being discovered rather than run is skipped by default. Nothing is executed, a successful result with empty output is returned, and MintPress logs a warning naming the actions.rb line that made the call and the arguments it was given.
Supply run_in_dry_run: true when the command's output shapes the actions or the step tree, and the CLI runs at this point as well. A command that alters MintPress is best left with the default, so that it only runs when the step does.
Error handling
opschain_cli raises an OpsChain::Dsl::CliCommand::Error when it cannot run the CLI at all:
- no API key is available — the keyword works only while a change or agent is running
- the runner image does not contain the MintPress CLI at
/usr/local/bin/opschain.
Once the CLI runs, failures behave as they do for exec_command. A non-zero exit status raises a RuntimeError and fails the step, unless abort_on_failure: false is supplied — in which case check result.failed? and result.stderr to determine the outcome.
What to do next
- Learn about the OpsChain step runner.