Skip to content

Custom Actions

GitHub Actions allows developers to create reusable custom actions using JavaScript (Node.js) or Docker containers. Custom actions encapsulate logic for tasks like code testing, dependency installation, or environment setup, enabling teams to standardize workflows across repositories. This guide explains how to build and package custom actions for both JavaScript and Docker-based implementations.


Creating JavaScript Actions

JavaScript actions are built using Node.js and follow a standard directory structure. Here's how to create one:

1. Project Setup

Create a new directory for your action and initialize a Node.js project:

mkdir my-action
cd my-action
npm init -y

Add a action.yml file to define metadata and inputs/outputs:

name: 'Hello World'
description: 'Prints a greeting message'
inputs:
  name:
    description: 'Name to greet'
    required: true
outputs:
  greeting:
    description: 'Generated greeting'
runs:
  using: 'node16'
  main: 'index.js'

Create an index.js file with the action logic:

const { context } = require('@actions/core');
const { io } = require('@actions/github');

const name = context.getInput('name');
const greeting = `Hello, ${name}!`;

console.log(greeting);
io.setOutput('greeting', greeting);

2. Packaging

Package the action into a ZIP file for distribution:

npm install
npx actions:package

This generates a dist directory containing the packaged action.


Creating Docker Actions

Docker actions run in isolated containers, ideal for complex tasks requiring specific environments.

1. Project Setup

Create a Dockerfile to define the container:

FROM node:16
WORKDIR /app
COPY . .
RUN npm install
CMD ["node", "index.js"]

Create an index.js file with the same logic as the JavaScript example above.

2. Packaging

Build and tag the Docker image:

docker build -t my-action:latest .
docker save my-action:latest > my-action.tar

Upload the .tar file to a container registry (e.g., Docker Hub) for reuse.


Packaging and Versioning

Packaging

  • JavaScript: Use actions:package to generate a ZIP file.
  • Docker: Export the container as a .tar file or push to a registry.

Versioning

Use semantic versioning (e.g., v1.0.0) and tag releases in Git:

git tag v1.0.0
git push origin v1.0.0

When publishing to the GitHub Marketplace, ensure the action.yml specifies the correct version:

version: '1.0.0'


Key takeaways

  • JavaScript actions leverage Node.js and require an action.yml metadata file.
  • Docker actions use containers, ideal for complex or environment-sensitive tasks.
  • Package actions as ZIP files (JavaScript) or Docker images (Docker) for distribution.
  • Use semantic versioning and Git tags to manage releases and ensure compatibility.