毎日学習記録 9/19 CircleCIでHugoをビルドしてS3に配置する

Share on:

概要

ローカルから手動でブログのアップをしていたのを、CircleCIに載せ替えたのでそのメモ

構成

タグ選択画面

完成形

とりあえず、最終形を記載するとこんな感じ

環境変数として、AWS側で使ってるCloudFront、S3、デプロイするためのロールのキーを環境変数に入れてる。

  • BUCKET_NAME
  • CF_DISTRIBUTION_ID
  • AWS_ACCESS_KEY_ID
  • AWS_SECRET_ACCESS_KEYdd
version: 2.1
jobs:
  build:
    docker:
      - image: cibuilds/hugo:latest
    steps:
      - checkout
      - run:
          name: "Up to date themes"
          command: |
            git submodule sync
            git submodule update --init --recursive            
      - run:
          name: "build"
          command: |
                        hugo --minify

      - persist_to_workspace:
          root: .
          paths: public

  deploy:
    docker:
      - image: xueshanf/awscli
    steps:
      - checkout
      - attach_workspace:
          at: .
      - run:
          name: "Upload S3"
          command: |
                        aws s3 sync --delete ./public/ s3://$BUCKET_NAME/
      - run:
          name: "Delete cache"
          command: |
                        aws cloudfront create-invalidation --distribution-id $CF_DISTRIBUTION_ID --paths '/*'

workflows:
  version: 2
  release:
    jobs:
      - build:
          filters:
            branches:
              only: master
      - deploy:
          requires:
            - build
          filters:
            branches:
              only: master

ポイント

Jobについて

ビルドしたディレクトリの共有
build:
    docker:
       - image: cibuilds/hugo:latest
    steps:
      - persist_to_workspace:
          root: .
          paths: public

deploy:
    docker:
      - image: xueshanf/awscli
    steps:
      - checkout
      - attach_workspace:
          at: .

persist_to_workspaceとattach_workspaceを合わせることで、ビルドしたあとにできるpublicディレクトリを引きつぐことができる

ワークフローについて

workflows:
  version: 2
  release:
    jobs:
      - build:
          filters:
            branches:
              only: master
      - deploy:
          requires:
            - build
          filters:
            branches:
              only: master

順序性を持たせる

- deploy:
    requires:
      - build

このように記載することで、deployの前にはbuildが動作しないといけないようにできる

ブランチを限定する

- deploy:
    filters:
      branches:
        only: master

filtersのなかでbranchを指定することができる

この設定を使えばmasterやfeatureなどに合わせてjobを作成できそう