728x90

AWS Lambda에 코드를 업로드할때 numpy, pandas와 같이 C 또는 C++을 기반으로 한 라이브러리가 포함되어 있다면 Lambda는 이 라이브러리를 Import하지 못합니다.

⚠️ pandas 라이브러리 설치시에는 NumPy가 같이 설치됩니다.

Please note and check the following:

  * The Python version is: Python3.9 from "/var/lang/bin/python3.9"
  * The NumPy version is: "1.23.4"

and make sure that they are the versions you expect.
Please carefully study the documentation linked above for further help.

Original error was: No module named 'numpy.core._multiarray_umath'

Unable to import required dependencies:\nnumpy: \n\nIMPORTANT: PLEASE READ THIS FOR ADVICE ON HOW TO SOLVE THIS ISSUE!\n\nImporting the numpy C-extensions failed. This error can happen for\nmany reasons, often due to issues with your setup or how NumPy was\ninstalled.\n\nWe have compiled some common reasons and troubleshooting tips at:\n\n    https://numpy.org/devdocs/user/troubleshooting-importerror.html\n\nPlease note and check the following:\n\n  * The Python version is: Python3.9 from \"/var/lang/bin/python3.9\"\n  * The NumPy version is: \"1.23.4\"\n\nand make sure that they are the versions you expect.\nPlease carefully study the documentation linked above for further help.\n\nOriginal error was: No module named 'numpy.core._multiarray_umath'\n",

따라서 Lambda Layer에 네이티브 코드 라이브러리가 포함되어 있는 경우 바이너리가 Amazon Linux와 호환되는 시스템을 사용하여 이러한 라이브러리를 컴파일하고 빌드해야 합니다.

pip를 활용하여 라이브러리를 mac에서 패키지를 다운로드 받아보면 다음과 같이 mac os기반의 패키지를 받는 것을 확인 할 수 있습니다.

모든 패키지가 위와같은 문제가 발생하는 것은 아니지만, 가능하면 OS 호환성을 고려하여 패키지를 설치하는 것이 좋습니다.

이러한 문제를 해결하기 위해 AWS EC2에서 Amazon Linux 인스턴스를 할용할 수 있지만, Docker를 활용하여 간단하게 Lambda Layer 패키지를 만들 수 있습니다.

1. Docker 설치하기

먼저 Docker 가 설치되어 있지 않다면, 아래 링크를 참고하여 Docker를 설치합니다.
Docker 설치하기

2. Amazone Linux2 컨테이너 실행하기

Amazone Linux2 실행합니다. docker images로 image가 없으면 해당 iamge를 pull 한 후 실행됩니다.

docker run -it amazonlinux:latest

-it 옵션은 컨테이너를 종료하지 않은채로 터미널 작업을 하기 위해서 사용합니다.

cat /etc/os-release를 입력하여 결과를 확인합니다.

#결과
NAME="Amazon Linux"
VERSION="2"
ID="amzn"
ID_LIKE="centos rhel fedora"
VERSION_ID="2"
PRETTY_NAME="Amazon Linux 2"
ANSI_COLOR="0;33"
CPE_NAME="cpe:2.3:o:amazon:amazon_linux:2"
HOME_URL="https://amazonlinux.com/"

Python 3.9, 3.8 은 Amazon Linux 2 런타임 환경만을 지원합니다.
Lambda 런타임 확인하기 ➔

3. 컨테이너에 파이썬 설치하기

3.1 필수 라이브러리 설치

먼저 파이썬 설치를 위해 GCC 컴파일러와 같은 필수 개발라이브러리를 먼저 설치 합니다.

yum -y groupinstall "Development Tools"
yum install -y openssl-devel bzip2-devel libffi-devel
yum install -y wget

3.2 Python 3.9 설치하기

파이썬 3.9 다운로드 페이지로 이동하여 파이썬 3.9를 설치합니다.

cd /home
# Download python 3.9
wget https://www.python.org/ftp/python/3.9.15/Python-3.9.15.tgz

# 압축풀기
tar xzf Python-3.9.15.tgz

# python 빌드 및 설치
cd Python-3.9.15
./configure --enable-optimizations
make altinstall

make altinstall 기본 파이썬 바이너리 파일위치 /usr/bin/python 교체를 방지하는 데 사용됩니다.

3.3 Python 버전 확인

설치된 Python 3.9는 /usr/local/bin 디렉토리에 설치됩니다. 기본 Python 버전을 덮어쓰지 않았으므로 설치된 버전 확인을 위해서 다음과 같이 실행해야 합니다.
파이썬이 제대로 설치되었는지 버전을 확인합니다.

