LoginSignup
0
0

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

Posted at

目的

上記ではsubprocess.runでAWS CLIコマンドを実行していたが、boto3に変更してみる

Pythonスクリプトの作成

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

get_ec2_throughput_boto3.py
import boto3
import json
import time
from datetime import datetime, timedelta

def cloudwatch_get_metric(metric_name):
    # boto3クライアントを作成
    cloudwatch = boto3.client('cloudwatch')

    # CloudWatchからメトリクスデータを取得
    response = cloudwatch.get_metric_statistics(
        Namespace='AWS/EC2',
        MetricName=metric_name,
        Dimensions=[
            {
                'Name': 'InstanceId',
                'Value': 'i-085509fb0174af9cd'
            },
        ],
        StartTime=start_time,
        EndTime=end_time,
        Period=period,
        Statistics=['Maximum']
    )

    # データを処理する
    datapoints = response['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] if cloudwatch_get_metric('NetworkIn') else None
NetworkOut = cloudwatch_get_metric('NetworkOut')[0] if cloudwatch_get_metric('NetworkOut') else None
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_boto3.py 
start_time_str='2024-02-18T02:25:34'
end_time_str='2024-05-18T02:25:34'
NetworkIn=57597321.0
NetworkOut=68488705.0
elapsed_time=0.5444772243499756

subprocess.runでの実行時間は2.34秒だったので、1.8秒短くなりました。

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