자동 배포 된 인스턴스의 경우 인스턴스 ID를 모르는 상태에서 CloudWatch Alarm을 설정할 수 없습니다. 알람을 설정하는 유일한 방법은 실행중인 모든 인스턴스를 폴링하고 시작 시간과 지정된 시간을 비교하는 AWS 람다 함수를 만드는 것입니다.
람다 함수는 주기적으로 CloudWatch - Event – Rule에 의해 트리거됩니다.
tags을 사용하면 다른 시스템에 다른 실행 지속 시간을 지정할 수 있습니다. 예를 들어 실행 도구는 인스턴스에 키 값 "Test"로 태그를 지정해야합니다.
이 코드는 보증이 제공됩니다. 이것은 더 많은 예입니다.
import boto3
import datetime
import json
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
ec2_client = boto3.client('ec2')
INSTANCE_TIMEOUT = 24
MAX_PERMITTED_INSTANCES = 5
MAILING_LIST = "[email protected], [email protected]"
def parse_tag(tags, keyValuePair):
for tag in tags:
if tag['Key'] == keyValuePair[0] and tag['Value'] == keyValuePair[1]:
return True
return False
def runtimeExceeded(instance, timeOutHours):
# Working in to UTC to avoid time-travel during daylight-saving changeover
timeNow = datetime.datetime.utcnow()
instanceRuntime = timeNow - instance.launch_time.replace(tzinfo=None)
print instanceRuntime
if instanceRuntime > datetime.timedelta(hours=timeOutHours):
return True
else:
return False
def sendAlert(instance, message):
msg = MIMEMultipart()
msg['From'] = '[email protected]'
msg['To'] = MAILING_LIST
msg['Subject'] = "AWS Alert: " + message
bodyText = '\n\nThis message was sent by the AWS Monitor ' + \
'Lambda. For details see AwsConsole-Lambdas. \n\nIf you want to ' + \
'exclude an instance from this monitor, tag it ' + \
'with Key=RuntimeMonitor Value=False'
messageBody = MIMEText(message + '\nInstance ID: ' +
str(instance.instance_id) + '\nIn Availability zone: '
+ str(instance.placement['AvailabilityZone']) + bodyText)
msg.attach(messageBody)
ses = boto3.client('ses')
ses.send_raw_email(RawMessage={'Data' : msg.as_string()})
def lambda_handler(event, context):
aws_regions = ec2_client.describe_regions()['Regions']
for region in aws_regions:
runningInstancesCount = 0
try:
ec2 = boto3.client('ec2', region_name=region['RegionName'])
ec2_resource = boto3.resource('ec2',
region_name=region['RegionName'])
aws_region = region['RegionName']
instances = ec2_resource.instances.all()
for i in instances:
if i.state['Name'] == 'running':
runningInstancesCount +=1
if i.tags != None:
if parse_tag(i.tags, ('RuntimeMonitor', 'False')):
# Ignore these instances
pass
else:
if runtimeExceeded(i, INSTANCE_TIMEOUT):
sendAlert(i, "An EC2 instance has been running " + \
"for over {0} hours".format(INSTANCE_TIMEOUT))
else:
print "Untagged instence"
if runtimeExceeded(i, UNKNOWN_INSTANCE_TIMEOUT):
sendAlert(i, "An EC2 instance has been running " + \
"for over {0} hours".format(UNKNOWN_INSTANCE_TIMEOUT))
except Exception as e:
print e
continue
if runningInstancesCount > MAX_PERMITTED_INSTANCES:
sendAlert(i, "Number of running instances exceeded threshold " + \
"{0} running instances".format(runningInstancesCount))
return True
Cloudwatch 설명서를 살펴 보셨습니까? 그 (것)들은 당신이 통계를 간행하는 것을 허용하는 apis이다 – Shibashis
@Shibashis는 간행물 metrics.But에있는 미터의 논리가 정의되는 곳에 확실하지 않다 .Eg : http://docs.aws.amazon.com/cli/latest /reference/cloudwatch/put-metric-data.html, 나는 메트릭 이름 만 있고, statiscal 출력과 단위가 정의되어있다. 하지만 원하는 것은 메트릭 이름이 EC2InstanceHealthDuration (EC2 인스턴스가 시작될 때까지 실행 된 시간을 의미)이라고 가정합니다. 메트릭 이름에서 수행중인 논리에 대한 유닉스 스크립트가 있어야합니다. 같은 것을 찾을 수있는 곳을 알려주십시오. – Vasanth
cloudwatch는 통계 만 수집하고 이에 대한 경고를 생성 할 수 있습니다. 인스턴스가 얼마나 오랫동안 지속되었는지보고 스크립트를 만들어 해당 측정 항목을 cloudwatch로 푸시해야합니다. 그런 논리를 개발하고 싶지 않다면 데이터 도그, 새로운 유적, 나기 오스 등과 같은 다른 소프트웨어를 고려해야 할 수도 있습니다. – Shibashis