python3.9 -V

# 결과
Python 3.9.15

3.4 파이썬 가상환경 생성하

애플리케이션 패키지가 포함시킬 수 있는 env라는 가상환경을 생성합하고 실행합니다.

python3.9 -m venv env
source env/bin/activate

# 결과
(env) bash-4.2#

Amazon Linux2 기반의 파이썬 3.9 개발환경 구성이 완료되었습니다. 이제 lambda layer 패키지를 생성하겠습니다.

4. AWS Lambda Layer 패키지 생성하기

requirement.txt를 갖고 전체 패키지 파일을 생성할 수 있지만 패키지 설치방식은 모두 동일 하므로 여기서는 Numpy 패키지를 가지고 Layer를 생성해보겠습니다.

4.1 Numpy 패키지 다운로드

pip로 numpy 패키지를 다운로드 하게 되면, 로컬 터미널 환경에 맞는 패키지를 다운로드 받게 됩니다. 따라서 Amazon Linux용으로 패키지를 다운로드 받아야만 종속성의 오류가 발생하지 않습니다.
https://pypi.org/project/numpy/#files 에서 파이썬3.9해당하는 Amazon Linux 버전의 .whl 파일을 다운로드 합니다.

# 패키지용 디렉토리로 이동
mkdir python && cd python

# NumPy 다운로드
wget https://files.pythonhosted.org/packages/92/49/127e40f3f468a9bbce1fe69e97d0f0db524621960e0adc51a977298eb49c/numpy-1.23.4-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl

다운로드 받은 파일은 압축을 풀고, 받은 파일은 삭제합니다.

# 압축 풀기
unzip numpy-1.23.4-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl

# .whl 파일 삭제
rm -rf numpy-1.23.4-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl

4.2 패키지 생성하기

상위 폴더로 이동하여 파이썬 패키지로 압축합니다.

zip -r python.zip python/

# 결과
adding: python/ (stored 0%)
adding: python/soupsieve/ (stored 0%)
adding: python/soupsieve/css_match.py (deflated 79%)
adding: python/soupsieve/css_parser.py (deflated 78%)
adding: python/soupsieve/py.typed (stored 0%)
adding: python/soupsieve/util.py (deflated 61%)
(중략)

파이썬 패키지로 압축 시에는 python/라이브러리로 생성되어져야 람다에서 라이브러리를 임포트 할 수 있습니다.

4.3 패키지 업로드

Docker 컨테이너에서 로컬로 패키지를 복사 한 후, Lambda Layer를 생성합니다.

# 컨테이너와 파일의 위치를 :로 구분하고 복사할 곳의 경로를 적습니다.
docker cp con:/root/data.txt /home/dst/

Layer 업로드는 Lambda Layer 공통라이브러리 등록하기 ➔ 에서 확인합니다.

5. Lambda 함수 생성

Lambda 함수에서 호출할 라이브러리에 대한 구성이 마쳤습니다.
이제 간단한 Numpy호출 예제를 활용하여 테스트 해보겠습니다.

  • Function Name : LambdaTestFuction
  • Runtime : Python 3.9
  • Architecture : x86_64

함수를 생성한 후 스크롤을 내려 Add a Layer 버튼을 클릭하고, 만들어둔 레이어를 추가합니다.

샘플 코드를 입력하고 Deploy 버튼을 클릭하고, Test 를 실행합니다.

import json
import numpy as np

def lambda_handler(event, context):

    a = np.arange(6)
    a2 = a[np.newaxis, :]

    # TODO implement
    return {
        'statusCode': 200,
        'body': a2.shape
    }

결과
아래의 return 결과가 나왔으면 정상적으로 임포트가 완료된 것입니다.

Response
{
  "statusCode": 200,
  "body": [
    1,
    6
  ]
}
(중략)

Reference

  1. https://docs.aws.amazon.com/ko_kr/lambda/latest/dg/configuration-layers.html
  2. https://devbruce.github.io/aws/aws-10-lambda_layer/#os-%ED%98%B8%ED%99%98-%EC%97%90%EB%9F%AC
  3. https://sangchul.kr/368
  4. https://tecadmin.net/install-python-3-9-on-amazon-linux/
  5. https://sangchul.kr/368
  6. https://docs.aws.amazon.com/ko_kr/AmazonECR/latest/userguide/amazon_linux_container_image.html
728x90
반응형
728x90

Mac OS에서 AWS CLI 버전 2를 설치하는 방법에 관해 알아보겠습니다.
Mac은 Homebrew가 있어 매우 편리하게 설치할 수 있습니다.

