IaC/CI CD Tool

8. Github Action Template 생성후 MarketPlace 등록하기

Somaz 2024. 7. 1. 15:57
728x90
반응형

Overview

Github Action Template 생성후 MarketPlace 등록하는 방법에 대해서 알아본다.

 


 

Github Action Template 생성

내가 생성하고 등록한 Github Action 주소는 아래와 같다.

 


 

1. Action Template Repository 생성

GitHub에서 제공하는 Container Action Template 을 사용하여 Repository를 생성한다.

 

 


 

2. Dockerfile 및 entrypoint.sh 스크립트 수정

Container Action은 Docker 이미지를 기반으로 하므로, `Dockerfile` 과 `entrypoint.sh` 스크립트를 수정하여 필요한 작업을 정의한다.

 

Dockerfile

FROM alpine:3.20

# Install necessary packages
RUN apk add --no-cache \\
    git=2.45.2-r0 \\
    bash=5.2.26-r0 \\
    gawk=5.3.0-r1 \\
    sed=4.9-r2 \\
    perl=5.38.2-r0 \\
    grep=3.11-r0

# Set the working directory inside the container    
WORKDIR /usr/src

# Copy any source file(s) required for the action
COPY entrypoint.sh .

# Configure the container to be run as an executable
ENTRYPOINT ["/usr/src/entrypoint.sh"]

 

entrypoint.sh

#!/bin/sh

# Allow git operations in the current directory
git config --global --add safe.directory /usr/src
# Explicitly set safe directory for git operations
git config --global --add safe.directory /github/workspace

# Check if .git directory exists
if [ -d ".git" ]; then
	# Fetch commit messages with optional pretty formatting
	if ! COMMIT_MESSAGES=$(git log -"$INPUT_COMMIT_LIMIT" "${INPUT_PRETTY:+--pretty=%B}"); then
		echo "Error fetching commit messages"
		exit 1
	fi
	echo "Commit Messages:"
	echo "$COMMIT_MESSAGES"
else
	echo "No git repository available."
	COMMIT_MESSAGES="No commit messages available."
fi

# Use the provided command to extract information.
if [ -n "$INPUT_EXTRACT_COMMAND" ]; then
	# Using eval to execute the command, ensuring the command is wrapped in quotes for proper handling
	if ! ENVIRONMENT=$(echo "$COMMIT_MESSAGES" | eval "$INPUT_EXTRACT_COMMAND" | sort -u); then
		echo "Error extracting environment information"
		exit 1
	fi
else
	ENVIRONMENT="$COMMIT_MESSAGES"
fi

echo "Extracted Environment: $ENVIRONMENT"

# Set the output variable name, defaulting to 'ENVIRONMENT' if not specified
OUTPUT_VAR=${INPUT_KEY_VARIABLE:-ENVIRONMENT}

# Echo input variable for debugging or further use
echo "Input Key Variable: $OUTPUT_VAR"

# Conditional handling for GitHub Actions or local execution
if [ -n "$GITHUB_ENV" ]; then
	# GitHub Actions environment
	echo "value_variable=$ENVIRONMENT" >>"$GITHUB_ENV"
	echo "::set-output name=value_variable::$ENVIRONMENT"
	echo "::set-output name=key_variable::$OUTPUT_VAR"
	echo "Final Environment Variable ($OUTPUT_VAR): $ENVIRONMENT"
else
	# Local execution
	echo "Final Environment Variable ($OUTPUT_VAR): $ENVIRONMENT"
fi

exit 0

 

 


 

3. action.yml 정의

`action.yml` 파일을 업데이트하여 액션의 입력, 출력 및 실행 환경을 정의한다.

name: 'Extract Commit Action'
description: 'Extracts information from commit messages. Defaults output variable name to "ENVIRONMENT" if not specified.'
inputs:
  commit_limit:
    description: 'Number of commits to retrieve.'
    required: true
  pretty:
    description: 'Whether to use pretty format for git log.'
    required: false
    default: 'false'
  key_variable:
    description: 'The name of the key variable to set, defaults to "ENVIRONMENT".'
    required: false
    default: 'ENVIRONMENT'
  extract_command:  
    description: 'The command to use for extracting information from commit messages.'
    required: false
outputs:
  key_variable:
    description: 'Extracted output key variable information.'
  value_variable:
    description: 'Extracted output value variable information.'
