私はSEとして働いておりますが、普段は自動テストとは無縁の仕事をしています。ただし、プライベートで作業をする時はテストを自動化しており、CIツールとしてCircleCIを使用しています。
そのCircleCIにはContextという、環境変数をCircleCI内にあらかじめ設定しておく機能があり、APIキーなどソースコードに含めると危険なものに関しては別途管理できます。ただし、自分はそれを利用する際に変数がなぜか参照できないという事態に陥ったので今回はその解決方法について記事にします。
前提
Contextの設定値は以下の通り。
Context名:LINE_BOT
環境変数名:API_KEY
修正前
以下が修正前のconfig.yml
(CircleCIの設定ファイル)になります。
command
の行に$API_KEY
とありますが、なんど実行してもこの値は空になります。
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名を指定するだけです。これで実行時には環境変数が参照され想定通りのテストが実行されます。
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はプロジェクトを跨いで環境変数を使い回す際に便利な機能です。プロジェクト単体でしか使用しない環境変数はプロジェクト設定の環境変数を使用することもできます。