LoginSignup
1
0

shyaml で yaml を parse して shell script で楽したい

Last updated at Posted at 2024-06-14

tldr;

shyaml を使うと yaml を shell script で parse して value を使えて楽だよ

requirements

  1. Python && pip がインストールされている
  2. shyaml がインストールされている
    • なければ pip install shyaml

shyaml の使い方

cat /path/to/my.yml | shyaml get-value path.of.my.yaml.field

example

例えば project root dir に以下の yaml があるとします。

.elasticbeanstalk/config.yml
branch-defaults:
  develop:
    environment: my-eb-env-develop
  main:
    environment: my-eb-env-main
environment-defaults:
  my-eb-env-test:
    branch: null
    repository: null
  my-eb-env-prod:
    branch: null
    repository: null
global:
  application_name: my-eb-env
  default_ec2_keyname: my-eb-env
  default_platform: hogelang on 64bit Amazon Linux
  default_region: ap-northeast-1
  include_git_submodules: true
  instance_profile: null
  platform_name: null
  platform_version: null
  profile: null
  sc: git
  workspace_type: Application

yaml を parse する shell script を書いてみる

test.sh
#!/bin/bash

# 環境の名前を設定
EB_CONFIG=".elasticbeanstalk/config.yml"
GIT_BRANCH=$(git branch --show-current)
ENV_NAME=$(cat $EB_CONFIG | shyaml get-value branch-defaults.$GIT_BRANCH.environment)
APP_NAME=$(cat $EB_CONFIG | shyaml get-value global.application_name)
REGION=$(cat $EB_CONFIG | shyaml get-value global.default_region)

echo $EB_CONFIG
echo $GIT_BRANCH
echo $ENV_NAME
echo $APP_NAME
echo $REGION

test.sh を実行してみる

validation は割愛しているけど欲しい項目の値が取得できる。

$ chmod +x test.sh

$ ./test.sh  
.elasticbeanstalk/config.yml
main
my-eb-env-main
my-eb-env
ap-northeast-1

まとめ

shyaml を使うと yaml を parse して楽して便利になるんではないかと思いました。そんじゃまた。

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