본문으로 바로가기

[LocalStack] AWS를 Mocking

category 개발 노트/LocalStack 2023. 4. 15. 22:43
728x90
반응형

목차

     

    개요

    AWS를 쓰게 되면 직접 서버를 준비해서 구성할 필요가 없으므로 여러모로 편리하기도 하지만 편리하다는 이유로 이것저것 막 쓰다 보면 어느샌가 비용이 증가하는 상황을 겪는다.

    그러다 보니 AWS를 건드릴 때마다 이건 비용이 얼마나 들까를 자연스레 고민하게 된다. 이에 더해 AWS와 통신을 하는 기능을 개발해야 한다면 개발과정에서 잘 동작하는지 여러 번 체크도 해야되고 테스트 코드가 AWS와 연계된 영역이라면 더 복잡하다.

     

    AWS를 Mocking 하는 방법이 뭐가 있을까를 막연하게 생각하던 도중에 글또에서 알게 되신 분에게서 "LocalStack"이라는 AWS를 Mocking 할 수 있는 도구가 있다는 것을 듣게 되었다.

    그러하여 "LocalStack"을 조사하면서 알게 된 내용을 남겨보고자 한다.

     

    Installation

    LocalStack을 사용하기에 앞서 필요한 건 로컬 환경에 Docker가 설치되어있어야 한다는 점이다. Docker가 설치되어 있는 환경에서  LocalStack을 사용하기 위한 방법에는 두 가지가 있다.

     

    1. "LocalStack" Dockerhub에서 Docker Compose 파일을 이용해 사용하기

    2. "Python"의 "pip"를 이용해서 localstack 모듈을 설치해서 사용하기


    앞서 언급했듯 위 두 가지 방법 모두 기본적으로 로컬에는 "Docker"가 설치되어있어야 한다는 것을 전제로 한다. 필자는 2번 방법을 택해 LocalStack을 설치했다.

    pip install localstack

    pip로 localstack을 설치하고 나면 다음과 같은 명령들을 이용할 수 있습니다.

    ╰─$ localstack --help
    Usage: localstack [OPTIONS] COMMAND [ARGS]...
    
      The LocalStack Command Line Interface (CLI)
    
    Options:
      --version       Show the version and exit.
      --debug         Enable CLI debugging mode
      --profile TEXT  Set the configuration profile
      --help          Show this message and exit.
    
    Commands:
      config  Inspect your LocalStack configuration
      infra   Manipulate LocalStack infrastructure (legacy)
      login   Log in with your account credentials
      logs    Show the logs of the LocalStack container
      pod     Manage the state of your instance via Cloud Pods
      ssh     Obtain a shell in the running LocalStack container
      start   Start LocalStack
      status  Print status information about the LocalStack runtime
      stop    Stop the running LocalStack container
      update  Update LocalStack components
      wait    Wait on the LocalStack container to start



    Execute

    pip로 localstack을 설치하고 나면 다음과 같이 localstack을 실행할 수 있다.

    ╰─$ localstack start
    
         __                     _______ __             __
        / /   ____  _________ _/ / ___// /_____ ______/ /__
       / /   / __ \/ ___/ __ `/ /\__ \/ __/ __ `/ ___/ //_/
      / /___/ /_/ / /__/ /_/ / /___/ / /_/ /_/ / /__/ ,<
     /_____/\____/\___/\__,_/_//____/\__/\__,_/\___/_/|_|
    
     💻 LocalStack CLI 1.4.0
    
    [20:32:02] starting LocalStack in Docker mode 🐳                                                                                                      localstack.py:138
    ──────────────────────────────────────────────────────────── LocalStack Runtime Log (press CTRL-C to quit) ────────────────────────────────────────────────────────────
    2023-04-15 11:32:03,113 CRIT Supervisor is running as root.  Privileges were not dropped because no user is specified in the config file.  If you intend to run as root, you can set user=root in the config file to avoid this message.
    2023-04-15 11:32:03,115 INFO supervisord started with pid 14
    2023-04-15 11:32:04,130 INFO spawned: 'infra' with pid 16
    2023-04-15 11:32:05,134 INFO success: infra entered RUNNING state, process has stayed up for > than 1 seconds (startsecs)
    
    LocalStack version: 2.0.0.dev
    LocalStack Docker container id: 092a39653a6c
    LocalStack build date: 2023-03-25
    LocalStack build git hash: 739a5965
    
    2023-04-15T11:32:05.427  WARN --- [  MainThread] localstack.deprecations    : LOCALSTACK_HOSTNAME is deprecated (since 2.0.0) and will be removed in upcoming releases of LocalStack! This configuration will be migrated to LOCALSTACK_HOST
    2023-04-15T11:32:05.427  WARN --- [  MainThread] localstack.deprecations    : EDGE_BIND_HOST is deprecated (since 2.0.0) and will be removed in upcoming releases of LocalStack! This configuration will be migrated to GATEWAY_LISTEN
    Ready.
    2023-04-15T11:32:06.081  WARN --- [-functhread3] hypercorn.error            : ASGI Framework Lifespan error, continuing without Lifespan support
    2023-04-15T11:32:06.081  WARN --- [-functhread3] hypercorn.error            : ASGI Framework Lifespan error, continuing without Lifespan support
    2023-04-15T11:32:06.088  INFO --- [-functhread3] hypercorn.error            : Running on https://0.0.0.0:4566 (CTRL + C to quit)
    2023-04-15T11:32:06.088  INFO --- [-functhread3] hypercorn.error            : Running on https://0.0.0.0:4566 (CTRL + C to quit)
    2023-04-15T11:32:06.126  INFO --- [  MainThread] localstack.utils.bootstrap : Execution of "start_runtime_components" took 606.15ms

    localstack을 foreground로 실행시키기 때문에 localstack 어떤 명령을 보낼 때마다 이 console을 통해 로그를 확인할 수 있게 됩니다. 로그가 console에 나오지 않게 하려면 다음과 같이 실행합시다.

    ╰─$ localstack start -d
    
         __                     _______ __             __
        / /   ____  _________ _/ / ___// /_____ ______/ /__
       / /   / __ \/ ___/ __ `/ /\__ \/ __/ __ `/ ___/ //_/
      / /___/ /_/ / /__/ /_/ / /___/ / /_/ /_/ / /__/ ,<
     /_____/\____/\___/\__,_/_//____/\__/\__,_/\___/_/|_|
    
     💻 LocalStack CLI 1.4.0
    
    [21:56:02] starting LocalStack in Docker mode 🐳                                                                  localstack.py:138
               preparing environment                                                                                   bootstrap.py:675
               configuring container                                                                                   bootstrap.py:683
               starting container                                                                                      bootstrap.py:690
    [21:56:03] detaching                                                                                               bootstrap.py:694

     만약 localstack을 처음 실행시키는 과정이라면 시간이 다소 조금 걸릴 수 있습니다.

    DashBoard

    구글링을 하다 LocalStack에 DashBoard가 존재한다는  것을 알게 되었다. "http://127.0.0.1:8080/#!/infra"을 통해 접근이 가능하다고 되어있었지만 LocalStack이 계속 업데이트되면서 내용이 변경되었는지 해당 주소로는 DashBoard로 접근할 수는 없었다

     

    이와 관련하여 LocalStack Github Repository에서 관련 Issue를 찾을 수 있었다. 요약하자면 localstack을 실행한 뒤에  http://app.localstack.cloud로 접속하면 된다는 것이다. LocalStack DashBoard의 인터페이스가 직관적이고 다루기 쉽게 되어있기 때문에 부연설명을 해야 되는 점은 없다

     

    LocalStack이 무료와 유료버전으로 나뉘어 저 있어서 어떤 항목에는 ApiKey를 입력하라고 나오기도한다. ApiKey를 입력하지 않는다고 해서 따로 경고창이 뜨거나 하지 않으므로 굳이 신경 쓸 필요는 없어 보입니다

     

    DashBoard 상에서 사용가능한 LocalStack의 AWS 서비스들은 다음과 같이 확인된다.

     

    boto3 연계하기

    아직 LocalStack의 DashBoard를 통해 무언가를 생성한다거나 하는 방법은 알지 못했지만 S3 Bucket을 생성해야 한다면 다음과 같이 awscli를 이용하는 중이다.

    # S3 Bucket 생성하기
    ╰─$ aws --endpoint-url=http://localhost:4566 s3 mb s3://test-bucket

    즉, 기존에 awscli를 통해 사용할 수 있는 명령이고 이 명령의 해당하는 LocalStack의 AWS Service가 있다면 사용이 가능하다. 이에 더해 python에서 aws를 다루기 위한 모듈인 boto3을 통해 LocalStack을 사용하려면 boto3.client의 endpoint에 localstack 주소를 넣어줘서 사용할 수 있습니다.

    import boto3
    
    s3 = boto3.client("s3", endpoint_url="http://localhost:4566")
    response = s3.list_buckets()
    
    for bucket in response['Buckets']:
        print(f"{bucket=}")

     

    마치며

    개인적으로는 LocalStack을 사용함으로써 awscli를 사용하는 방법도 익히고 일석이조였다.

     

    특정한 경우지만 평소에 EC2 같은 것을 Mocking 할 일이 없었기에 언제 EC2를 Mocking 해서 사용할 수 있을까를 고민해 보게 되었는데 일차원적으로는 지금까지 EC2를 Mocking 해서 사용할 일이 없었기 때문에 의의로 사용성이 없는 건가라는 생각이 들기도 한다.

    곰곰이 생각해 보니 AWS Script를 작성할 때도 LocalStack을 통해 미리 테스트해 볼 수 있지 않을까 싶습니다. 사용하는 방법에 따라서 다양한 상황에서 많이 써먹을 수 있는 좋은 도구인 듯하다.

    728x90
    반응형