boto 3 - EC2 Linux instance - need to capture device name as variable

163 views Asked by At

I need to capture variable value for Linux EC2 instances.

'Name': 'device',
'Value': "xvdg"

The value Disk Name(device name) changes for EC2 Linux instances e.g sdh,xvdg, etc..

I am using boto3 SDK

Any help is much appreciated.

Current Code (Hard coded the Device Name):

cloudwatch.put_metric_alarm(
  AlarmName=prefix +  ' -  Elastic Search Disc % Availabilty is less than the configured threshold value - Please increase size of EBS Volume',
  ComparisonOperator='LowerThanThreshold',
  EvaluationPeriods=3,
  MetricName='disk_used_percent',
  Namespace='CWAgent',
  Period=300,
  Statistic='Average',
  Threshold=75,
  AlarmActions=[snstopicarn],
  AlarmDescription='Standard Disc Alert - Elastic Search Disc % Availabilty is less than the configured threshold value - Please increase size of EBS Volume',
  Dimensions=[
                            {
                              'Name': 'InstanceId',
                              'Value': instance["InstanceId"]
                            },

                            {
                              'Name': 'path',
                              'Value': "/mnt/elasticsearch"
                            },
                            {
                              'Name': 'device',
                              'Value': "xvdi"
                            },
                            {
                              'Name': 'fstype',
                              'Value': "ext4"
                            },
  ]
)
1

There are 1 answers

5
shimo On

You can use describe_instances and extract DeviceName. (boto3 doc)

import boto3

instance_id = <instance_id>

client = boto3.client('ec2')

response = client.describe_instances(
    InstanceIds=[
        instance_id,
    ],
)

device_name = response['Reservations'][0]['Instances'][0]['BlockDeviceMappings'][0]['DeviceName']

#/dev/xvda
print(device_name)

When using describe_alarms_for_metric, the code would be like this.

response = client.describe_alarms_for_metric(
    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'
)
response = cloudwatch.put_metric_alarm(....)

for i in response['MetricAlarms'][0]['Dimensions'][0]:
    if i['Name'] == 'device':
        print(i['Value'])  # xvdi