AWS

AWS EC2/RDS Instance 정보 조회 Lambda 코드

yechan93 2023. 9. 24. 15:40

AWS EC2 / RDS 의 인스턴스 정보를 조회하는 boto3 코드

  • 태그값을 지정하여 원하는 태그를 추출 가능

 

import json
import boto3

def lambda_handler(event, context):
    # TODO implement
    ec2_asset()
    rds_asset()


######EC2#####################################################
def ec2_asset():
    ec2 = boto3.client('ec2')   
    #ec2_info = []
    
    describe_ec2_instance = ec2.describe_instances()
    print("################EC2 Instance Info####################")
    for reservation in describe_ec2_instance['Reservations']:
        for instance in reservation['Instances']:
            instance_id = instance['InstanceId']
            instance_type = instance['InstanceType']
            tagName = None
            tagComponent = None
            for instance_Tags in instance['Tags']:
                               
                if instance_Tags['Key'] == 'Name':
                    tagName = instance_Tags['Value']
                    
                
                if instance_Tags['Key'] == 'Component':
                    tagComponent = instance_Tags['Value']
            print(instance_id,"\t", instance_type,"\t", tagName,"\t", tagComponent)    

                

######RDS#####################################################
def rds_asset():
    rds = boto3.client('rds')
    print("################RDS Instance Info####################")
    describe_rds_instance = rds.describe_db_instances()
    for dbInstances in describe_rds_instance['DBInstances']:
        for instance in dbInstances['DBInstanceIdentifier']:
            instance_zone = dbInstances['AvailabilityZone']
            instance_type = dbInstances['DBInstanceClass']            
            instance_endpoint = dbInstances['Endpoint']['Address']
            instance_engine = dbInstances['Engine']
            instance_enginevesion = dbInstances['EngineVersion']
            
            tagName = None
            tagComponent = None
            for instance_Tags in dbInstances['TagList']:
                if instance_Tags['Key'] == 'Name':
                    tagName = instance_Tags['Value']
                if instance_Tags['Key'] == 'Component':
                    tagComponent = instance_Tags['Value']

        print(tagName ,"\t",tagComponent,"\t", instance_type,"\t", instance_zone, "\t",instance_engine,"\t",instance_enginevesion,"\t",instance_endpoint)