JavaScript 액션 만들기

JavaScript 액션 만들기

이 튜토리얼에서는 actions toolkit을 사용해서 JavaScript 액션을 직접 만드는 방법을 알려드릴게요. 패키징된 JavaScript 액션을 만들고 사용하는 데 필요한 기본 구성 요소를 배울 수 있어요.

출처: 문서

본문

Introduction

이 가이드에서는 패키징된 JavaScript 액션을 만들고 사용하는 데 필요한 기본 구성 요소를 배우게 돼요. 이 가이드는 액션을 패키징하는 데 필요한 구성 요소에 초점을 맞추기 때문에 액션 코드의 기능은 최소한으로 유지해요. 이 액션은 로그에 "Hello World"를 출력하거나 사용자 지정 이름을 제공하면 "Hello [who-to-greet]"을 출력해요.

이 가이드는 개발 속도를 높이기 위해 GitHub Actions Toolkit Node.js 모듈을 사용해요. 자세한 내용은 actions/toolkit 저장소를 참고하세요.

이 프로젝트를 완료하면 JavaScript 액션을 직접 만들고 워크플로우에서 테스트하는 방법을 이해할 수 있게 돼요.

JavaScript 액션이 모든 GitHub에서 호스팅하는 러너(Ubuntu, Windows, macOS)와 호환되도록 하려면, 작성하는 패키징된 JavaScript 코드는 순수 JavaScript여야 하고 다른 바이너리에 의존해서는 안 돼요. JavaScript 액션은 러너에서 직접 실행되며 러너 이미지에 이미 존재하는 바이너리를 사용해요.

[!WARNING] 워크플로우와 액션을 만들 때는 항상 코드가 잠재적인 공격자의 신뢰할 수 없는 입력을 실행할 수 있는지 고려해야 해요. 특정 컨텍스트는 신뢰할 수 없는 입력으로 취급해야 해요. 공격자가 자신의 악성 콘텐츠를 삽입할 수 있기 때문이에요. 자세한 내용은 Secure use reference 문서를 참고하세요.

Prerequisites

시작하기 전에 Node.js를 다운로드하고 공개 GitHub 저장소를 만들어야 해요.

  1. npm을 포함하는 Node.js 24.x를 다운로드하고 설치하세요.

    https://nodejs.org/en/download/

  2. GitHub에서 새 공개 저장소를 만들고 "hello-world-javascript-action"이라고 부르세요. 자세한 내용은 Creating a new repository 문서를 참고하세요.

  3. 저장소를 컴퓨터에 복제하세요. 자세한 내용은 Cloning a repository 문서를 참고하세요.

  4. 터미널에서 새 저장소로 디렉터리를 변경하세요.

    cd hello-world-javascript-action
    
  5. 터미널에서 npm으로 디렉터리를 초기화해서 package.json 파일을 생성하세요.

    npm init -y
    

Creating an action metadata file

hello-world-javascript-action 디렉터리에 다음 예시 코드로 action.yml이라는 새 파일을 만드세요. 자세한 내용은 Metadata syntax reference 문서를 참고하세요.

name: Hello World
description: Greet someone and record the time

inputs:
  who-to-greet: # id of input
    description: Who to greet
    required: true
    default: World

outputs:
  time: # id of output
    description: The time we greeted you

runs:
  using: node24
  main: dist/index.js

이 파일은 who-to-greet 입력과 time 출력을 정의해요. 또한 액션 러너에 이 JavaScript 액션을 실행하는 방법을 알려줘요.

Adding actions toolkit packages

actions toolkit은 더 일관성 있게 JavaScript 액션을 빠르게 빌드할 수 있게 해 주는 Node.js 패키지 모음이에요.

toolkit @actions/core 패키지는 워크플로우 명령, 입력 및 출력 변수, 종료 상태, 디버그 메시지에 대한 인터페이스를 제공해요.

toolkit은 또한 인증된 Octokit REST 클라이언트와 GitHub Actions 컨텍스트 접근을 반환하는 @actions/github 패키지를 제공해요.

toolkit은 coregithub 패키지보다 더 많은 것을 제공해요. 자세한 내용은 actions/toolkit 저장소를 참고하세요.

터미널에서 actions toolkit의 coregithub 패키지를 설치하세요.

