AWS CLI のデバッグログをファイルへ出力する方法を教えてください

AWS CLI の --debug オプション結果は標準エラー出力から取得できます。
2021.12.11

この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。

この記事はアノテーション株式会社 AWS Technical Support Advent Calendar 2021のカレンダー | Advent Calendar 2021 - Qiita 11日目の記事です。

困っていた内容

AWS CLI を使ったトラブルシューティングを行うため--debugオプションを付けてデバッグを行っています。

コマンドの出力結果をターミナルからコピー & ペーストしていたのですが、ログ量が多く辛いため、ファイルに出力しようと考えています。

出力結果をファイルへリダイレクトしたのですが、結果は何も表示されません。

AWS CLI のデバッグ結果をファイルへ出力するにはどう対応したらいいのでしょうか?

どう対応すればいいの?

AWS CLI で--debugオプションを指定した場合の実行結果は、標準エラー出力から取得できます。

シンプルな方法

もっともシンプルなリダイレクト方法は以下のようになります。

$ aws s3 ls s3://not-exists-bucket --debug 2> result.txt

※「aws s3 ls s3://not-exists-bucket」の箇所は任意のコマンドです。

取得結果は以下のようになります。

result.txt

2021-12-10 19:31:30,936 - MainThread - awscli.clidriver - DEBUG - CLI version: aws-cli/2.1.19 Python/3.7.4 Darwin/20.6.0 exe/x86_64
2021-12-10 19:31:30,937 - MainThread - awscli.clidriver - DEBUG - Arguments entered to CLI: ['s3', 'ls', 's3://not-exists-bucket', '--debug']
2021-12-10 19:31:30,992 - MainThread - botocore.hooks - DEBUG - Event building-command-table.main: calling handler 
...(省略)

上記の方法ではコマンド実行時のターミナル上に何も結果が出力されません。

tee コマンドを使ってファイルとターミナルへ同時に結果をする方法

コマンド実行結果を見ながらファイルにも出力したい場合は、標準出力と標準エラー出力をteeコマンドへ繋ぐと期待する結果が得られます。

$ aws s3 ls s3://not-exists-bucket --debug 2>&1 | tee result.txt
2021-12-10 19:40:38,051 - MainThread - awscli.clidriver - DEBUG - CLI version: aws-cli/2.1.19 Python/3.7.4 Darwin/20.6.0 exe/x86_64
2021-12-10 19:40:38,052 - MainThread - awscli.clidriver - DEBUG - Arguments entered to CLI: ['s3', 'ls', 's3://not-exists-bucket', '--debug']
2021-12-10 19:40:38,111 - MainThread - botocore.hooks - DEBUG - Event building-command-table.main: calling handler <function add_s3 at 0x7fa7480465f0>
...(省略)

$ cat result.txt | head -n 3
2021-12-10 19:40:38,051 - MainThread - awscli.clidriver - DEBUG - CLI version: aws-cli/2.1.19 Python/3.7.4 Darwin/20.6.0 exe/x86_64
2021-12-10 19:40:38,052 - MainThread - awscli.clidriver - DEBUG - Arguments entered to CLI: ['s3', 'ls', 's3://not-exists-bucket', '--debug']
2021-12-10 19:40:38,111 - MainThread - botocore.hooks - DEBUG - Event building-command-table.main: calling handler <function add_s3 at 0x7fa7480465f0>

運用観点でのワンポイント

運用では調査のためにデバッグログのファイルを取得する機会が多々あります。

AWS CLI は検証の手軽さからデバッグを行う機会も多いはずですので、ログファイルの取得方法をしっかりと抑えておきましょう。

参考資料