DEV Community

Yuta Goto
Yuta Goto

Posted on

3 2

ArtifactsにアップしたファイルのURLをSlackに通知する

CircleCIのArtifactにアップロードしたファイルのURLをSlackに通知する仕組みを作ります。作業リポジトリは以下です。


サンプルとしてvivriostyleでビルドして出来上がったpdfファイルをArtifactとしてアップロードしています。

アーティファクトのアップロード

https://circleci.com/docs/ja/2.0/artifacts/

公式にある通り、 store_artifactsにパスを指定します。

jobs:
  build:
    executor:
      name: node/default
      tag: 'lts-browsers'
    working_directory: ~/project # 作業用ディレクトリ指定
    steps:
      - checkout
      - node/install-packages:
          cache-path: ~/project/node_modules
          override-ci-command: yarn install
      - run:
          name: build
          command: yarn build
      - run:
          command: mkdir ~/project/artifacts # アップロード用ディレクトリ生成
      - run:
          command: mv output.pdf ~/project/artifacts/output.pdf # pdfファイルの移動
      - store_artifacts:
          path: ~/project/artifacts # アップロード
Enter fullscreen mode Exit fullscreen mode

URLの取得

https://circleci.com/docs/api/v1/#download-an-artifact-file

CircleCIのAPIにリクエストして環境変数に保存します。

artifacts=$(curl -X GET "https://circleci.com/api/v2/project/github/$CIRCLE_PROJECT_USERNAME/$CIRCLE_PROJECT_REPONAME/$CIRCLE_BUILD_NUM/artifacts" \
-H "Accept: application/json" \
--header "Circle-Token: $CIRCLE_TOKEN") # APIをたたいてレスポンス値を代入する
artifact0=$(echo $artifacts | jq '.items[0].url') # jqコマンドでurlの文字列を取得する
echo "export ARTIFACT0=$artifact0" >> $BASH_ENV # 環境変数に登録する
Enter fullscreen mode Exit fullscreen mode

変数に関しては過去記事もありますので合わせてみてください。

Slackに通知

https://circleci.com/developer/ja/orbs/orb/circleci/slack

CircleCIのSlackOrbを使うと簡単に通知させることができます。メッセージの組み立てはSlackのBlock Kit Builderを使っています。

https://app.slack.com/block-kit-builder/

      - slack/notify:
          event: always # 常に通知させる
          custom: |
            {
              "blocks": [
                {
                  "type": "section",
                  "text": {
                    "type": "mrkdwn",
                    "text": "Book Artifacts <${ARTIFACT0}>"
                  }
                }
              ]
            }
Enter fullscreen mode Exit fullscreen mode

結果

正しく登録できると以下の画像のようなSlack通知が来ると思います。リンククリックしたら実際にPDFファイルがブラウザで確認ができます。

slack

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay