1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

CircleCIでContextを使おうとしてハマった話

Last updated at Posted at 2021-03-30

私はSEとして働いておりますが、普段は自動テストとは無縁の仕事をしています。ただし、プライベートで作業をする時はテストを自動化しており、CIツールとしてCircleCIを使用しています。

そのCircleCIにはContextという、環境変数をCircleCI内にあらかじめ設定しておく機能があり、APIキーなどソースコードに含めると危険なものに関しては別途管理できます。ただし、自分はそれを利用する際に変数がなぜか参照できないという事態に陥ったので今回はその解決方法について記事にします。

前提

Contextの設定値は以下の通り。

Context名:LINE_BOT
環境変数名:API_KEY

修正前

以下が修正前のconfig.yml(CircleCIの設定ファイル)になります。
commandの行に$API_KEYとありますが、なんど実行してもこの値は空になります。

config.yml
version: 2.1

orbs:
  python: circleci/python@0.2.1

jobs:
  build-and-test:
    executor: python/default
    steps:
~~~(中略)~~~
      - run:
          name: Run pytest
          command: pipenv run pytest --apikey $API_KEY

workflows:
  main:
    jobs:
      - build-and-test

ちなみにこの段階ではContext名を指定する必要があるということまでは気づいており、$LINE_BOT.API_KEYなど色々試したのですが上手くいくことはありませんでした。

修正後

以下が修正後です。違いがわかりますでしょうか?対応としては単純な話で、最下部のジョブbuild-and-testに使用するContext名を指定するだけです。これで実行時には環境変数が参照され想定通りのテストが実行されます。

config.yml
version: 2.1

orbs:
  python: circleci/python@0.2.1

jobs:
  build-and-test:
    executor: python/default
    steps:
~~~(中略)~~~
      - run:
          name: Run pytest
          command: pipenv run pytest --apikey $API_KEY

workflows:
  main:
    jobs:
      - build-and-test
          context:
            - LINE_BOT

補足

Contextはプロジェクトを跨いで環境変数を使い回す際に便利な機能です。プロジェクト単体でしか使用しない環境変数はプロジェクト設定の環境変数を使用することもできます。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?