Inputs & Outputs
GitHub Actions allows custom actions to accept inputs and produce outputs, enabling dynamic data exchange between steps in a workflow. Inputs are defined in the action's metadata and passed via the workflow, while outputs are set during execution and consumed by subsequent steps. This section explains how to define and use inputs/outputs effectively.
Defining Inputs in Custom Actions¶
Inputs are declared in the action's metadata.yml file. Each input has a name, description, and optional default value. Required inputs must be provided by the workflow.
Example: metadata.yml
inputs:
version:
description: 'The software version to build.'
required: true
env:
description: 'Environment for deployment (e.g., staging, production).'
default: 'staging'
In the action's code (e.g., a Node.js script), inputs are accessed via the inputs object:
const version = inputs.version;
const environment = inputs.env;
console.log(`Building version ${version} for ${environment}`);
Defining Outputs in Custom Actions¶
Outputs are declared in the metadata.yml file with an id and description. They must be explicitly set during execution using the ::set-output syntax.
Example: metadata.yml
In the action's code, outputs are set like this:
Consuming Outputs in Workflows¶
Outputs from an action are accessible in subsequent steps via the steps context. Use needs or direct references to pass values.
Example Workflow:
jobs:
deploy:
steps:
- uses: actions/checkout@v3
- id: build
uses: your-action@v1
with:
version: '1.0.0'
- name: Use build number
run: |
echo "Build number: ${{ steps.build.outputs.build_number }}"
In this example, the build step's output is used in the next step to log the build number.
Best Practices¶
- Inputs: Use them for configuration parameters that vary between runs.
- Outputs: Reserve for data that must be shared between steps (e.g., artifact IDs, version numbers).
- Validation: Always validate inputs in your action code to avoid runtime errors.
- Avoid Side Effects: Ensure outputs are deterministic and not dependent on external state.
Key takeaways¶
- Inputs allow dynamic configuration of actions via the workflow.
- Outputs enable passing data between steps, such as build numbers or artifact IDs.
- Define inputs in
metadata.ymland set outputs using::set-output. - Consume outputs in workflows using
${{ steps.step-id.outputs.output-name }}. - Prioritize clarity and reliability by validating inputs and ensuring outputs are deterministic.