Skip to main content

ctx

The ctx value describes the situation a script runs in: its raw arguments, its source file, the parsed inputs of a custom command, the component in scope, and the lifecycle hook that triggered it. Every attribute is read-only.

Usage​

ctx.args # list of script arguments
ctx.script # source file, or None
ctx.flags # dictionary of parsed flags
ctx.arguments # dictionary of parsed named arguments
ctx.component # component handle, or None
ctx.hook # hook details, or None
ctx.operation # parent operation details, or None

Attributes​

ctx.args
The command-line arguments passed to a standalone script.
ctx.script
The path and directory of the script file, when the script was read from a file.
ctx.flags
The parsed flags of a custom command, or the flags a workflow supplies.
ctx.arguments
The parsed named arguments of a custom command.
ctx.component
The component a custom command or hook is scoped to.
ctx.hook
The name and event of the lifecycle hook that runs the script.
ctx.operation
The parent operation, such as terraform apply, and its outcome.

What each entry point provides​

The attributes always exist. What they hold depends on how the script started:

Entry pointctx.argsctx.scriptctx.flagsctx.argumentsctx.componentctx.hook, ctx.operation
Standalone scriptArguments after the script name or stdin marker (-)The script file, or None for stdinEmptyEmptyNoneNone
Custom commandEmptySet when the script comes from a local !includeParsed flagsParsed argumentsThe command's component when it declares component:, otherwise NoneNone
Workflow stepEmptySet when the script comes from a local !includeWorkflow flags, as stringsEmptyNoneNone
Lifecycle hookEmptySet when the script comes from a local !includeEmptyEmptyThe hook's component, or None for an aggregate hookThe hook and the parent operation

Steps inside parallel and matrix groups inherit the context of the step that contains them. A standalone program that declares its interface with cli.command receives its parsed inputs as the arguments of its entry function instead of through ctx.flags and ctx.arguments.

Examples​

Branch on the entry point​

if ctx.hook != None:
print("running as the {} hook".format(ctx.hook.event))
elif len(ctx.args) > 0:
print("standalone script with arguments:", ctx.args)
else:
print("workflow or custom command step")

Read inputs in a custom command​

replicas = int(ctx.flags["replicas"])
service = ctx.arguments["service"]
print("{}: {} replicas".format(service, replicas))