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

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

by Devsong26 2021. 7. 15.

장기간 서비스를 이용하다 보면 사용 여부를 모르는 리소스들이 많이 생겨난다.

이번에 AWS EC2 리소스 중 key-pair를 정리하려다 알게 된 내용을 정리한다.

 


 

AWS EC2 Key-Pairs란?

프라이빗 키와 퍼블릭 키로 구성되는 키 페어는 인스턴스에 연결할 때 자격 증명 입증에 사용하는 보안 자격 증명 집합입니다. 퍼블릭 키는 Amazon EC2에 저장되며 프라이빗 키는 사용자가 저장합니다. 
암호 대신 프라이빗 키를 사용하여 인스턴스에 안전하게 액세스 할 수 있습니다. 프라이빗 키를 소유하는 사람은 누구나 인스턴스에 연결할 수 있으므로 보안된 위치에 프라이빗 키를 저장해 두는 것이 중요합니다.

출처: https://docs.aws.amazon.com/ko_kr/AWSEC2/latest/UserGuide/ec2-key-pairs.html

 

그렇다면 어떻게 미 사용 AWS EC2 Key-Pairs를 찾을 수 있을까?

'check unuse aws key-pairs' 라고 검색하니 아래의 URL을 찾을 수 있었다.

https://relay.sh/blog/delete-unused-key-pairs-with-python/

 

How to Secure AWS Account - Remove Unused EC2 Key Pairs with Python - Blog - Relay by Puppet

Learn simple, practical ways to secure your AWS account. One overlooked potential vulnerability is unused EC2 key pairs. See how to find and eliminate them with Python.

relay.sh

세상에는 똑똑한 사람들이 참 많다.

 

해당 포스팅을 참고하여 미 사용 Key-Pairs를 식별하기 위해서는 파이썬의 boto3 라이브러리를 사용해야 한다.

필자의 경우 delete 함수는 수행하지 않고 미 사용 Key-Pairs 목록을 보는 코드까지만 작성했다. (삭제 코드까지 보려면 위에 URL 참고)

아래 코드를 수행하기 위해서는 프로그래밍으로 접근 가능한 IAM 유저 계정이 필요하다.

계정의 access_key_id, secret_access_key가 필요하기 때문이다.

 

import boto3


class KeyPairs:
    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
        )

        # Creating lists for all, used, and unused key pairs
        self.all_key_pairs = []
        self.all_used_key_pairs = []
        self.all_unused_key_pairs = []

        ec2 = sess.client('ec2')
        self.__set_all_key_pairs(ec2, sess)
        self.__set_instance_groups(ec2)

    def __set_all_key_pairs(self, ec2, sess):
        # List the key pairs in the selected region
        self.all_key_pairs = list(map(lambda i: i['KeyName'], ec2.describe_key_pairs()['KeyPairs']))

        print("##### Print all key pairs #####")
        for i, e in enumerate(self.all_key_pairs):
            print(e)

    def __set_instance_groups(self, ec2):
        # Each EC2 reservation returns a group of instances.
        self.instance_groups = list(map(lambda i: i['Instances'], ec2.describe_instances()['Reservations']))

        print("##### Print all instance groups #####")
        for i, e in enumerate(self.instance_groups):
            print(e)

    def __set_all_used_key_pairs(self):
        # Create a list of all used key pairs in the account based on the running instances
        for group in self.instance_groups:
            for i in group:
                if i['KeyName'] not in self.all_used_key_pairs:
                    self.all_used_key_pairs.append(i['KeyName'])

        print("##### Print all used key pairs #####")
        print(self.all_used_key_pairs)

    def __set_all_unused_key_pairs(self):
        # Now compare the two lists
        for key in self.all_key_pairs:
            if key not in self.all_used_key_pairs:
                self.all_unused_key_pairs.append(key)

        print("##### Print all unused key pairs #####")
        print(self.all_unused_key_pairs)

    def check(self):
        self.__set_all_used_key_pairs()
        self.__set_all_unused_key_pairs()


if __name__ == '__main__':
    KeyPairs().check()

 

 



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


 

블로그의 다른 글

 

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

boto3는 python3 라이브러리다. AWS EBS 웹 UI는 사용자가 이용하기 편리하지만, 나는 코드로 확인을 해보고 싶었다. 우선 AWS CLI 계정의 액세스 키와 시크릿 액세스 키, 리전을 사용하여 세션 객체를

developer-syubrofo.tistory.com

 

미 사용 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