0
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 1 year has passed since last update.

YAMLファイルの確認ではyqを使うと便利でした

Posted at

CIやDockerなどの設定でYAMLを書く機会が増えましたが、構文を覚えられずエラーになることが多かったです。
WikipediaのYAMLの項目に詳細な内容が載っていて便利なのですが、どうしてもズレてしまったりすると構文エラーになってしまっていました。

今まで確認の際にはCIに投げたりして実際に動かしてエラー箇所を特定していましたが、yqというツールを使うとローカルで確認できるようになって便利でした。

インストール

brew install yq

使い方

yqの後に参照したい変数名、ファイル名を列挙します。

yq -o=json '.' .github/workflows/actions.yml

変数名は例えば、.nameといったようにルートからの階層構造で表されます。

actions.yml
name: actions
run-name: ${{ github.actor }} is learning GitHub Actions
on: [push]
jobs:
  check-bats-version:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - uses: actions/setup-node@v3
        with:
          node-version: '14'

      - run: curl https://api.openai.com/v1/chat/completions
      - run: >
          curl https://api.openai.com/v1/chat/completions
          -H "Content-Type: application/json"
          -H "Authorization: Bearer ${OPEN_AI_KEY}"
          -d '{"model": "gpt-3.5-turbo","messages": [{"role": "system", "content": "語尾ににゃーと付けて応答してください"}, {"role": "user", "content": "どうやってAPIで呼び出しを行ったらいいですか?"}]}'
      - run: npm install -g bats
      - run: bats -v
$ yq -o=json '.name' .github/workflows/learn-github-actions.yml

"actions"

利用例

下記のような長いコマンドの部分を文字列連結させてみました。

jobs:
  check-bats-version:
    steps:
          - run: >
          curl https://api.openai.com/v1/chat/completions
          -H "Content-Type: application/json"
          -H "Authorization: Bearer ${OPEN_AI_KEY}"
          -d '{"model": "gpt-3.5-turbo","messages": [{"role": "system", "content": "語尾ににゃーと付けて応答してください"}, {"role": "user", "content": "どうやってAPIで呼び出しを行ったらいいですか?"}]}'

この部分をyqを使うと、下記のようにひと繋ぎの文字列になっていることがわかります。

$ $ yq -o=json '.jobs.check-bats-version.steps' .github/workflows/learn-github-actions.yml

中略
  {
    "run": "curl https://api.openai.com/v1/chat/completions -H \"Content-Type: application/json\" -H \"Authorization: Bearer ${OPEN_AI_KEY}\" -d '{\"model\": \"gpt-3.5-turbo\",\"messages\": [{\"role\": \"system\", \"content\": \"語尾ににゃーと付けてください\"}, {\"role\": \"user\", \"content\": \"どうやってAPIで呼び出しを行ったらいいですか?\"}]}'\n"
  },

参考

文字列の連結ではこちらの記事が大変参考になりました。
https://zenn.dev/gekal/articles/yaml-multi-lines-string

文字列の連結がスムーズに行えるようになると、CI上で回したいコマンドを複数行に記載することができ便利でした。

0
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
0
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?