설치하기

명령줄에서 다음 단계에 따라 Linux에 AWS CLI를 설치합니다.

# aws cli 설치
brew install awscli

# 설치 경로 확인
which aws

# 결과
/usr/local/bin/aws

# 버전확인
aws --version

# 결과
aws-cli/2.7.17 Python/3.10.5 Darwin/21.5.0 source/x86_64 prompt/off

aws 자격증명 설치하기

🗂 아래 링크에서 설치 방법을 참고하세요.

  1. aws 자격증명 하기
  2. aws 여러계정 사용하기
728x90
반응형
728x90

AWS Account를 사용하다 보면 개인용, 회사계정 등 여러 계정들을 사용하게 됩니다. AWS CLI를 활용 시 aws configure --profile 을 활용하여 여러개의 Access Key ID 와 Secret Access Key를 생성하여 관리할 수 있습니다.

Profile 추가하기

# aws configure --profile {profile name}
aws configure --profile newprofile

# Result
AWS Access Key ID [None]: 
AWS Secret Access Key [None]: 
Default region name [None]:
Default output format [None]:

해당 프로필 맞는 Access Key ID 와 _Secret Access Key_를 입력합니다.

설정확인

# 설정된 Config 정보
cat ~/.aws/config

# 설정된 credentials 정보
cat ~/.aws/credentials

테스트

해당 Account의 s3 버킷리스트를 가져옵니다.

aws s3 ls --profile "user1"

명명된 프로파일을 사용하려는 경우, 명령줄에서 AWS_PROFILE 환경 변수를 설정하면 모든 명령에서 매번 프로파일을 지정하는 것을 피할 수 있습니다.

# Linux 또는 macOS
export AWS_PROFILE=user1

# Windows
setx AWS_PROFILE user1

Reference

728x90
반응형
728x90

aws cli명령어로 s3에 파일을 복사하거나 삭제하는 방법을 알아보겠습니다.

AWS 자격증명

먼저 로컬에서 AWS 접근을 위해 aws configure를 통해 자격증명을 합니다.
AWS 자격증명방법

버킷 및 객체 나열

# 버킷 리스트 보기
aws s3 ls

# 버킷 내 파일 리스트 보기
aws s3 ls s3://mybucket/

파일 복사

# 현재 작업 디렉터리에서 S3 버킷으로 로컬 파일을 복사
aws s3 cp localfile s3://bucket-name

# S3 버킷에서 현재 작업 디렉터리로 파일을 복사(./은 현재 디렉토리)
aws s3 cp s3://bucket-name ./

객체 동기화

버킷과 디렉터리의 내용을 동기화하기 위해 s3 sync 명령어를 사용합니다.
s3 sync는 동일한 이름의 파일과 크기 또는 수정 시간이 다른 모든 파일을 업데이트합니다.

aws s3 sync . s3://my-bucket/path

recursive

지정된 디렉터리 아래의 모든 파일 또는 객체에 대해 명령이 수행됩니다.

# 현대 디렉터리의 모든 파일 및 폴더 복사
aws s3 cp . s3://my-bucket --recursive

# 현대 디렉터리의 모든 파일 및 폴더 복사
aws s3 rm s3://my-bucket/ --recursive

Reference

728x90
반응형

'AWS' 카테고리의 다른 글

Mac OS에서 AWS Cli 설치하기  (0) 2022.07.22
[AWS] AWS Configure 여러 계정 사용하기  (0) 2022.03.01
AWS cli 보안자격증명(aws configure)  (0) 2021.09.04
AWS Cli 버전 2 설치  (0) 2021.09.03
AWS Pycharm Toolkit 설치하기  (0) 2021.08.08
728x90

aws 자격 증명

먼전 aws configure로 aws 자격 증명을 합니다.
AWS console에서 보안자격증명을 통해 얻은 Access Key ID, Secret Access Key 를 입력하고 Region은 서울리전(ap-northeast-2)를 입력합니다.

AWS Access Key ID [None]: 
AWS Secret Access Key [None]: 
Default region name [None]: ap-northeast-2
Default output format [None]: 

입력한 정보는 다음의 위치에 저장됩니다.

~/.aws/configure : 각 프로필 별 리전 및 output format

~/.aws/credentials : 각 프로필 별 Access Key / Secret Access Key

Reference

728x90
반응형
728x90

Linux에서 AWS CLI 버전 2를 설치하는 방법에 관해 알아보겠습니다.

Prerequisites

운영 체제에 기본 제공 unzip 명령이 없는 경우 unzip 설치 포스트를 참고하여 설치합니다.

