AWSのコストがなんか不安 その2

2020-4-15 - 読み終える時間: 2 分

Cost usage reportを自動取得するスクリプト(Windowsバッチ)

別にWindowsでやる必要はないな。インスタンスのお値段高くなるし。

でも書いた。

コード

@echo off

REM Cost report 取得スクリプト

REM Requiere::
REM jq-windows <https://stedolan.github.io/jq/download/>
REM AWS Cli V2 Windows <https://docs.aws.amazon.com/ja_jp/cli/latest/userguide/install-cliv2-windows.html>

REM list_file format::
REM profile,bucket-name,Manifest-file-name

setlocal enabledelayedexpansion

set script_name=%~n0
set script_dir=%~dp0
set log_dir=%script_dir%\log

if not exist %log_dir%\ md "%log_dir%"

set list_file=%script_name%.list

pushd %script_dir%

REM 年月切り出し
set year_now=%date:~0,4%
set month_now=%date:~5,2%

set /a month_tmp=%month_now%-1
if %month_tmp% EQU 0 (
    set month_previous=12
    set /a year_previous=%year_now%-1
) else (
    if %month_tmp% LEQ 9 (
        set month_previous=0%month_tmp%
        set year_previous=%year_now%
    ) else (
    set month_previous=%month_tmp%
    set year_previous=%year_now%
    )
)

set S3folder_name=%year_previous%%month_previous%01-%year_now%%month_now%01

for /f "eol=# tokens=1,2,3 delims=," %%e in (%list_file%) do (
    echo ==========
    echo %%e
    echo %%f
    echo %%g
    echo ==========
    echo !S3folder_name!
    echo ==========

    set prfile_name=%%e
    set bucket_name=%%f
    set manifest_filename=%%g

    aws --profile !prfile_name! s3api list-objects-v2 --bucket !bucket_name! | jq ".Contents[].Key" | findstr "!S3folder_name!/!manifest_filename!" > !log_dir!\!prfile_name!-manifest.tmp

    for /f "usebackq delims=" %%h in (`type !log_dir!\!prfile_name!-manifest.tmp`) do set manifest_key=%%~h

    set getdir_path=C:\work\CUR-!year_previous!!month_previous!\!prfile_name!
    md !getdir_path!

    aws --profile !prfile_name! s3api get-object --bucket !bucket_name! --key !manifest_key! !log_dir!\!prfile_name!-CUR-path.tmp
    jq ".reportKeys" !log_dir!\!prfile_name!-CUR-path.tmp > !log_dir!\!prfile_name!-CUR-path-line.tmp

    for /f "usebackq delims=" %%i in (`findstr !S3folder_name! !log_dir!\!prfile_name!-CUR-path-line.tmp`) do set CUR_key=%%~i

    REM get CUR
    aws --profile !prfile_name! s3api get-object --bucket !bucket_name! --key !CUR_key! "!getdir_path!\!S3folder_name!_!prfile_name!_CUR.gz"
)

exit /b

今日はここまで