lework 5 years ago
parent
commit
af43483509
  1. 1269
      cloud/aws/lambda/addAlarm.py
  2. 83
      cloud/aws/lambda/delAlarm.py
  3. 77
      cloud/aws/lambda/wechat.py

1269
cloud/aws/lambda/addAlarm.py

File diff suppressed because it is too large Load Diff

83
cloud/aws/lambda/delAlarm.py

@ -0,0 +1,83 @@
import boto3
import json
cloudwatch = boto3.client('cloudwatch')
def del_alarm(type, name_prefix):
print("[delete %s alarm.]" % type)
rep = cloudwatch.describe_alarms(AlarmNamePrefix=name_prefix, )
alarm_names = []
for m in rep.get('MetricAlarms'):
alarm_names.append(m.get('AlarmName'))
response = cloudwatch.delete_alarms(
AlarmNames=alarm_names
)
print('alarm_names', alarm_names)
print('response', response)
def del_dashboards(type, name_prefix):
print("[delete %s dashboards.]" % type)
rep = cloudwatch.list_dashboards(DashboardNamePrefix=name_prefix)
dashboard_names = []
for m in rep.get('DashboardEntries'):
dashboard_names.append(m.get('DashboardName'))
response = cloudwatch.delete_dashboards(
DashboardNames=dashboard_names
)
print('dashboard_names', dashboard_names)
print('response', response)
def lambda_handler(event, context):
# TODO implement
print(event)
detail = event.get('detail', {})
event_source = detail.get('eventSource')
event_name = detail.get('eventName')
event_response = detail.get('responseElements', {})
if event_source == 'ec2.amazonaws.com':
if event_name == 'TerminateInstances':
instances = event_response.get('instancesSet', {})
for item in instances.get('items', []):
instance_id = item.get('instanceId')
if instance_id:
del_alarm('ec2', 'AWS_EC2_%s' % instance_id)
del_dashboards('ec2', 'AWS_EC2_%s' % instance_id)
elif event_source == 'rds.amazonaws.com':
if event_name == 'DeleteDBInstance':
dBInstanceIdentifier = event_response.get('dBInstanceIdentifier')
engine = event_response.get('engine')
if engine == 'mysql':
del_alarm('mysql', 'AWS_MYSQL_%s' % dBInstanceIdentifier)
del_dashboards('mysql', 'AWS_MYSQL_%s' % dBInstanceIdentifier)
elif event_source == 'elasticache.amazonaws.com':
if event_name == 'DeleteReplicationGroup':
group_id = event_response.get('replicationGroupId')
del_alarm('redis', 'AWS_REDIS_%s' % group_id)
del_dashboards('redis', 'AWS_REDIS_%s' % group_id)
elif event_source == 'elasticloadbalancing.amazonaws.com':
if event_name == 'DeleteLoadBalancer':
requestParameters = detail.get('requestParameters', {})
loadBalancerArn = requestParameters.get('loadBalancerArn')
instance_name = loadBalancerArn.split(':loadbalancer/')[1].split('/')[1]
del_alarm('elb', 'AWS_ELB_%s' % instance_name)
del_dashboards('elb', 'AWS_ELB_%s' % instance_name)
return {
'statusCode': 200,
'body': json.dumps('add success.')
}

77
cloud/aws/lambda/wechat.py

@ -0,0 +1,77 @@
import json
from botocore.vendored import requests
def lambda_handler(event, context):
# TODO implement
url = "https://qyapi.weixin.qq.com"
corpid = ""
secret = ""
agentid = ""
touser = ''
toparty = ''
totag = ''
headers={
'Content-Type':'application/json'
}
access_token_url = '{url}/cgi-bin/gettoken?corpid={id}&corpsecret={crt}'.format(url=url, id=corpid, crt=secret)
access_token_response = requests.get(url=access_token_url, headers=headers)
token = json.loads(access_token_response.text)['access_token']
send_url = '{url}/cgi-bin/message/send?access_token={token}'.format(url=url, token=token)
message = event['Records'][0]['Sns']
Timestamp = message['Timestamp']
Subject = message['Subject']
sns_message = json.loads(message['Message'])
region = message['TopicArn'].split(':')[-3]
state_exclude = ['INSUFFICIENT_DATA']
if sns_message['OldStateValue'] in state_exclude:
return
if "ALARM" in Subject:
title='<font color=\"info\">[aws] 警报!!警报!!</font>'
elif "OK" in Subject:
title='<font color=\"info\">[aws] 故障恢复</font>'
else:
title='<font color=\"info\">[aws]</font>'
content = title \
+ "\n> **详情信息**" \
+ "\n> 时间: " + Timestamp \
+ "\n> 内容: " + Subject \
+ "\n> 状态: <font color=\"comment\">{old}</font> => <font color=\"warning\">{new}</font>".format(old=sns_message['OldStateValue'], new=sns_message['NewStateValue']) \
+ "\n> " \
+ "\n> Region: " + sns_message['Region'] \
+ "\n> Namespace: " + sns_message['Trigger']['Namespace'] \
+ "\n> MetricName: " + sns_message['Trigger']['MetricName'] \
+ "\n> " \
+ "\n> AlarmName: " + sns_message['AlarmName'] \
+ "\n> AlarmDescription: " + sns_message['AlarmDescription'] \
+ "\n> " \
+ "\n> 详情请点击:[Alarm](https://{region}.console.amazonaws.cn/cloudwatch/home?region={region}#s=Alarms&alarm={alarm})".format(region=region, alarm=sns_message['AlarmName'])
msg = {
"msgtype": 'markdown',
"agentid": agentid,
"markdown": {'content': content },
"safe": 0
}
if touser:
msg['touser'] = touser
if toparty:
msg['toparty'] = toparty
if toparty:
msg['totag'] = totag
response = requests.post(url=send_url, data=json.dumps(msg), headers=headers)
errcode = json.loads(response.text)['errcode']
if errcode == 0:
print('Succesfully')
else:
print(response.json())
print('Failed')
Loading…
Cancel
Save