JSON出力から一部を取り出したいとき、いつも困っているのでメモ
練習のために、CloudFormationのCLIコマンド出力をtmp.json
	に保存して使います。
{
    "Stacks":  [
        {
            "StackId": "arn:aws:cloudformation:us-east-1:123456789012:stack/myteststack/466df9e0-0dff-08e3-8e2f-5088487c4896",
            "Description": "AWS CloudFormation Sample Template S3_Bucket: Sample template showing how to create a publicly accessible S3 bucket. **WARNING** This template creates an S3 bucket. You will be billed for the AWS resources used if you create a stack from this template.",
            "Tags": [],
            "Outputs": [
                {
                    "Description": "Name of S3 bucket to hold website content",
                    "OutputKey": "BucketName",
                    "OutputValue": "myteststack-s3bucket-jssofi1zie2w"
                }
            ],
            "StackStatusReason": null,
            "CreationTime": "2013-08-23T01:02:15.422Z",
            "Capabilities": [],
            "StackName": "myteststack",
            "StackStatus": "CREATE_COMPLETE",
            "DisableRollback": false
        }
    ]
}
一行だけを抜き出したい
OutputValue がある行を抜き出します。
grep -o '"OutputValue": "[^"]*' tmp.json | grep -o '[^"]*$'
'"OutputValue": "[^"]*' の部分で "OutputValue... の部分にマッチして(最後の"の手前まで)、
grep -o '[^"]*$' の部分で最初の " を削除しています。
一ブロックを抜き出したい
"Outputs" のブロックを抜き出します。中身を見ながらコマンドを作る必要があります。
a="$(cat tmp.json)" として、jsonの中身を変数aに入れておきます。 echo $a で確認できます。ここからネストした部分を切り出していきます。
echo $a | jq -r '.Stacks[0]'
で Stacks の1番目が見れます。
さらにOutputsを抜き出すには、こうなります。
echo $a | jq -r '.Stacks[0].Outputs[0]'
最終的に、cliコマンドの結果から繋げて直接見たいときは
aws cloudformation describe-stacks --stack-name aaaabbbbcccc | jq -r '.Stacks[0].Outputs[0]'
などとなります。
参考
https://stackoverflow.com/questions/36073695/how-to-retrieve-single-value-with-grep-from-json
https://unix.stackexchange.com/questions/597368/grep-print-value-of-a-key-in-json-that-is-stored-in-a-variable