Question

How can I expose the exit code from a container in an Argo workflow?

Answer and Explanation

To expose the exit code of a container in an Argo workflow, you typically utilize Argo’s built-in features for capturing and handling container statuses. Argo provides a way to access the exit code through its status information. Here’s how you can achieve this:

1. Using `containerStatus.exitCode` in Templates:

- In your Argo workflow template, you can access the exit code of a container using the expression ``. This expression becomes available after the container has completed execution.

2. Accessing Exit Code in a Script Template (Example):

- If you are using a script template, you can reference the exit code within the script logic. For instance:

apiVersion: argoproj.io/v1alpha1
kind: Workflow
metadata:
  generateName: exit-code-example-
spec:
  entrypoint: main
  templates:
  - name: main
    steps:
    - - name: my-container
       template: container-template
    - - name: check-exit-code
       template: exit-code-template
  - name: container-template
    container:
      image: alpine:latest
      command: ["sh", "-c"]
      args: ["exit 1"] # This will result in exit code 1
  - name: exit-code-template
    script:
      image: alpine:latest
      command: ["sh"]
      source: |
        echo "Container exit code: {{steps.my-container.outputs.exitCode}}"
        if [[ "{{steps.my-container.outputs.exitCode}}" -ne 0 ]]; then
          echo "Container failed!"
          exit 1
        else
          echo "Container Success"
        fi

3. Explanation of the Example:

- The `container-template` will exit with the exit code 1. This will be captured and made available as `steps.my-container.outputs.exitCode`.

- The `exit-code-template` uses a script to check that `exitCode`. If not 0, it will print a failure message and exit with code 1 to indicate failure, otherwise success.

4. Using the Exit Code in Conditionals:

- You can use the exit code in workflow conditionals to control the flow of execution based on success or failure of a container. For instance, you could use it in an `when` condition in a step:

steps:
  - name: my-container
    template: container-template
  - name: next-step
    template: next-step-template
    when: "{{steps.my-container.outputs.exitCode}} == 0"

5. Important Notes:

- The exit code is only available after the container has completed. Argo uses a sidecar container to observe the status of the main container.

- If a container fails to start, the `exitCode` might be null or contain a different error code. Be sure to handle potential null values when using this.

By using `container.status.exitCode` or `steps.stepname.outputs.exitCode`, you can reliably expose and use the exit code of your containers within your Argo workflows to create more robust and intelligent pipelines.

More questions