npm install @actions/core @actions/github

이제 설치된 의존성과 버전을 추적하는 node_modules 디렉터리와 package-lock.json 파일이 보일 거예요. node_modules 디렉터리는 저장소에 커밋하면 안 돼요.

Writing the action code

이 액션은 toolkit을 사용해서 액션의 메타데이터 파일에 필요한 who-to-greet 입력 변수를 가져오고, 로그의 디버그 메시지에 "Hello [who-to-greet]"을 출력해요. 다음으로 스크립트는 현재 시간을 가져와서 job의 이후 단계에서 사용할 수 있는 출력 변수로 설정해요.

GitHub Actions는 웹훅 이벤트, Git refs, 워크플로우, 액션, 워크플로우를 트리거한 사람에 대한 컨텍스트 정보를 제공해요. 컨텍스트 정보에 접근하려면 github 패키지를 사용할 수 있어요. 작성할 액션은 웹훅 이벤트 페이로드를 로그에 출력할 거예요.

다음 코드로 src/index.js라는 새 파일을 추가하세요.

import * as core from "@actions/core";
import * as github from "@actions/github";

try {
  // `who-to-greet` input defined in action metadata file
  const nameToGreet = core.getInput("who-to-greet");
  core.info(`Hello ${nameToGreet}!`);

  // Get the current time and set it as an output variable
  const time = new Date().toTimeString();
  core.setOutput("time", time);

  // Get the JSON webhook payload for the event that triggered the workflow
  const payload = JSON.stringify(github.context.payload, undefined, 2);
  core.info(`The event payload: ${payload}`);
} catch (error) {
  core.setFailed(error.message);
}

index.js 예시에서 오류가 발생하면 core.setFailed(error.message);가 actions toolkit @actions/core 패키지를 사용해서 메시지를 기록하고 실패 종료 코드를 설정해요. 자세한 내용은 Setting exit codes for actions 문서를 참고하세요.

Creating a README

사람들이 액션을 사용하는 방법을 알 수 있도록 README 파일을 만들 수 있어요. README는 액션을 공개적으로 공유할 계획이 있을 때 가장 유용하지만, 여러분이나 팀에게 액션 사용 방법을 상기시켜 주는 훌륭한 방법이기도 해요.

hello-world-javascript-action 디렉터리에 다음 정보를 명시하는 README.md 파일을 만드세요.

  • 액션이 수행하는 작업에 대한 상세 설명.
  • 필수 입력 및 출력 인수.
  • 선택적 입력 및 출력 인수.
  • 액션이 사용하는 secret.
  • 액션이 사용하는 환경 변수.
  • 워크플로우에서 액션을 사용하는 예시.
# Hello world JavaScript action

This action prints "Hello World" or "Hello" + the name of a person to greet to the log.

## Inputs

### `who-to-greet`

**Required** The name of the person to greet. Default `"World"`.

## Outputs

### `time`

The time we greeted you.

## Example usage

```yaml
uses: actions/hello-world-javascript-action@e76147da8e5c81eaf017dede5645551d4b94427b
with:
  who-to-greet: Mona the Octocat
```

Commit, tag, and push your action

GitHub는 워크플로우에서 실행되는 각 액션을 런타임 중에 다운로드하고 run 같은 워크플로우 명령을 사용해 러너 머신과 상호작용하기 전에 완전한 코드 패키지로 실행해요. 즉, JavaScript 코드를 실행하는 데 필요한 모든 패키지 의존성을 포함해야 해요. 예를 들어 이 액션은 @actions/core@actions/github 패키지를 사용해요.

