見出し画像

GitHub ActionsとFirebaseを使ってVue.jsのコードをdeployしてみる

GitHub Actionsを試してみました
コード管理 / CI / CDまでGitHubで管理でできちゃうんですね〜

AWSを使っているプロジェクトだとCode pipeline等を使用してCI / CDをするのが今どきは主流な様ですが、
web開発するにほぼ確実にgithub絶対使うのと、
GCP等を使用するprojectでも汎用性があると思ったのでGitHub Actionsを試してみました。

今どきはAWS / Firebase / GCP / Azure等プロジェクトによって使用するクラウドが異なっているので、
ベンダーロックされるならGAFAクラウド側よりGitHubにベンダーロックされたほうが安心感があるような気がしてます!

今回のゴール

github actionを使ってmasterにpush(merge)されたことをトリガーにdeployする👍

使うもの
・Firebase Hosting
・Vue.js
・GitHub Actions

まずFirebase Hosting / Vue.jsでHelloWorldしてみます。

# GUIでFirebaseのproject済み
mkdir github_action_test
cd github-action-test
vue create github-action-test
npm install
npm run serve

http://localhost:8080/  にアクセス



画像1


frontのコードをbuildします。
distという名前のフォルダにbuildされたコードが保存されています。


npm run build
tree -d -L 1
.
├── dist (ここ)
├── node_modules
├── public
└── src
​

Firebaseにhosting

firebase init hosting
     ######## #### ########  ######## ########     ###     ######  ########
     ##        ##  ##     ## ##       ##     ##  ##   ##  ##       ##
     ######    ##  ########  ######   ########  #########  ######  ######
     ##        ##  ##    ##  ##       ##     ## ##     ##       ## ##
     ##       #### ##     ## ######## ########  ##     ##  ######  ########

? Please select an option: Use an existing project
? Select a default Firebase project for this directory: github-action-test-7bad1 (gith
ub-action-test)
# guiで選択したprojectを選択
i  Using project github-action-test-7bad1 (github-action-test)
=== Hosting Setup
# ここでvueの静的ファイルが保存されているdictを指定
? What do you want to use as your public directory? dist
? Configure as a single-page app (rewrite all urls to /index.html)? No
✔  Wrote dist/404.html
? File dist/index.html already exists. Overwrite? No
i  Skipping write of dist/index.html
i  Writing configuration info to firebase.json...
i  Writing project information to .firebaserc...
✔  Firebase initialization complete!
# 一旦手動でdeployしてみます
firebase deploy
✔  Deploy complete!

# このURLにhostiningされている
Hosting URL: https://github-action-test-7bad1.web.app

hostingされたURLを確認します。

画像2


公式ドキュメントを確認

ここからGithub Actionsを始めていきます👍
実際に始める前に公式ドキュメントを確認を斜め読みします。偉い人に公式ドキュメント読んでから作業しろと言ってたので読みます。

以下はメモなので各自公式ドキュメントを読んでもらえればと思います。

公式ドキュメント
https://help.github.com/en/actions/reference/workflow-syntax-for-github-actions#usage-limits
公式node用のymlの例
https://github.com/actions/starter-workflows/blob/master/ci/node.js.yml
公式のFirebase用のymlの例
https://github.com/marketplace/actions/github-action-for-firebase

Workflow files use YAML syntax, and must have either a .yml or .yaml file extension. If you're new to YAML and want to learn more, see "Learn YAML in five minutes."
You must store workflow files in the .github/workflows directory of your repository.

.github/workflowsにymlを定義

Job execution time - Each job in a workflow can run for up to 6 hours of execution time. If a job reaches this limit, the job is terminated and fails to complete. This limit does not apply to self-hosted runners.
Workflow run time - Each workflow run is limited to 72 hours. If a workflow run reaches this limit, the workflow run is cancelled. This limit also applies to self-hosted runners.
Job queue time - Each job for self-hosted runners can be queued for a maximum of 24 hours. If a self-hosted runner does not start executing the job within this limit, the job is terminated and fails to complete. This limit does not apply to GitHub-hosted runners.
API requests - You can execute up to 1000 API requests in an hour across all actions within a repository. If exceeded, additional API calls will fail, which might cause jobs to fail. This limit also applies to self-hosted runners.
Concurrent jobs - The number of concurrent jobs you can run in your account depends on your GitHub plan, as indicated in the following table. If exceeded, any additional jobs are queued. There are no concurrency limits for self-hosted runners.

