AWS发邮件:
进入SNS服务,创建topic --> subscribe to topic --> protocol 选email,填写自己的email。完。
CloudWatch:
- Metric —> ec2 --> Per Instance Metrics–> search metrics for example: CPUUtilization --> Tag : Graph Metrics --> select the BELL --> input info and select the SNS topic.
- Event --> rules --> create rules --> schedule(定时) OR Event Pattern (如选取ec2stop了发消息)–> Target–> select the SNS topic–> save.
Lambda :
- create function --> deploy -->run Test
- If show permission error–> Configure–> Permission —> add policy, like sns/ec2 permissions
- Trigger --> select CloudWatch–>rule/metric
Below is the code:
import json
import boto3
def lambda_handler(event, context):
# TODO implement
ec2_cli = boto3.client('ec2','us-west-2')
f_prod_bk = {'Name': 'tag:Prod', 'Values':['Backup', 'backup'] }
paginator = ec2_cli.get_paginator('describe_volumes')
list_val_ids = []
for page in paginator.paginate(Filters=[f_prod_bk]):
print(page)
for vol in page['Volumes']:
list_val_ids.append(vol['VolumeId'])
print('Volumes Ids: {}'.format(list_val_ids))
snap_ids = []
for e in list_val_ids:
print(e)
res = ec2_cli.create_snapshot(
Description="Create snap",
VolumeId = e,
TagSpecifications=[
{
'ResourceType': 'snapshot',
'Tags': [
{
'Key': 'Delete-on',
'Value': '90'
},
]
},
],
)
print(res)
snap_ids.append(res.get('SnapshotId'))
print(snap_ids)
waiter = ec2_cli.get_waiter('snapshot_completed')
waiter.wait(SnapshotIds=snap_ids)
sns_cli = boto3.client('sns','us-west-2')
sns_cli.publish(TargetArn='arn:aws:sns:us-east-2:701808552826:topic_send_email', Message='Snapshot has been created')