설치하기

명령줄에서 다음 단계에 따라 Linux에 AWS CLI를 설치합니다.

# 설치파일 다운로드
$ curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"

# 압축해제
unzip awscliv2.zip

# cli 설치
sudo ./aws/install


# 버전확인
aws --version

삭제하기

1. 삭제를 위해 설치경로를 확인합니다.

# 설치 경로 확인
which aws

#결과
/usr/local/bin/aws

2. ls 명령을 사용하여 symlink가 가리키는 디렉터리를 찾습니다. 그러면 --install-dir 파라미터와 함께 사용한 경로가 제공됩니다.

ls -l /usr/local/bin/aws

# 결과
lrwxrwxrwx 1 root root 37 Sep  3 23:05 /usr/local/bin/aws -> /usr/local/aws-cli/v2/current/bin/aws

3. --bin-dir 디렉터리에서 두 개의 symlink를 삭제합니다.

sudo rm /usr/local/bin/aws
sudo rm /usr/local/bin/aws_completer

4. --install-dir 디렉터리를 삭제합니다.

sudo rm -rf /usr/local/aws-cli

Reference

728x90
반응형
728x90

AWS Pycharm Toolkit을 활용하여 다음과 같은 작업을 수행할 수 있습니다.

  • 원하는 런타임에 즉시 배포 가능한 서버리스 애플리케이션을 생성합니다.
  • Lambda 런타임에서 단계별 디버깅으로 로컬에서 코드를 테스트 할 수 있습니다.
  • 원하는 AWS 리전에 애플리케이션을 배포합니다.
  • Amazon Simple Storage Service(S3), Amazon API Gateway 및 Amazon Simple Notification Service(SNS)를 활용하고 구성할 수 있습니다.

Pycharm Toolkit 설치

[File]-[Settings]-[Plugins] 에서 aws tool을 검색하여 AWS Toolkit을 설치하고, Pycharm을 재시작 합니다.

AWS Serverless Application Model(SAM) 설치

일부 기능은 AWS Serverless Application Model(SAM) CLI를 사용하기 때문에 AWS SAM을 설치합니다. https://aws.amazon.com/ko/serverless/sam/

※ 설치는 Linux 버전으로 설치합니다.

1. AWS SAMCLI 다운로드 받고 sam-installation/하위에 설치 파일 압축 해제

unzip aws-sam-cli-linux-x86_64.zip -d sam-installation

2. AWS SAM CLI를 설치

sudo ./sam-installation/install

3. 설치 결과 확인

sam --version

# Result
SAM CLI, version 1.27.2

업그레이드

--update 옵션을 다음과 같이 설치 명령에 추가합니다.

sudo ./sam-installation/install --update

설치삭제하기

1. which 명령으로 심볼릭 링크 확인

which sam

# 결과예시
/usr/local/bin/sam

2. symlink가 가리키는 디렉터리 확인

ls -l /usr/local/bin/sam

# 결과 예시
lrwxrwxrwx 1 ec2-user ec2-user 49 Oct 22 09:49 /usr/local/bin/sam -> /usr/local/aws-sam-cli/current/bin/sam

3. 심볼릭 링크 삭제

sudo rm /usr/local/bin/sam

4. 설치 디렉터리 삭제

sudo rm -rf /usr/local/aws-sam-cli

Reference

  1. https://aws.amazon.com/ko/blogs/korea/new-aws-toolkits-for-pycharm-intellij-preview-and-visual-studio-code-preview/
  2. https://docs.aws.amazon.com/ko_kr/serverless-application-model/latest/developerguide/serverless-sam-cli-install-linux.html
728x90
반응형
728x90

Amazon Simple Storage Service (Amazon S3)에서 버킷을 생성하고, 퍼블릭으로 설정하여 사용자가 사진을 볼 수 있도록 허용하는 방법입니다.

1. S3 버킷생성하기

[S3] 메뉴에 진입한 뒤, [버킷 만들기] 을 선택합니다.

버킷 이름은 Unique한 이름으로 명명하고, 리전을 선택합니다.

외부에서 접근할 수 있도록 [모든 퍼블릭 액세스 차단] 체크를 해제합니다.

퍼블릭 읽기 액세스 권한을 부여하기 위해 버킷 정책을 복사한 후 버킷 정책 편집기에 붙여 넣습니다. Resource는 생성된 버킷 ARN을 복사하여 붙여 넣습니다.

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "PublicReadGetObject",
            "Effect": "Allow",
            "Principal": "*",
            "Action": [
                "s3:GetObject"
            ],
            "Resource": [
                "arn:aws:s3:::Bucket-Name/*"
            ]
        }
    ]
}

