skip to Main Content

I’m a newbie to both Stack Overflow and coding, so please bear with me if my question seems a bit basic or naive. I’m trying to figure out how to retrieve the complete list of IP addresses used in my AWS account and export them to an Excel sheet. Furthermore, I’d like to send this exported file via email using AWS Lambda.

So far, I’ve successfully managed to extract the IP addresses into an Excel file and store it in an S3 bucket. However, instead of keeping it in the bucket, I’d prefer receiving it directly in my email inbox. Any guidance would be highly appreciated!

import boto3
import ipaddress
import json
import xlsxwriter

def lambda_handler(event, context):
    ec2 = boto3.client('ec2')
    s3 = boto3.client('s3')

# Create a new Excel workbook
workbook = xlsxwriter.Workbook('/tmp/ip_report.xlsx')
worksheet = workbook.add_worksheet()

# Define Excel cell formatting
bold_format = workbook.add_format({'bold': True})
percentage_format = workbook.add_format({'num_format': '0.00%'})

# List all VPCs
vpcs = ec2.describe_vpcs()

# Initialize a row counter
row = 0

# Write headers to the Excel file
worksheet.write(row, 0, 'VPC Name', bold_format)
worksheet.write(row, 1, 'Subnet Name', bold_format)
worksheet.write(row, 2, 'Total IPs', bold_format)
worksheet.write(row, 3, 'Available IPs', bold_format)
worksheet.write(row, 4, 'IP Count', bold_format)
worksheet.write(row, 5, 'IP Usage Percentage', bold_format)
row += 1

for vpc in vpcs['Vpcs']:
    vpc_id = vpc['VpcId']
    vpc_name = vpc.get('Tags', [{'Key': 'Name', 'Value': 'N/A'}])[0]['Value']

    # Describe subnets in the VPC
    subnets = ec2.describe_subnets(Filters=[{'Name': 'vpc-id', 'Values': [vpc_id]}])
    awsReservationIPCount = 5

    for subnet in subnets['Subnets']:
        subnet_name = subnet.get('Tags', [{'Key': 'Name', 'Value': 'N/A'}])[0]['Value']
        cidr_block = subnet['CidrBlock']

        # Calculate total IP addresses in the subnet
        total_ips = sum(1 for _ in ipaddress.IPv4Network(cidr_block))

        ip_count = total_ips - awsReservationIPCount
        available_ips = subnet['AvailableIpAddressCount']

        # Calculate the percentage of IP address usage
        if total_ips > 0:
            ip_usage_percentage = (1 - available_ips / total_ips)
        else:
            ip_usage_percentage = 0

        # Write data to the Excel file
        worksheet.write(row, 0, vpc_name)
        worksheet.write(row, 1, subnet_name)
        worksheet.write(row, 2, total_ips)
        worksheet.write(row, 3, available_ips)
        worksheet.write(row, 4, ip_count)
        worksheet.write(row, 5, ip_usage_percentage, percentage_format)
       
        row += 1

# Close the Excel workbook
workbook.close()

#Upload the Excel file to S3
s3.upload_file('/tmp/ip_report.xlsx', 'd-s-akhil-dhp-lambdafuntion', 'ip_report.xlsx')

return {
    'statusCode': 200,
    'body': 'IP availability report generated and uploaded to S3 in Excel format.'
}

2

Answers


  1. You can send Email using AWS SES,

    Sample Code:

    import boto3
    
    ses_client = boto3.client("ses")
    
    message = prepare_msg()
    
    response = self.ses_client.send_raw_email(
        RawMessage={
            "Data": message.as_string(),
        },
    )
    

    For full code reference visit: https://gist.github.com/DilLip-Chowdary-Codes/32a83a7d7ce2df2fe181d7ace174e3fe.js

    Note: Before sending the mail, you need to add your from and to email_ids in SES Identities.

    By default, you’ll be provided with Sandbox mode where you need to add every identity (email) in the SES, for the above use case you’ve mentioned sandbox mode is enough.

    Login or Signup to reply.
  2. To send this exported file directly to your email inbox, you can follow these steps:

    You’ll need to modify your Lambda function to not only generate the Excel file but also send it via email. You can use the AWS SDK (boto3 for Python) to send an email using the Simple Email Service (SES).

    Verify your email address or domain, and make sure it’s in a "sandbox" environment (for development and testing). Once you’re ready to use SES in a production environment, you’ll need to request to move out of the sandbox.

    Install and Configure Bot3
    In your Lambda function, you’ll need to use Boto3 to send an email. Make sure you have the Boto3 library installed and configured with the appropriate AWS credentials. You can use environment variables or IAM roles to securely provide the credentials to your Lambda function.

    Continue generating the Excel file as you’ve already done and save it to a temporary location in your Lambda function.

    Send Email with Attachment:
    Use Boto3 and SES to send the email with the Excel file attached. Here’s a Python example of how you can do this:

    import boto3
    from botocore.exceptions import NoCredentialsError
    import pandas as pd
    import io
    
    def send_email_with_attachment(subject, body, file_name, recipient_email):
        # Initialize SES
        ses = boto3.client('ses', region_name='your_region')
    
        # Load the Excel file from S3
        s3 = boto3.client('s3')
        bucket_name = 'your-s3-bucket-name'
        object_key = 'path/to/your/excel-file.xlsx'
        response = s3.get_object(Bucket=bucket_name, Key=object_key)
        excel_data = response['Body'].read()
    
        # Send the email
        try:
            ses.send_email(
                Source='[email protected]',
                Destination={'ToAddresses': [recipient_email]},
                Message={
                    'Subject': {'Data': subject},
                    'Body': {'Text': {'Data': body}},
                },
                ReplyToAddresses=['[email protected]'],
                MessageDsn={
                    'ReturnPath': '[email protected]',
                },
                Attachments=[
                    {
                        'FileName': file_name,
                        'Data': excel_data,
                    },
                ]
            )
            print("Email sent successfully")
        except NoCredentialsError:
            print("Error: Could not send email. Check your AWS credentials.")
    
    def lambda_handler(event, context):
        # Your code to generate and save the Excel file
    
        # Send the email with the Excel file
        send_email_with_attachment(
            subject='AWS IP Addresses',
            body='Attached is the list of IP addresses in your AWS account.',
            file_name='aws_ip_addresses.xlsx',
            recipient_email='[email protected]'
        )
    

    Replace ‘your_region’, ‘your-s3-bucket-name’, ‘path/to/your/excel-file.xlsx’, ‘[email protected]’, ‘[email protected]’, and ‘[email protected]’ with your specific values.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search