Github
https://github.com/wmetaw/cloud-run-exec-gcloud-command
Cloud RunにGoアプリを自動デプロイ
https://www.apps-gcp.com/deploy-go-app-to-cloud-run-by-cloud-build/
main.go
package main
import (
"fmt"
"log"
"net/http"
"os"
"os/exec"
)
func main() {
http.HandleFunc("/", index)
http.HandleFunc("/version", version)
port := os.Getenv("PORT")
if port == "" {
port = "8080"
log.Printf("Defauting to port %s", port)
}
log.Printf("Linstening on port %s", port)
err := http.ListenAndServe(fmt.Sprintf(":%s", port), nil)
if err != nil {
log.Fatal(err)
}
}
func index(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "hello cloud run")
}
func version(w http.ResponseWriter, r *http.Request) {
s, err := exec.Command("gcloud", "version").Output()
if err != nil {
log.Fatal(err)
}
fmt.Fprintf(w, string(s))
}
go.mod
module github.com/wmetaw/cloud-run-exec-gcloud-command
go 1.14
Dockerfile
FROM golang:1.14.4-alpine3.12 as builder
WORKDIR /go/src
COPY . .
RUN CGO_ENABLED=0 GOOS=linux go build -v -o main
FROM gcr.io/cloud-builders/gcloud:latest
WORKDIR /usr/local/bin
COPY --from=builder /go/src/main /main
ENTRYPOINT ["/main"]
cloudbuild.yaml
steps:
# dockerビルド
# build -t ['イメージ名:タグ'] [DcokerFileパス]
- name: 'gcr.io/cloud-builders/docker'
id: 'build-docker-image'
args: ['build', '-t', 'gcr.io/$PROJECT_ID/${_SERVICE_NAME}', '.']
# docker imageをpush
- name: 'gcr.io/cloud-builders/docker'
id: 'push-docker-image'
args: ['push', 'gcr.io/$PROJECT_ID/${_SERVICE_NAME}']
# Cloud Runへデプロイ
# --platformはmanaged,gke,kubernetesのいずれかを指定 see https://cloud.google.com/sdk/gcloud/reference/beta/run/deploy
- name: 'gcr.io/cloud-builders/gcloud'
id: 'deploy-cloud-run'
args: ['run', 'deploy', '${_SERVICE_NAME}', '--image', 'gcr.io/$PROJECT_ID/${_SERVICE_NAME}', '--region', '${_REGION}', '--platform', 'managed']
# Cloud Run閲覧権限付与
- name: 'gcr.io/cloud-builders/gcloud'
id: 'apply-member-role-cloud-run'
args: ['run', 'services', 'add-iam-policy-binding', '${_SERVICE_NAME}', '--region', '${_REGION}', '--member', 'allUsers', '--role', 'roles/run.invoker', '--platform', 'managed']
# 変数定義
# see https://cloud.google.com/cloud-build/docs/configuring-builds/substitute-variable-values?hl=ja
substitutions:
_REGION: asia-northeast1
_SERVICE_NAME: exec-gcloud-command
# imagesフィールドにはCloudBuildがContainerRegistry にpushする1つ以上の Dockerイメージを指定
images:
- gcr.io/$PROJECT_ID/${_SERVICE_NAME}