Open5
【実務で使えるLambda】(EC2)describe_instancesで色々やってみる
インスタンスIDをリストで取得してみる
とりあえずこれをコピペすればOK
import boto3
ec2_client = boto3.client('ec2', region_name='ap-northeast-1') # リージョンは任意
instances = ec2_client.describe_instances()
instance_ids = [] # 空のリストを用意
for reservations in instances['Reservations']:
for instance in reservation['Instances']:
instance_id = instance['InstanceId']
instance_ids.append(instance_id)
describe_instancesで取得できるデータ(instances)の形式
{
'Reservations': [
{
'Groups': [
{
'GroupName': 'string',
'GroupId': 'string'
},
],
'Instances': [
{
'AmiLaunchIndex': 123,
'ImageId': 'string',
'InstanceId': 'string',
'InstanceType': 'string',
'KernelId': 'string',
'KeyName': 'string',
'LaunchTime': datetime(2015, 1, 1),
'Monitoring': {
'State': 'disabled'|'disabling'|'enabled'|'pending'
},
'Placement': {
'AvailabilityZone': 'string',
'Affinity': 'string',
'GroupName': 'string',
'PartitionNumber': 123,
'HostId': 'string',
'Tenancy': 'default'|'dedicated'|'host',
'SpreadDomain': 'string',
'HostResourceGroupArn': 'string',
'GroupId': 'string'
},
'Platform': 'Windows',
'PrivateDnsName': 'string',
'PrivateIpAddress': 'string',
'ProductCodes': [
{
'ProductCodeId': 'string',
'ProductCodeType': 'devpay'|'marketplace'
},
],
'PublicDnsName': 'string',
'PublicIpAddress': 'string',
'RamdiskId': 'string',
'State': {
'Code': 123,
'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped'
},
'StateTransitionReason': 'string',
'SubnetId': 'string',
'VpcId': 'string',
'Architecture': 'i386'|'x86_64'|'arm64'|'x86_64_mac'|'arm64_mac',
'BlockDeviceMappings': [
{
'DeviceName': 'string',
'Ebs': {
'AttachTime': datetime(2015, 1, 1),
'DeleteOnTermination': True|False,
'Status': 'attaching'|'attached'|'detaching'|'detached',
'VolumeId': 'string',
'AssociatedResource': 'string',
'VolumeOwnerId': 'string'
}
},
],
'ClientToken': 'string',
'EbsOptimized': True|False,
'EnaSupport': True|False,
'Hypervisor': 'ovm'|'xen',
'IamInstanceProfile': {
'Arn': 'string',
'Id': 'string'
},
'InstanceLifecycle': 'spot'|'scheduled'|'capacity-block',
'ElasticGpuAssociations': [
{
'ElasticGpuId': 'string',
'ElasticGpuAssociationId': 'string',
'ElasticGpuAssociationState': 'string',
'ElasticGpuAssociationTime': 'string'
},
],
'ElasticInferenceAcceleratorAssociations': [
{
'ElasticInferenceAcceleratorArn': 'string',
'ElasticInferenceAcceleratorAssociationId': 'string',
'ElasticInferenceAcceleratorAssociationState': 'string',
'ElasticInferenceAcceleratorAssociationTime': datetime(2015, 1, 1)
},
],
'NetworkInterfaces': [
{
'Association': {
'CarrierIp': 'string',
'CustomerOwnedIp': 'string',
'IpOwnerId': 'string',
'PublicDnsName': 'string',
'PublicIp': 'string'
},
'Attachment': {
'AttachTime': datetime(2015, 1, 1),
'AttachmentId': 'string',
'DeleteOnTermination': True|False,
'DeviceIndex': 123,
'Status': 'attaching'|'attached'|'detaching'|'detached',
'NetworkCardIndex': 123,
'EnaSrdSpecification': {
'EnaSrdEnabled': True|False,
'EnaSrdUdpSpecification': {
'EnaSrdUdpEnabled': True|False
}
}
},
'Description': 'string',
'Groups': [
{
'GroupName': 'string',
'GroupId': 'string'
},
],
'Ipv6Addresses': [
{
'Ipv6Address': 'string',
'IsPrimaryIpv6': True|False
},
],
'MacAddress': 'string',
'NetworkInterfaceId': 'string',
'OwnerId': 'string',
'PrivateDnsName': 'string',
'PrivateIpAddress': 'string',
'PrivateIpAddresses': [
{
'Association': {
'CarrierIp': 'string',
'CustomerOwnedIp': 'string',
'IpOwnerId': 'string',
'PublicDnsName': 'string',
'PublicIp': 'string'
},
'Primary': True|False,
'PrivateDnsName': 'string',
'PrivateIpAddress': 'string'
},
],
'SourceDestCheck': True|False,
'Status': 'available'|'associated'|'attaching'|'in-use'|'detaching',
'SubnetId': 'string',
'VpcId': 'string',
'InterfaceType': 'string',
'Ipv4Prefixes': [
{
'Ipv4Prefix': 'string'
},
],
'Ipv6Prefixes': [
{
'Ipv6Prefix': 'string'
},
],
'ConnectionTrackingConfiguration': {
'TcpEstablishedTimeout': 123,
'UdpStreamTimeout': 123,
'UdpTimeout': 123
}
},
],
'OutpostArn': 'string',
'RootDeviceName': 'string',
'RootDeviceType': 'ebs'|'instance-store',
'SecurityGroups': [
{
'GroupName': 'string',
'GroupId': 'string'
},
],
'SourceDestCheck': True|False,
'SpotInstanceRequestId': 'string',
'SriovNetSupport': 'string',
'StateReason': {
'Code': 'string',
'Message': 'string'
},
'Tags': [
{
'Key': 'string',
'Value': 'string'
},
],
'VirtualizationType': 'hvm'|'paravirtual',
'CpuOptions': {
'CoreCount': 123,
'ThreadsPerCore': 123,
'AmdSevSnp': 'enabled'|'disabled'
},
'CapacityReservationId': 'string',
'CapacityReservationSpecification': {
'CapacityReservationPreference': 'open'|'none',
'CapacityReservationTarget': {
'CapacityReservationId': 'string',
'CapacityReservationResourceGroupArn': 'string'
}
},
'HibernationOptions': {
'Configured': True|False
},
'Licenses': [
{
'LicenseConfigurationArn': 'string'
},
],
'MetadataOptions': {
'State': 'pending'|'applied',
'HttpTokens': 'optional'|'required',
'HttpPutResponseHopLimit': 123,
'HttpEndpoint': 'disabled'|'enabled',
'HttpProtocolIpv6': 'disabled'|'enabled',
'InstanceMetadataTags': 'disabled'|'enabled'
},
'EnclaveOptions': {
'Enabled': True|False
},
'BootMode': 'legacy-bios'|'uefi'|'uefi-preferred',
'PlatformDetails': 'string',
'UsageOperation': 'string',
'UsageOperationUpdateTime': datetime(2015, 1, 1),
'PrivateDnsNameOptions': {
'HostnameType': 'ip-name'|'resource-name',
'EnableResourceNameDnsARecord': True|False,
'EnableResourceNameDnsAAAARecord': True|False
},
'Ipv6Address': 'string',
'TpmSupport': 'string',
'MaintenanceOptions': {
'AutoRecovery': 'disabled'|'default'
},
'CurrentInstanceBootMode': 'legacy-bios'|'uefi'
},
],
'OwnerId': 'string',
'RequesterId': 'string',
'ReservationId': 'string'
},
],
'NextToken': 'string'
}
インスタンスに付いているタグ名をリストで取得してみる
さっき取得したinstance_ids
を使う
tag_names = []
for instance_id in instance_ids:
tags_info = ec2_client.describe_instances(
Filters = [
{
'Name' : 'tag-key',
'Values' : ['Name']
},
{
'Name' : 'instance-id',
'Values' : [instance_id]
}
]
)['Reservations'][0]['Instances'][0]['Tags']
for res in tags_info:
if res['Key'] == "Name":
tag_name = res['Value']
tag_names.append(tag_name)
リスト取得したインスタンスIDに対して「停止」「起動」をする
instance_ids
を使う
# 停止
ec2_client.stop_instances(InstanceIds=instance_ids)
# 起動
ec2_client.start_instances(InstanceIds=instance_ids)
(CloudWatch)describe_alarmsを組み合わせて、設定されているCloudWatchアラーム一覧を取得してみる
instance_ids
を使う
cw_client = boto3.client('cloudwatch', region_name='ap-northeast-1')
for instance_id in instance_ids:
tags_info = ec2_client.describe_instances(
Filters = [
{
'Name' : 'tag-key',
'Values' : ['Name']
},
{
'Name' : 'instance-id',
'Values' : [instance_id]
}
]
)['Reservations'][0]['Instances'][0]['Tags']
for res in tags_info:
if res['Key'] == "Name":
tag_name = res['Value']
alarm_list = cw_client.describe_alarms(
AlarmNamePrefix = tag_name
)['MetricAlarms']
取得できるデータの形式
'MetricAlarms': [
{
'AlarmName': 'string',
'AlarmArn': 'string',
'AlarmDescription': 'string',
'AlarmConfigurationUpdatedTimestamp': datetime(2015, 1, 1),
'ActionsEnabled': True|False,
'OKActions': [
'string',
],
'AlarmActions': [
'string',
],
'InsufficientDataActions': [
'string',
],
'StateValue': 'OK'|'ALARM'|'INSUFFICIENT_DATA',
'StateReason': 'string',
'StateReasonData': 'string',
'StateUpdatedTimestamp': datetime(2015, 1, 1),
'MetricName': 'string',
'Namespace': 'string',
'Statistic': 'SampleCount'|'Average'|'Sum'|'Minimum'|'Maximum',
'ExtendedStatistic': 'string',
'Dimensions': [
{
'Name': 'string',
'Value': 'string'
},
],
'Period': 123,
'Unit': 'Seconds'|'Microseconds'|'Milliseconds'|'Bytes'|'Kilobytes'|'Megabytes'|'Gigabytes'|'Terabytes'|'Bits'|'Kilobits'|'Megabits'|'Gigabits'|'Terabits'|'Percent'|'Count'|'Bytes/Second'|'Kilobytes/Second'|'Megabytes/Second'|'Gigabytes/Second'|'Terabytes/Second'|'Bits/Second'|'Kilobits/Second'|'Megabits/Second'|'Gigabits/Second'|'Terabits/Second'|'Count/Second'|'None',
'EvaluationPeriods': 123,
'DatapointsToAlarm': 123,
'Threshold': 123.0,
'ComparisonOperator': 'GreaterThanOrEqualToThreshold'|'GreaterThanThreshold'|'LessThanThreshold'|'LessThanOrEqualToThreshold'|'LessThanLowerOrGreaterThanUpperThreshold'|'LessThanLowerThreshold'|'GreaterThanUpperThreshold',
'TreatMissingData': 'string',
'StateTransitionedTimestamp': datetime(2015, 1, 1)
},
]
CloudWatchアラーム設定されている特定期間のメトリクスを取得してみる
import datetime
from dateutil.relativedelta import relativedelta
alarm_values = []
for instance_id in instance_ids:
tags_info = ec2_client.describe_instances(
Filters = [
{
'Name' : 'tag-key',
'Values' : ['Name']
},
{
'Name' : 'instance-id',
'Values' : [instance_id]
}
]
)['Reservations'][0]['Instances'][0]['Tags']
for res in tags_info:
if res['Key'] == "Name":
tag_name = res['Value']
alarm_list = cw_client.describe_alarms(
AlarmNamePrefix = tag_name
)['MetricAlarms']
for alarmList in alarm_list:
values_list = []
alarm_value = cw_client.get_metric_statistics(
Namespace = alarmList['Namespace'],
MetricName = alarmList['MetricName'],
Dimensions = alarmList['Dimensions'],
StartTime = datetime.datetime.now() - relativedelta(days=1) + datetime.timedelta(hours=9),
EndTime = datetime.datetime.now() + datetime.timedelta(hours=9),
Period = 1800,
Statistics = [
'Maximum',
]
)
if len(alarm_value) != 0:
for value in alarm_value['Datapoints']:
values_list.append(value['Maximum'])
# print(value['Maximum'])
alarm_values.append(values_list)
print(alarm_values)
取得データ
[[0.344827586207367,
0.491803278688077,
0.508474576270724,
0.500000000000303,
0.33898305084792,
0.500000000000303,
0.499999999999545,
0.344827586207367,
0.508474576270724,
0.508474576271495,
0.344827586206583,
0.33898305084792,
0.508474576271495,
0.344827586206583,
0.344827586206583,
0.508474576270724,
0.33898305084792,
0.508474576270724,
0.500000000000303,
0.508474576271495,
0.499999999999545,
1.83333333333394,
0.500000000000303,
0.344827586206583,
0.344827586206583,
0.508474576271495,
0.500000000000303,
0.344827586206583,
0.66666666666606,
0.508474576270724]]