jobの最大時間 / キューの時間 / APIのリクエスト数 / 並列数の上限がプランにより異なる。
今回はテストなのでそこまで気にすることはない。

on
Required The name of the GitHub event that triggers the workflow. You can provide a single event string, array of events, array of event types, or an event configuration map that schedules a workflow or restricts the execution of a workflow to specific files, tags, or branch changes. For a list of available events, see "Events that trigger workflows."

onでトリガーと指定できる。一つならsting 、複数ならarray。

on.<push|pull_request>.<branches|tags>
When using the push and pull_request events, you can configure a workflow to run on specific branches or tags. For a pull_request event, only branches and tags on the base are evaluated. If you define only tags or only branches, the workflow won't run for events affecting the undefined Git ref.
The branches, branches-ignore, tags, and tags-ignore keywords accept glob patterns that use the * and ** wildcard characters to match more than one branch or tag name. For more information, see the "Filter pattern cheat sheet."

on(トリガー)が発行されるブランチとかを指定できる。
* とかで `release/*` の様にbranchに指定できる。

on.schedule
You can schedule a workflow to run at specific UTC times using POSIX cron syntax. Scheduled workflows run on the latest commit on the default or base branch. The shortest interval you can run scheduled workflows is once every 5 minutes.
This example triggers the workflow every 15 minutes:

スケジューリングもできるっぽい。クラウドのcronサービスではなくこちらを使用してもいいかも。
今回は使用しないが今度試してみたい。


defaults.run
You can provide default shell and working-directory options for all run steps in a workflow. You can also set default settings for run that are only available to a job. For more information, see jobs.<job_id>.defaults.run. You cannot use contexts or expressions in this keyword.
When more than one default setting is defined with the same name, GitHub uses the most specific default setting. For example, a default setting defined in a job will override a default setting that has the same name defined in a workflow.

実行するshellの選択
ディレクトリを指定できる(今回は特に指定しなかった。defaultはbashな感じ)

jobs
A workflow run is made up of one or more jobs. Jobs run in parallel by default. To run jobs sequentially, you can define dependencies on other jobs using the jobs.<job_id>.needs keyword.
Each job runs in an environment specified by runs-on.
You can run an unlimited number of jobs as long as you are within the workflow usage limits. For more information, see "Usage limits."
If you need to find the unique identifier of a job running in a workflow run, you can use the GitHub API. For more information, see "Workflow Jobs" in the GitHub Developer documentation.
jobs.<job_id>
Each job must have an id to associate with the job. The key job_id is a string and its value is a map of the job's configuration data. You must replace <job_id> with a string that is unique to the jobs object. The <job_id> must start with a letter or _ and contain only alphanumeric characters, -, or _.
jobs.<job_id>.name
The name of the job displayed on GitHub.
jobs.<job_id>.needs
Identifies any jobs that must complete successfully before this job will run. It can be a string or array of strings. If a job fails, all jobs that need it are skipped unless the jobs use a conditional statement that causes the job to continue.

実行するjobを定義できる。
id /  name(表示される名前) /  need(依存関係の指定)
(特に今回は依存関係の指定をしなかった。)


jobs.<job_id>.runs-on
Required The type of machine to run the job on. The machine can be either a GitHub-hosted runner, or a self-hosted runner.
GitHub-hosted runners
If you use a GitHub-hosted runner, each job runs in a fresh instance of a virtual environment specified by runs-on.
Available GitHub-hosted runner types are:
linux
mac
windows

runする実行環境を選択できる。今回はubuntu

jobs.<job_id>.if
You can use the if conditional to prevent a job from running unless a condition is met. You can use any supported context and expression to create a conditional.
When you use expressions in an if conditional, you may omit the expression syntax (${{ }}) because GitHub automatically evaluates the if conditional as an expression. For more information, see "Context and expression syntax for GitHub Actions."
jobs.<job_id>.steps
A job contains a sequence of tasks called steps. Steps can run commands, run setup tasks, or run an action in your repository, a public repository, or an action published in a Docker registry. Not all steps run actions, but all actions run as a step. Each step runs in its own process in the runner environment and has access to the workspace and filesystem. Because steps run in their own process, changes to environment variables are not preserved between steps. GitHub provides built-in steps to set up and complete a job.
You can run an unlimited number of steps as long as you are within the workflow usage limits. For more information, see "Usage limits."
jobs.<job_id>.steps.id
A unique identifier for the step. You can use the id to reference the step in contexts. For more information, see "Context and expression syntax for GitHub Actions."
jobs.<job_id>.steps.if
You can use the if conditional to prevent a step from running unless a condition is met. You can use any supported context and expression to create a conditional.