runs:
  using: 'docker'
  image: 'Dockerfile'
  env:
    INPUT_COMMIT_LIMIT: ${{ inputs.commit_limit }}
    INPUT_PRETTY: ${{ inputs.pretty }}
    INPUT_KEY_VARIABLE: ${{ inputs.key_variable }}
    INPUT_EXTRACT_COMMAND: ${{ inputs.extract_command }}

 

 


 

4. Local Docker Build and Test

액션 템플릿을 로컬에서 빌드하고 테스트한다. 문제가 없다면 GitHub에 푸시하고 태그를 달아 버전을 관리하면 된다.

# build
docker build -f Dockerfile -t extract-commit-action .

# .env.test 생성
cat <<EOF > .env.test
INPUT_COMMIT_LIMIT=10
INPUT_EXTRACT_COMMAND=grep -oP \\bfix\\b
# INPUT_EXTRACT_COMMAND=sed 's/.*\b\(Initial\)\b.*/\1/'
# INPUT_EXTRACT_COMMAND=awk '{for(i=1;i<=NF;i++) if($i=="Initial") print $i}'
INPUT_PRETTY=true
INPUT_KEY_VARIABLE=extracted_info
EOF

 

실행한다. 잘 동작하는 걸 볼 수 있다.

docker run --rm -v "$(pwd):/repo" -w /repo --env-file ./.env.test --user "$(id -u):$(id -g)" -e HOME=/repo extract-commit-action

Commit Messages:
fix: .env.test

fix: use-action.yml

fix: entrypoint.sh

fix: entrypoint.sh

update variable

docs: README.md

docs: README.md

fix: use-action.yml

delete: tag.yml

Add tag workflow and rename test-action workflow
Extracted Environment: fix
Input Key Variable: extracted_info
Final Environment Variable (extracted_info): fix

 


 

5. Github Workflow에서 Action 사용

다양한 `yml` 을 사용하여 관리할 수 있다.

 

 


 

Github Action Template MarketPlace 등록

Github Docs에 잘 설명 되어있기 때문에 읽어보면 쉽게 등록할 수 있다.

 

 

그리고 자신이 원하는 ICON으로 변경하고 싶다면, 아래와 같이 `action.yml` 에 branding을 추가해서 작성해주면 된다.

name: 'Extract Commit Action'
description: 'Extracts information from commit messages. Defaults output variable name to "ENVIRONMENT" if not specified.'
inputs:
...
branding:
  icon: 'check-circle'
  color: 'yellow'

 

 

icon과 coler 코드는 아래의 사진에 보이는 리스트에서 확인가능하다.

 

 

그리고 만약 v1을 release 후에 v1.0.1,v1.0.2.. 이런식으로 release 하게 될텐데, module을 사용할때 아래와 같이 v1으로 사용하고 싶다면, 새로운 release의 tag의 commit과 v1을 맞춰주면 된다.

name: Example Workflow using Extract Commit Action

on:
  workflow_dispatch:
    inputs:
      run:
        description: "workflow run"
        required: true
        default: "true"

permissions:
  contents: read

jobs:
  acton-module:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v4
        with:
          fetch-depth: 10
    
      - name: Extract Commit Information
        uses: somaz94/commit-info-extractor@v1
        id: extract_commit
        with:
          commit_limit: 10
          extract_command: "grep -oP '\\bfix\\b'" # Use regex for values
          pretty: true
          key_variable: 'CUSTOM_ENV' # Key

      - name: Print Output
        run: |
          echo "Extracted variable: ${{ steps.extract_commit.outputs.key_variable }} = ${{ steps.extract_commit.outputs.value_variable }}"

 

tag를 맞춰주는 방법은 아래와 같다.

# 새로운 버전 release
git tag v1.0.1
git push origin v1.0.1

# v1과 v1.0.1 맞추기
git tag -f v1 v1.0.1
git push -f origin v1

 

그럼 사진과 같이 commit값이 동일해진다.

 

 

 

 

Github Action Template을 생성후에 MarketPlace에 등록을 해보았다!

https://github.com/marketplace/actions/extract-commit-action

 

Extract Commit Action - GitHub Marketplace

Extracts information from commit messages. Defaults output variable name to "ENVIRONMENT" if not specified

github.com

 

 

 


Reference

https://github.com/actions/container-action

https://docs.github.com/en/actions/creating-actions/publishing-actions-in-github-marketplace

https://github.com/marketplace/actions/extract-commit-action

https://medium.com/jung-han/github-action%EC%9D%84-%EB%A7%88%EC%BC%93%EC%97%90-%EB%93%B1%EB%A1%9D%ED%95%B4%EB%B3%B4%EC%9E%90-7a181a0b4a8f

728x90
반응형