본문 바로가기
개발/아키텍처

boto3 라이브러리로 미 사용중인 AWS EBS를 알아보자.

by Devsong26 2021. 7. 27.

boto3는 python3 라이브러리다.

AWS EBS 웹 UI는 사용자가 이용하기 편리하지만, 나는 코드로 확인을 해보고 싶었다.

 


 

우선 AWS CLI 계정의 액세스 키시크릿 액세스 키, 리전을 사용하여 세션 객체를 생성해야 한다.

그 후, 세션 객체로 Client 클래스의 객체를 생성한다.

sess = boto3.Session(
	# TODO: Supply your AWS credentials & specified region here
	aws_access_key_id='',
	aws_secret_access_key='',
	region_name='',  # Or whatever region you want
)

ec2 = sess.client('ec2')

 

Client 클래스는 여러 메소드를 가지고 있으니, 문서를 참고하자.

EBS 데이터를 보기 위해서 describe_volume 메소드를 호출해야 한다.

self.all_ebs = ec2.describe_volumes()['Volumes']

 

사용 여부는 self.all_ebs의 각 아이템이 "Attachments" key에 매칭되는 value 가 있는지 확인하면 된다.

for i, e in enumerate(self.all_ebs):
	if len(e['Attachments']) > 0:
		self.all_used_ebs.append(e)
	else:
		self.all_unused_ebs.append(e)

 

전체 소스 코드

import boto3


class EBS:
    def __init__(self):
        sess = boto3.Session(
            # TODO: Supply your AWS credentials & specified region here
            aws_access_key_id='',
            aws_secret_access_key='',
            region_name='',  # Or whatever region you want
        )

        ec2 = sess.client('ec2')

        self.all_ebs = ec2.describe_volumes()['Volumes']
        self.all_used_ebs = []
        self.all_unused_ebs = []

    def check_unused_ebs(self):
        self.__print_items("Print all ebs", self.all_ebs)

        for i, e in enumerate(self.all_ebs):
            if len(e['Attachments']) > 0:
                self.all_used_ebs.append(e)
            else:
                self.all_unused_ebs.append(e)

        self.__print_items("Print all used ebs", self.all_used_ebs)
        self.__print_items("Print all unused ebs", self.all_unused_ebs)

    def __print_items(self, msg, arr):
        print()
        print("##### {0} #####".format(msg))
        for i, e in enumerate(arr):
            print(e)


if __name__ == '__main__':
    EBS().check_unused_ebs()

 


 


더 많은 내용을 보시려면 아래를 참고하세요.


 

블로그의 다른 글

 

미 사용 AWS EC2 보안 그룹은 어떻게 확인할까?

미 사용 중인 Volume과 Key-pairs는 코드로 확인하였으나, 보안 그룹은 사용하는 서비스가 많아 코드만으로는 한계가 있다. (물론, 사용자가 보안 그룹이 적용되는 모든 서비스를 알고 있다면 이야기

developer-syubrofo.tistory.com

 

AWS Well-Architected Tool이란 무엇일까?

이번에 회사에서 사용중인 AWS 아키텍처의 보안 점검을 위해, "AWS Well-Architected Tool"이라는 무료 도구를 사용한다는 이야기를 들었다. 생소하여 간단히 조사 및 학습을 해보려고 한다. 해당 글은

developer-syubrofo.tistory.com

 

AWS도 로그인 시 OTP를 쓸 수 있다? AWS MFA에 대해서 알아보자

보통 로그인을 할 때 2차 인증으로 OTP를 많이 사용한다. AWS에도 OTP가 있는지 궁금했는데, MFA라는 것이 있었다. 한 번 알아보자. AWS MFA란? AWS Multi-Factor Authentication(MFA)은 사용자 이름과 암호 외에..

developer-syubrofo.tistory.com

 

미 사용 AWS key-pairs 를 정리하는 방법

장기간 서비스를 이용하다 보면 사용 여부를 모르는 리소스들이 많이 생겨난다. 이번에 AWS EC2 리소스 중 key-pair를 정리하려다 알게 된 내용을 정리한다. AWS EC2 Key-Pairs란? 프라이빗 키와 퍼블릭

developer-syubrofo.tistory.com