aws中國區(qū)目前并沒有提供批量添加告警的功能,需要通過cli編寫程序的方式來實(shí)現(xiàn)圆恤。
說明:
1.需要部署aws cli并配置權(quán)限突倍。
2.此腳本基于python3環(huán)境
#!/usr/bin/python
# -*- coding: utf-8 -*-
import json
import subprocess
# 1. 配置cli路徑和region
Contants = {
"AWSCLI": '"aws" --output json',
"AWSREGION": ['cn-north-1'] # 北京
}
# 構(gòu)造字典
class CreateDict(dict):
def __getitem__(self, item):
try:
return dict.__getitem__(self, item)
except KeyError:
value = self[item] = type(self)()
return value
#########################################################################################################
# 配置告警
# CPUUtilization,3分鐘檢查3次,平均值大于或等于80%盆昙,就告警羽历。
def getCPUUtilizationComm(name, action, instance_id):
mertic = 'CPUUtilization'
print("#####開始配置 %s#####" % mertic)
return '''{cli} cloudwatch put-metric-alarm \
--alarm-name "AWS_EC2_{name}_{mertic}" \
--alarm-description "aws ec2 {mertic}" \
--metric-name {mertic} \
--namespace AWS/EC2 \
--statistic Average \
--period 60 \
--threshold 70 \
--evaluation-periods 3 \
--datapoints-to-alarm 3 \
--comparison-operator GreaterThanOrEqualToThreshold \
--treat-missing-data notBreaching \
--alarm-actions "{action}" \
--ok-actions "{action}" \
--unit Percent \
--dimensions "Name=InstanceId,Value={id}"'''.format(cli=Contants['AWSCLI'], name=name, action=action, id=instance_id, mertic=mertic)
# 執(zhí)行命令函數(shù)
def execCommand(comm):
try:
print(comm)
(status, stdout) = subprocess.getstatusoutput(comm)
print(status)
return stdout
except Exception as e:
print(e)
# 獲取當(dāng)前可用區(qū)內(nèi)所有ec2的基礎(chǔ)信息
def getAll():
comm1 = "%s ec2 describe-instances" % Contants['AWSCLI']
all_data = json.loads(execCommand(comm1))
instance_list = []
for r in all_data['Reservations']:
for i in r['Instances']:
data = {'id': i['InstanceId']}
for t in i['Tags']:
if t['Key'] == 'Name':
data['name'] = t['Value']
if not data['name']:
data['name'] = i['InstanceId']
instance_list.append(data)
return instance_list
# 添加報(bào)警
def add_alert(data, action):
for i in data:
instance_id = i['id']
name = i['name']
execCommand(getCPUUtilizationComm(name, action, instance_id))
if __name__ == '__main__':
# 2. 配置sns的arn
sns_arn = "arn:*****:rds_alert1"
cli = Contants['AWSCLI']
for i in Contants['AWSREGION']:
print('[Region] ', i)
Contants['AWSCLI'] = cli + ' --region ' + i
add_alert(getAll(), sns_arn)