jobに対して条件分岐出来る。
jobを順次実行するためにstepという単位がある。
stepに対しても条件分岐が出来る。今回は使用しない。

jobs.<job_id>.steps.uses
Selects an action to run as part of a step in your job. An action is a reusable unit of code. You can use an action defined in the same repository as the workflow, a public repository, or in a published Docker container image.
>We strongly recommend that you include the version of the action you are using by specifying a Git ref, SHA, or Docker tag number. If you don't specify a version, it could break your workflows or cause unexpected behavior when the action owner publishes an update.

stepの内で実行したい内容がすでにactionsに定義されていて、それを使用したい場合はuseを使う。公式でFirebase周りやnode周りはこれを使っていたので使用する。

jobs.<job_id>.steps.run
Runs command-line programs using the operating system's shell. If you do not provide a name, the step name will default to the text specified in the run command.

実行したい内容をrunで指定

jobs.<job_id>.strategy
A strategy creates a build matrix for your jobs. You can define different variations of an environment to run each job in.

strategyで実行バージョン・環境とかも定義できます。。
ubuntu / node12系にしました。
完全に理解したので、実際にymlを書きます👍

画像3

Github Actionsの設定ファイルを作成する

HellowWorldした画面を少しいじります。

git diff
diff --git a/src/App.vue b/src/App.vue
index fb03c6e..3862b84 100644
--- a/src/App.vue
+++ b/src/App.vue
@@ -1,7 +1,7 @@
 <template>
   <div id="app">
     <img alt="Vue logo" src="./assets/logo.png" />
-    <HelloWorld msg="Welcome to Your Vue.js App" />
+    <HelloWorld msg="emono test😸" />
   </div>
 </template>

local環境がこうなりました😸

画像4

Github Action設定の為に、ディレクトリとymlファイルを作ります。

mkdir -p .github/workflows
touch vue-firebase.yml

色々試してみた結果ymlは以下になりました。

name: Firebase deploy

on:
  push:
    branches:
      - master

jobs:
  build-deploy:
    runs-on: ubuntu-latest
    strategy:
      matrix:
        node-version: [12.x]

    steps:
    - name: check out master
      uses: actions/checkout@master
    - name: Use Node.js ${{ matrix.node-version }}
      uses: actions/setup-node@master
      with:
        node-version: ${{ matrix.node-version }}
    - name: install package
      run: npm install
    - name: build vue code
      run: npm run build
    - name: deploy to Firebase Hosting
      uses: w9jds/firebase-action@master
      with:
        args: deploy
      env:
        FIREBASE_TOKEN: ${{ secrets.FIREBASE_TOKEN }}
            

deployにはFirebaseのtokenが必要なので環境変数に設定する。
tokenは下記のコマンドで取得出来る。

firebase login:ci
Success! Use this token to login on a CI server:
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Setting > Secretsから上記で確認したtokenを環境編集に指定します。

画像5

PRを作成してmasterにマージします。
マージをトリガーにしてdeployが走りました。

画像6

firebaseのhostingされているURLを確認します

画像7

変更が反映されています🙆‍♀️

いえーーい!!!!

以上でGithub Actionsを使ってCI / CDが出来ました。

感じたメリット

1. クラウドを使用する場合Personal access tokensを作成して環境変数に入れたりが必要だが、Github内で完結している為不要。クラウドよりも管理する鍵は減る。
2. クラウドベンダーロックされない(Githubにロックされる)。

他にもあるかもですが、あんまりCI / CD強くないのであれば教えて下さい!


終わり

もはやバックエンドエンジニアは
CI / CDも出来るよね?👀
クラウドもわかるよね?👀
という流れを感じるので、最低限キャッチアップしたいなという気持ちもあり試してみることにしました。
意外とさっくりいけたのでよかったです。

以上あざした〜。
もっとイケてるやりかたがあれば指摘下さい👾

この記事が気に入ったらサポートをしてみませんか?