最近工作上時常會用到CI/CD
也對於Github Action有點興趣
使用後真的覺得Github Actions是最方便的CI/CD服務
因為trigger速度之快~~XD
這是其他CI/CD服務比不上的
不管使用的是Github本身或是self-host
只要commit code馬上就執行job
如果是example code 一兩秒就跑完了 超神~
不僅是速度上的優勢
在工作上也把原本在Jenkins與circleci的CI/CD流程搬到Github Actions了
Actions完全可以達到 push 到 repo 後unit test、自動 build、自動跑API test、自動部署
而且還可以寫template給Github enterprise同個Organisation底下的所有Repo直接套用
也可以直接拿全世界開發者publish到marketplace的Actions來用
減少code重複撰寫的部分
總的來說~GitHub Actions優點:
- 程式碼版本控制跟CICD在同一個service下=>security 更高
- 可以直接用GitHub官方提供的免費runner機器做操作=>成本低
- GitHub Actions提供給大家撰寫actions當作function給其他使用者call =>減少code 更方便建立CI/CD workflows
本文主要是帶大家看如何撰寫自己的Action給其他人使用
最核心的檔案是action.yml:
name: Jane Hello World Action # [Required]
author: jane-chen
description: print hello world for testing self-actions # [Required]
branding:
icon: ‘activity’
color: ‘purple’
inputs: # [Optional]
strecho: # [Required] # in dockerfile using INPUT_STRECHO
description: ‘print string’ # [Required]
required: true # [Required]
numecho: # in dockerfile using INPUT_NUMECHO
description: ‘print number’
required: false
default: ‘default number’ # setting it if required: false
# outputs:
# time: # id of output
# description: ‘The time we greeted you’
runs: # [Required]
using: ‘docker’ # [Required]
image: ‘Dockerfile’ # [Required] dockerfile or public Docker registry container
args:
— ${{ inputs.strecho }}
— ${{ inputs.numecho }}
以上定義了action的資訊以及其他人使用時可以藉由with帶入的參數
主要執行內容為run
using docker 代表是Docker container type的actions 並且執行Dockerfile(帶入input的參數)
Dockerfile就是很簡單的用Image起一個
以下先展示兩種方式
- 使用dockerfile起python-based image 直接執行print
FROM python:3.9-alpine ## install helloworld module
RUN pip install — upgrade pip
RUN pip install helloworld-ajilraju CMD [“python”, “-c”, “print(‘helloworld!’);”]
2. 讓dockerfile去執行script
FROM python:3.9-alpine
# Copies your code file from your action repository to the
# filesystem path `/` of the container
COPY entrypoint.sh /entrypoint.sh # Make entrypoint.sh executable
RUN chmod +x /entrypoint.sh
# Code file to execute when the docker container starts up
# (`entrypoint.sh`)
ENTRYPOINT [“/entrypoint.sh”]
script需要注意到要讓script executable
否則會得到以下的error
docker: Error response from daemon: OCI runtime create failed: container_linux.go:380: starting container process caused: exec: “/entrypoint.sh”: permission denied: unknown.
在Dockerfile加上RUN chmod +x /entrypoint.sh 即可
Dockerfile最後帶入entrypoint.sh
而在action.yml寫的input也會作為script input variable
#!/bin/sh
#required parameters
str_echo=$1
num_echo=$2
echo “Required Information”
echo “====================”
echo “str_echo: $str_echo”
echo “num_echo: $num_echo”
如此就可以印出從action帶入的variable
最後可以建一個workflow來測試!!
/.github/workflows/helloworld.yml
name: helloworld_workflow
on: [push, workflow_dispatch]
jobs:
say_hello_job:
runs-on: ubuntu-latest
steps:
— name: hello world actions
uses: u0324020/actions-helloword@v1.0.0
with:
strecho: helloworld
主要是uses去指定某個account下的action name 以及 release version
並根據規格用with帶入客製化參數
這樣就完成一個簡單的action啦~