這次我們要使用Github的Action來執行自動整合,在特定情況會自動建立Image和推到 GCR 上。
STEP 1: Build A Role in GCP
- 為專案新增一個 主體 > 擁有者
- 為專案新增一個 主體 > 服務帳戶
- 驗證您是否擁有所足夠的權限,該角色至少要有 Storage Admin以上權限的角色。
- 有關 Storage Admin (roles/storage.admin)角色的說明,請參閱Cloud Storage 文檔。
STEP 2: Generate an Admin Key
- 為專案新增金鑰服務帳戶 > [Role Name] > 金鑰 。
- 金鑰類型 JSON
- 建完之後金鑰會自動下載。
STEP 3: Push Key to Github Project Setting
- 打開金鑰,整段複製。
- [GITHUB USER]/[GITHUB PROJECT NAME] > Settings > Secrets > Actions > New repository secret
- 名字我們這邊使用: GCR_KEY
STEP 4: Create Action .yml file
添加一個yaml檔到專案裡,位置是.github/workflows/
下。
這邊提供一個範例,用來修改應該相當方便,有一些標籤,都滿直白的應該都不會有太多問題
name: Build and Push to GCR
on:
push:
branches:
- 'release'
- 'main'
# Environment variables available to all jobs and steps in this workflow
env:
GITHUB_SHA: '${{github.sha}}'
GITHUB_REF: '${{github.ref}}'
IMAGE: 'python:3.7.13-slim'
REGISTRY_HOSTNAME: 'gcr.io'
IMAGE_NAME: 'flask-helloworld'
PROJECT_NAME: 'modelpoc'
jobs:
setup-build-publish-deploy:
name: 'Setup, Build, and Publish'
runs-on: 'ubuntu-latest'
steps:
- name: 'Checkout'
uses: 'actions/checkout@v2'
# Setup gcloud CLI
- name: 'auth'
uses: 'google-github-actions/auth@v0'
with:
credentials_json: '${{secrets.GCR_KEY}}'
- name: 'Set up Cloud SDK'
uses: 'google-github-actions/setup-gcloud@v0'
# Configure docker to use the gcloud command-line tool as a credential helper
- name: 'Use gcloud CLI'
run: |
# Set up docker to authenticate
# via gcloud command-line tool.
gcloud auth configure-docker
# Build the Docker image
- name: 'Build'
run: |
export TAG=`echo $GITHUB_REF | awk -F/ '{print $NF}'`
echo $TAG
docker build -t "$REGISTRY_HOSTNAME"/"$PROJECT_NAME"/"$IMAGE_NAME":"$TAG" \
--build-arg GITHUB_SHA="$GITHUB_SHA" \
--build-arg GITHUB_REF="$GITHUB_REF" .
# Push the Docker image to Google Container Registry
- name: 'Publish'
run: |
export TAG=`echo $GITHUB_REF | awk -F/ '{print $NF}'`
echo $TAG
docker push "$REGISTRY_HOSTNAME"/"$PROJECT_NAME"/"$IMAGE_NAME":"$TAG"
docker tag "$REGISTRY_HOSTNAME"/"$PROJECT_NAME"/"$IMAGE_NAME":"$TAG" "$REGISTRY_HOSTNAME"/"$PROJECT_NAME"/"$IMAGE_NAME":latest-"$TAG"
docker push "$REGISTRY_HOSTNAME"/"$PROJECT_NAME"/"$IMAGE_NAME":latest-"$TAG"