AWS CloudTrail可以记录ALB的事件,包括修改与创建。我们可以利用这个功能来监控ALB的私有IP地址是否更改。
步骤:
以下是示例代码:
import boto3
def lambda_handler(event, context):
client = boto3.client('ec2')
alb_id = 'ALB_ID'
alb_network_interface = client.describe_network_interfaces(
Filters=[{
'Name': 'description',
'Values': [alb_id]
}]
)
current_ip_address = alb_network_interface['NetworkInterfaces'][0]['PrivateIpAddress']
# Get previous IP address from SSM Parameter Store
ssm = boto3.client('ssm')
previous_ip_address = ssm.get_parameter(Name='previous_alb_ip_address')
if previous_ip_address['Parameter']['Value'] != current_ip_address:
# Update previous IP address in SSM Parameter Store
ssm.put_parameter(
Name='previous_alb_ip_address',
Value=current_ip_address,
Type='String',
Overwrite=True
)
# Send notification via SNS
sns = boto3.client('sns')
sns.publish(
TopicArn='SNS_TOPIC_ARN',
Message='ALB private IP address has changed to ' + current_ip_address
)