node_modules 디렉터리를 커밋하면 문제가 발생할 수 있어요. 대안으로 rollup.js 또는 @vercel/ncc 같은 도구를 사용해서 코드와 의존성을 배포용 단일 파일로 결합할 수 있어요.

  1. 터미널에서 다음 명령을 실행해서 rollup과 해당 플러그인을 설치하세요.

    npm install --save-dev rollup @rollup/plugin-commonjs @rollup/plugin-node-resolve

  2. 저장소의 루트에 다음 코드로 rollup.config.js라는 새 파일을 만드세요.

    import commonjs from "@rollup/plugin-commonjs";
    import { nodeResolve } from "@rollup/plugin-node-resolve";
    
    const config = {
      input: "src/index.js",
      output: {
        esModule: true,
        file: "dist/index.js",
        format: "es",
        sourcemap: true,
      },
      plugins: [commonjs(), nodeResolve({ preferBuiltins: true })],
    };
    
    export default config;
    
  3. dist/index.js 파일을 컴파일하세요.

    rollup --config rollup.config.js

    코드와 의존성이 포함된 새 dist/index.js 파일이 보일 거예요.

  4. 터미널에서 업데이트를 커밋하세요.

    git add src/index.js dist/index.js rollup.config.js package.json package-lock.json README.md action.yml
    git commit -m "Initial commit of my first action"
    git tag -a -m "My first action release" v1.1
    git push --follow-tags
    

코드를 커밋하고 푸시하면 업데이트된 저장소는 다음과 같아야 해요.

hello-world-javascript-action/
├── action.yml
├── dist/
│   └── index.js
├── package.json
├── package-lock.json
├── README.md
├── rollup.config.js
└── src/
    └── index.js

Testing out your action in a workflow

이제 워크플로우에서 액션을 테스트할 준비가 됐어요.

공개 액션은 어떤 저장소의 워크플로우에서든 사용할 수 있어요. 액션이 비공개 저장소에 있을 때는 저장소 설정이 액션이 같은 저장소 내에서만 사용 가능한지, 아니면 같은 사용자나 조직이 소유한 다른 저장소에서도 사용 가능한지 결정해요. 자세한 내용은 Managing GitHub Actions settings for a repository 문서를 참고하세요.

Example using a public action

이 예시는 새 공개 액션을 외부 저장소에서 실행할 수 있는 방법을 보여줍니다.

다음 YAML을 .github/workflows/main.yml의 새 파일에 복사하고, uses: octocat/hello-world-javascript-action@1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b 줄을 여러분의 사용자 이름과 위에서 만든 공개 저장소 이름으로 업데이트하세요. who-to-greet 입력도 자신의 이름으로 바꿀 수 있어요.

on:
  push:
    branches:
      - main

jobs:
  hello_world_job:
    name: A job to say hello
    runs-on: ubuntu-latest

    steps:
      - name: Hello world action step
        id: hello
        uses: octocat/hello-world-javascript-action@1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b
        with:
          who-to-greet: Mona the Octocat

      # Use the output from the `hello` step
      - name: Get the output time
        run: echo "The time was ${{ steps.hello.outputs.time }}"

이 워크플로우가 트리거되면 러너가 공개 저장소에서 hello-world-javascript-action 액션을 다운로드한 다음 실행해요.

Example using a private action

워크플로우 코드를 액션 저장소의 .github/workflows/main.yml 파일에 복사하세요. who-to-greet 입력도 자신의 이름으로 바꿀 수 있어요.

on:
  push:
    branches:
      - main

jobs:
  hello_world_job:
    name: A job to say hello
    runs-on: ubuntu-latest

    steps:
      # To use this repository's private action,
      # you must check out the repository
      - name: Checkout
        uses: actions/checkout@v6

      - name: Hello world action step
        uses: ./ # Uses an action in the root directory
        id: hello
        with:
          who-to-greet: Mona the Octocat

      # Use the output from the `hello` step
      - name: Get the output time
        run: echo "The time was ${{ steps.hello.outputs.time }}"

저장소에서 Actions 탭을 클릭하고 가장 최근 워크플로우 실행을 선택하세요. Jobs 아래 또는 시각화 그래프에서 A job to say hello를 클릭하세요.

Hello world action step을 클릭하면 로그에 "Hello Mona the Octocat" 또는 who-to-greet 입력에 사용한 이름이 출력되는 것을 볼 수 있어요. 타임스탬프를 보려면 Get the output time을 클릭하세요.

Template repositories for creating JavaScript actions

GitHub는 JavaScript 및 TypeScript 액션을 만들기 위한 템플릿 저장소를 제공해요. 이 템플릿을 사용하면 테스트, 린팅, 기타 권장 사례가 포함된 새 액션을 빠르게 시작할 수 있어요.

Example JavaScript actions on GitHub.com

GitHub.com에서 JavaScript 액션의 많은 예시를 찾을 수 있어요.

더 알아보기 (Learn more)