Question
Answer and Explanation
To get the exit code of Golang code executed within an Argo workflow, you need to understand how Argo handles container executions and how exit codes are propagated. Here’s a breakdown of how to achieve this:
1. Understanding Argo Workflow Steps:
Argo Workflows executes steps as containers. When a containerized process completes, it exits with an exit code. Argo captures this exit code. A zero exit code usually indicates success, while a non-zero code typically signifies a failure.
2. Accessing the Exit Code:
Argo automatically exposes the exit code of each step as an output parameter. You can access this exit code in subsequent steps or in the workflow's final status. The exit code is part of the status of the workflow step.
3. Using `status.exitCode` in Subsequent Steps:
If you need to use the exit code in another step, you can reference it in a parameter or in a condition. The key is to use {{steps.<step-name>.outputs.exitCode}}
where <step-name>
is the name of the step that executes your Golang code.
4. Example Workflow Definition:
Here is an example of an Argo workflow YAML definition, showcasing how to access the exit code:
apiVersion: argoproj.io/v1alpha1
kind: Workflow
metadata:
generateName: go-exit-code-example-
spec:
entrypoint: main
templates:
- name: main
steps:
- - name: run-go-code
template: go-code-template
- - name: check-exit-code
template: exit-code-check
- name: go-code-template
container:
image: alpine/git # or any image with go installed
command: ["sh", "-c"]
args: ["go run - << EOF
package main
import \"fmt\"
import \"os\"
func main() {
fmt.Println(\"Running GO code...\")
// exit with a specific code
os.Exit(2)
}
EOF"]
- name: exit-code-check
container:
image: alpine/git
command: ["sh", "-c"]
args: ["echo Exit code was {{steps.run-go-code.outputs.exitCode}}"]
5. Explanation of the YAML:
- The run-go-code
step executes a simple Golang program that exits with code 2. It uses an alpine/git image with go installed.
- The exit-code-check
step accesses the exit code of run-go-code
step via {{steps.run-go-code.outputs.exitCode}}
and echoes it.
6. Using `exitCode` in Conditions:
You can also use the exit code in the conditions to make decision within your workflow, like:
- name: conditional-step
template: some-template
when: "{{steps.run-go-code.outputs.exitCode}} == '0'"
This ensures that `some-template` will only be executed if the run-go-code
exits with 0 exit code.
7. Important Considerations:
- Ensure that your Golang program explicitly exits with a meaningful exit code by using `os.Exit(code)`.
- Remember to properly handle non-zero exit codes in your workflow logic, depending on your application's requirements.
By following these steps, you can effectively retrieve and use the exit code of your Golang program within an Argo Workflow, enabling better workflow control and error handling.