LoginSignup
0
1

PythonでAWS CLIコマンド実行の練習 (subprocess編)

Last updated at Posted at 2024-05-12

目的

PythonでAWS CLIの実行方法を覚えるために、EC2のスループット値を取得してみる

AWS CLIコマンドの確認

下記コマンドでスループット値を取得できることを確認

コマンド
aws cloudwatch get-metric-statistics \
--namespace AWS/EC2 \
--metric-name NetworkIn \
--dimensions Name=InstanceId,Value=i-085509fb0174af9cd \
--period 2628000 \
--statistics Maximum \
--start-time 2024-05-01T06:15:00+00:00 \
--end-time 2024-05-10T06:30:00+00:00
出力
[cloudshell-user@ip-10-130-39-130 ~]$ aws cloudwatch get-metric-statistics \
> --namespace AWS/EC2 \
> --metric-name NetworkIn \
> --dimensions Name=InstanceId,Value=i-085509fb0174af9cd \
> --period 2628000 \
> --statistics Maximum \
> --start-time 2024-05-01T06:15:00+00:00 \
> --end-time 2024-05-10T06:30:00+00:00
{
    "Label": "NetworkIn",
    "Datapoints": [
        {
            "Timestamp": "2024-05-01T06:15:00+00:00",
            "Maximum": 57597321.0,
            "Unit": "Bytes"
        }
    ]
}

PythonでのAWS CLIコマンド実行

subprocessモジュールを読み込んでsubprocess.run()で実行できそう

Pythonスクリプトの作成

直近3ヶ月間の最大スループット値(In/Out)を取得する

get_ec2_throughput_subprocess.py
import subprocess
import json
import time
from datetime import datetime, timedelta

def cloudwatch_get_metric(metric_name):
    # AWS CLIコマンドを構築
    command = (
        "aws cloudwatch get-metric-statistics "
        "--namespace AWS/EC2 "
        f"--metric-name {metric_name} "
        "--dimensions Name=InstanceId,Value=i-085509fb0174af9cd "
        f"--period {period} "
        "--statistics Maximum "
        f"--start-time {start_time_str} "
        f"--end-time {end_time_str}"
    )

    # AWS CLIコマンドを実行し、結果を取得
    result = subprocess.run(command, capture_output=True, text=True, shell=True)
    data = json.loads(result.stdout.strip())

    # データを処理する
    datapoints = data['Datapoints']
    maximum_values = [datapoint['Maximum'] for datapoint in datapoints]

    return maximum_values

start_script_time = time.time()

# 現在の日付から3か月前の日付を計算
end_time = datetime.utcnow()
start_time = end_time - timedelta(days=90)
period = 3600 * 24 * 90

# 日付をISO 8601形式に変換
start_time_str = start_time.strftime('%Y-%m-%dT%H:%M:%S')
end_time_str = end_time.strftime('%Y-%m-%dT%H:%M:%S')
print(f'{start_time_str=}')
print(f'{end_time_str=}')

NetworkIn = cloudwatch_get_metric('NetworkIn')[0]
NetworkOut = cloudwatch_get_metric('NetworkOut')[0]
print(f'{NetworkIn=}')
print(f'{NetworkOut=}')	

end_script_time = time.time()
elapsed_time = end_script_time - start_script_time

print(f'{elapsed_time=}')

実行

取得できました。

出力
[cloudshell-user@ip-10-130-39-130 ~]$ python get_ec2_throughput_subprocess.py 
start_time_str='2024-02-18T02:13:17'
end_time_str='2024-05-18T02:13:17'
NetworkIn=57597321.0
NetworkOut=68488705.0
elapsed_time=2.3432440757751465
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