브라우저 스크립트가 Amazon S3 버킷에 액세스하려면 먼저CORS 구성를 다음과 같이 설정합니다.

[
    {
        "AllowedHeaders": [
            "*"
        ],
        "AllowedMethods": [
            "PUT",
            "POST",
            "DELETE"
        ],
        "AllowedOrigins": [
            "*"
        ],
        "ExposeHeaders": [
            "x-amz-server-side-encryption",
            "x-amz-request-id",
            "x-amz-id-2"
        ],
        "MaxAgeSeconds": 3000
    }
]

2. 이미지 업로드

이미지 하나를 업로드 해보고, 해당 링크를 오픈합니다. 링크 오픈 시 크롬 시크릿창으로 오픈하여 외부 접근이 가능한지 확인합니다.

링크 결과입니다.

Reference

  1. https://docs.aws.amazon.com/ko_kr/AmazonS3/latest/userguide/WebsiteAccessPermissionsReqd.html
  2. https://docs.aws.amazon.com/ko_kr/AmazonS3/latest/userguide/ManageCorsUsing.html
728x90
반응형

'AWS' 카테고리의 다른 글

AWS Cli 버전 2 설치  (0) 2021.09.03
AWS Pycharm Toolkit 설치하기  (0) 2021.08.08
[AWS] EC2 인스턴스 SSH 접속하기(2)  (0) 2021.08.03
[AWS] EC2 인스턴스 SSH 접속하기(1)  (0) 2021.08.03
AWS 람다(Lambda)로 Python함수 구현하기  (0) 2021.07.30
728x90

이전에 생성된 EC2 인스턴스에 SSH 클라이언트로 EC2 서버에 접속해 보겠습니다.

EC2 생성관련 내용은 링크를 참고하세요.

 

[AWS] EC2 인스턴스 SSH 접속하기(1)

SSH를 활용하여 EC2 인스턴스에 접속할 수 있는 방법을 알아보겠습니다. 먼저 접속할 EC2를 생성해보겠습니다. 1. EC2 인스턴스 생성하기 1.1 인스턴스 시작 EC2 대시보드에서 인스턴스시작 버튼을 클

jjnomad.tistory.com


2. EC2 연결하기

EC2 대시보드에서 연결하기를 클릭합니다.

아래와 같이 접속할 수 있는 가이드를 제공합니다.

다운로드 받은 pem파일은 리드 권한으로 최소화 하고 ssh 클라이언트 접속 합니다.

결과

위와 같이 했을 경우 아래와 같이 "Permissions 0555" 에러 발생할 수 있습니다.

The authenticity of host 'ec2-3-34-192-17.ap-northeast-2.compute.amazonaws.com (3.34.192.17)' can't be established.
ECDSA key fingerprint is SHA256:sBCH/6kroLB89QA4VBvyV3ntx8CvtV5wjPUvAQOE4hg.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added 'ec2-3-34-192-17.ap-northeast-2.compute.amazonaws.com,3.34.192.17' (ECDSA) to the list of known hosts.
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@         WARNING: UNPROTECTED PRIVATE KEY FILE!          @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
Permissions 0555 for 'ec2-key-pair.pem' are too open.
It is required that your private key files are NOT accessible by others.
This private key will be ignored.
Load key "ec2-key-pair.pem": bad permissions
ec2-user@ec2-3-34-192-17.ap-northeast-2.compute.amazonaws.com: Permission denied (publickey,gssapi-keyex,gssapi-with-mic).

그럴경우, sudo 명령어로 실행하면 접속이 가능합니다.

sudo ssh -i "ec2-key-pair.pem" ec2-user@ec2-3-34-192-17.ap-northeast-2.compute.amazonaws.com

접속이 되었습니다. 😄

The authenticity of host 'ec2-3-34-192-17.ap-northeast-2.compute.amazonaws.com (3.34.192.17)' can't be established.
ECDSA key fingerprint is SHA256:sBCH/6kroLB89QA4VBvyV3ntx8CvtV5wjPUvAQOE4hg.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added 'ec2-3-34-192-17.ap-northeast-2.compute.amazonaws.com,3.34.192.17' (ECDSA) to the list of known hosts.

       __|  __|_  )
       _|  (     /   Amazon Linux 2 AMI
      ___|\___|___|

https://aws.amazon.com/amazon-linux-2/
[ec2-user@ip-172-31-1-4 ~]$
728x90
반응형

+ Recent posts