Created
August 3, 2023 10:07
-
-
Save sasasin/af69eeeb0f18bb6ba1e8f63090fafe33 to your computer and use it in GitHub Desktop.
Amazon VPC サブネットの総/使用済/残 IP アドレス数を CloudWatch に投稿する Lambda Fn
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import boto3 | |
from datetime import datetime | |
def lambda_handler(event, context): | |
# CloudWatch Metrics に付与するタイムスタンプとして使う | |
timestamp = datetime.utcnow() | |
client = boto3.client('ec2') | |
responses = [] | |
next_token = None | |
while True: | |
if next_token is None: | |
response = client.describe_subnets() | |
else: | |
response = client.describe_subnets(NextToken=next_token) | |
responses.append(response) | |
if not 'NextToken' in response: | |
break | |
next_token = response['NextToken'] | |
for response in responses: | |
for subnet in response['Subnets']: | |
put_subnet_metric(subnet, timestamp) | |
def put_subnet_metric(subnet, timestamp): | |
SubnetMask=int(subnet['CidrBlock'].split('/')[1]) | |
SubnetTotalIpAddressCount = 2 ** (32 - SubnetMask) | |
SubnetUsedIpAddressCount = SubnetTotalIpAddressCount - int(subnet['AvailableIpAddressCount']) | |
# 使用可能IPアドレス数 | |
put_metric_to_cloudwatch( | |
'SubnetAvailableIpAddressCount', | |
int(subnet['AvailableIpAddressCount']), | |
timestamp, | |
subnet['VpcId'], | |
subnet['SubnetId'] | |
) | |
# 総IPアドレス数 | |
put_metric_to_cloudwatch( | |
'SubnetTotalIpAddressCount', | |
SubnetTotalIpAddressCount, | |
timestamp, | |
subnet['VpcId'], | |
subnet['SubnetId'] | |
) | |
# 使用済みIPアドレス数 | |
put_metric_to_cloudwatch( | |
'SubnetUsedIpAddressCount', | |
SubnetUsedIpAddressCount, | |
timestamp, | |
subnet['VpcId'], | |
subnet['SubnetId'] | |
) | |
def put_metric_to_cloudwatch(metric_name, metric_value, timestamp, vpc_id, subnet_id): | |
client = boto3.client('cloudwatch') | |
response = client.put_metric_data( | |
Namespace='VpcSubnetMetricsCollector', | |
MetricData=[ | |
{ | |
'MetricName': metric_name, | |
'Value': metric_value, | |
'Unit': 'Count', | |
'Dimensions': [ | |
{ | |
'Name': 'VpcId', | |
'Value': vpc_id | |
}, | |
{ | |
'Name': 'SubnetId', | |
'Value': subnet_id | |
} | |
], | |
'Timestamp': timestamp | |
} | |
] | |
) | |
if __name__ == '__main__': | |
lambda_handler('','') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment