CircleCIのAPIでパラメータを指定して実行する方法です。cURL等の外部コマンドを利用してJobにパラメータを渡し柔軟にJobを実行する事が可能になります。
CircleCIの設定
プロジェクトの設定
プロジェクト → Advanced Settings で Enable pipelines が On になっている事を確認します。初期設定では On になっています。
APIトークンの発行
- CircleCIの管理画面で自分のアイコンをクリック
- User Settings をクリック
- Personal API Tokens をクリック
- Create New Token をクリックしてトークンを作成する


API経由でJobを実行する
サンプルYAML
version: 2.1
parameters:
messages:
type: string
default: ""
jobs:
build:
docker:
- image: circleci/node
steps:
- checkout
- run:
command: |
echo "<< pipeline.parameters.messages >>"
workflows:
version: 2.1
workflow:
jobs:
- build
実行コマンド
curl -u [circleci-api-token]:
-X POST
-H "Content-Type: application/json"
-d '{"branch":"[branch_name]",
"parameters":
{"messages": "hello,world!"}
}'
https://circleci.com/api/v2/project/gh/[github_project_name]/[github_repo_name]/pipeline
実行結果

コマンド解説解説
circleci-api-token
- 末尾に「:」を付与する事でパスワードの入力をスキップさせます。
ブランチ、パラメータ
現在のAPI v2の仕様だとリビジョンは指定できないみたい?です。ブランチ名を指定します。パラメータを指定する場合は{"パラメータ名1":"値1", "パラメータ名2":"値2",...}の形式になります。
APIバージョン
1.1ではなく2を利用します。CircleCIの Using the API to Trigger Jobs - CircleCI を参考にするとversion 1.1のAPIリファレンスにリンクが貼ってあります。
version 1.1では動かないので必ず version2のリファレンス を参考にします。
その他
Contextsについて
Contexts (プロジェクト全体の環境変数を設定する機能)で指定した環境変数もJobに反映されます。
Commands, Orbsについて
config.ymlに commands セクション、 orbs セクションが含まれていてもAPIからJobは実行されます。
例えば以下のようなconfig.ymlでも動作確認できました。APIからGoogle Compute Engineにインスタンスを起動し起動が成功したらTwitterのダイレクトメッセージに通知する処理です。
version: 2.1
orbs:
gcp-cli: circleci/gcp-cli@1.8.3
parameters:
instance-name:
type: string
default: ""
commands:
initialize-gce:
description: "Register GCP access keys to CircleCI project"
steps:
- gcp-cli/initialize
start-vm:
steps:
- run:
command: |
gcloud compute instances start << pipeline.parameters.instance-name >> \
--zone=asia-northeast1-b
send-notification:
description: "Send job status to Twitter direct message"
steps:
- run:
name: Set external IP address to environment variable
command: |
ip_addr=$(
gcloud compute instances describe << pipeline.parameters.instance-name >> \
--format='get(networkInterfaces[0].accessConfigs[0].natIP)' \
--zone=asia-northeast1-b \
)
echo "export INSTANCE_IP=${ip_addr}" >> $BASH_ENV
- run:
name: Install Tweepy
command: |
pip install tweepy
- run:
name: Send Job notifcation
command: |
python tweet.py \
${TWITTER_CONSUMER_KEY} \
${TWITTER_CONSUMER_SECRET_KEY} \
${TWITTER_ACCESS_TOKEN} \
${TWITTER_ACCESS_TOKEN_SECRET} \
${TWITTER_RECIPIENT}
jobs:
build:
docker:
- image: google/cloud-sdk:latest
steps:
- checkout
- initialize-gce
- start-vm
- send-notification
workflows:
version: 2.1
start-vm:
jobs:
- build:
context: GCP