Skip to main content

Deploying to Google Kubernetes Engine

You can deploy to Google Kubernetes Engine as part of your continuous deployment (CD) workflows.

Introduction

This guide explains how to use GitHub Actions to build a containerized application, push it to Google Container Registry (GCR), and deploy it to Google Kubernetes Engine (GKE) when there is a push to the main branch.

GKE is a managed Kubernetes cluster service from Google Cloud that can host your containerized workloads in the cloud or in your own datacenter. For more information, see Google Kubernetes Engine.

참고 항목

GitHub Actions 워크플로가 OIDC(OpenID Connect)를 지원하는 클라우드 공급자의 리소스에 액세스해야 하는 경우 클라우드 공급자에게 직접 인증하도록 워크플로를 구성할 수 있습니다. 이렇게 하면 이러한 자격 증명을 수명이 긴 비밀로 저장하지 않을 수 있고 다른 보안 이점을 제공할 수 있습니다. 자세한 내용은 OpenID Connect를 사용한 보안 강화 정보을(를) 참조하세요.

Prerequisites

Before you proceed with creating the workflow, you will need to complete the following steps for your Kubernetes project. This guide assumes the root of your project already has a Dockerfile and a Kubernetes Deployment configuration file.

Creating a GKE cluster

To create the GKE cluster, you will first need to authenticate using the gcloud CLI. For more information on this step, see the following articles:

For example:

Shell
$ gcloud container clusters create $GKE_CLUSTER \
	--project=$GKE_PROJECT \
	--zone=$GKE_ZONE

Enabling the APIs

Enable the Kubernetes Engine and Container Registry APIs. For example:

Shell
$ gcloud services enable \
	containerregistry.googleapis.com \
	container.googleapis.com

Configuring a service account and storing its credentials

This procedure demonstrates how to create the service account for your GKE integration. It explains how to create the account, add roles to it, retrieve its keys, and store them as a base64-encoded encrypted repository secret named GKE_SA_KEY.

  1. Create a new service account:

    Shell
    gcloud iam service-accounts create $SA_NAME
    
  2. Retrieve the email address of the service account you just created:

    Shell
    gcloud iam service-accounts list
    
  3. Add roles to the service account.

    참고 항목

    Apply more restrictive roles to suit your requirements.

    Shell
    gcloud projects add-iam-policy-binding $GKE_PROJECT \
      --member=serviceAccount:$SA_EMAIL \
      --role=roles/container.admin
    gcloud projects add-iam-policy-binding $GKE_PROJECT \
      --member=serviceAccount:$SA_EMAIL \
      --role=roles/storage.admin
    gcloud projects add-iam-policy-binding $GKE_PROJECT \
      --member=serviceAccount:$SA_EMAIL \
      --role=roles/container.clusterViewer
    
  4. Download the JSON keyfile for the service account:

    Shell
    gcloud iam service-accounts keys create key.json --iam-account=$SA_EMAIL
    
  5. Store the service account key as a secret named GKE_SA_KEY:

    Shell
    export GKE_SA_KEY=$(cat key.json | base64)
    

    For more information about how to store a secret, see Using secrets in GitHub Actions.

Storing your project name

Store the name of your project as a secret named GKE_PROJECT. For more information about how to store a secret, see Using secrets in GitHub Actions.

(Optional) Configuring kustomize

Kustomize is an optional tool used for managing YAML specs. After creating a kustomization file, the workflow below can be used to dynamically set fields of the image and pipe in the result to kubectl. For more information, see kustomize usage.

(Optional) Configure a deployment environment

환경은 일반적인 배포 대상(예: production, staging 또는 development)을 설명하는 데 사용됩니다. GitHub Actions 워크플로가 환경에 배포되면 환경이 리포지토리의 기본 페이지에 표시됩니다. 작업을 진행하기 위해 승인을 요구하거나 워크플로, 사용자 지정 배포 보호 규칙을 사용하여 게이트 배포를 트리거할 수 있는 분기를 제한하거나 비밀에 대한 액세스를 제한할 수 있습니다. 환경을 만드는 방법에 대한 자세한 내용은 Managing environments for deployment을(를) 참조하세요.

Creating the workflow

Once you've completed the prerequisites, you can proceed with creating the workflow.

The following example workflow demonstrates how to build a container image and push it to GCR. It then uses the Kubernetes tools (such as kubectl and kustomize) to pull the image into the cluster deployment.

Under the env key, change the value of GKE_CLUSTER to the name of your cluster, GKE_ZONE to your cluster zone, DEPLOYMENT_NAME to the name of your deployment, and IMAGE to the name of your image.

배포 환경을 구성한 경우 환경의 이름으로 environment 값을 변경합니다. 환경을 구성하지 않은 경우 또는 워크플로가 프라이빗 리포지토리에 있고 GitHub Enterprise Cloud를 사용하지 않는 경우 environment 키를 삭제합니다.

YAML
# 이 워크플로는 GitHub에서 인증되지 않은 작업을 사용합니다.
# 작업은 타사에서 제공하며
# 별도의 서비스 약관, 개인정보처리방침, 지원 설명서에서 규정됩니다.
# 참조하세요.

# 커밋 SHA에 작업을 고정하는 것이 좋습니다.
# 최신 버전을 얻으려면 SHA를 업데이트해야 합니다.
# 태그 또는 분기를 참조할 수도 있지만 경고 없이 작업이 변경될 수 있습니다.

name: Build and Deploy to GKE

on:
  push:
    branches:
      - main

env:
  PROJECT_ID: ${{ secrets.GKE_PROJECT }}
  GKE_CLUSTER: cluster-1    # Add your cluster name here.
  GKE_ZONE: us-central1-c   # Add your cluster zone here.
  DEPLOYMENT_NAME: gke-test # Add your deployment name here.
  IMAGE: static-site

jobs:
  setup-build-publish-deploy:
    name: Setup, Build, Publish, and Deploy
    runs-on: ubuntu-latest
    environment: production

    steps:
    - name: Checkout
      uses: actions/checkout@v4

    # Setup gcloud CLI
    - uses: google-github-actions/setup-gcloud@1bee7de035d65ec5da40a31f8589e240eba8fde5
      with:
        service_account_key: ${{ secrets.GKE_SA_KEY }}
        project_id: ${{ secrets.GKE_PROJECT }}

    # Configure Docker to use the gcloud command-line tool as a credential
    # helper for authentication
    - run: |-
        gcloud --quiet auth configure-docker

    # Get the GKE credentials so we can deploy to the cluster
    - uses: google-github-actions/get-gke-credentials@db150f2cc60d1716e61922b832eae71d2a45938f
      with:
        cluster_name: ${{ env.GKE_CLUSTER }}
        location: ${{ env.GKE_ZONE }}
        credentials: ${{ secrets.GKE_SA_KEY }}

    # Build the Docker image
    - name: Build
      run: |-
        docker build \
          --tag "gcr.io/$PROJECT_ID/$IMAGE:$GITHUB_SHA" \
          --build-arg GITHUB_SHA="$GITHUB_SHA" \
          --build-arg GITHUB_REF="$GITHUB_REF" \
          .

    # Push the Docker image to Google Container Registry
    - name: Publish
      run: |-
        docker push "gcr.io/$PROJECT_ID/$IMAGE:$GITHUB_SHA"

    # Set up kustomize
    - name: Set up Kustomize
      run: |-
        curl -sfLo kustomize https://github.com/kubernetes-sigs/kustomize/releases/download/v3.1.0/kustomize_3.1.0_linux_amd64
        chmod u+x ./kustomize

    # Deploy the Docker image to the GKE cluster
    - name: Deploy
      run: |-
        ./kustomize edit set image gcr.io/PROJECT_ID/IMAGE:TAG=gcr.io/$PROJECT_ID/$IMAGE:$GITHUB_SHA
        ./kustomize build . | kubectl apply -f -
        kubectl rollout status deployment/$DEPLOYMENT_NAME
        kubectl get services -o wide

Additional resources

For more information on the tools used in these examples, see the following documentation: