[Serverless] Google Cloud Functions에서 환경변수 사용하는 방법 (Using Environment variables)

남양주개발자

·

2020. 12. 14. 14:52

728x90
반응형

[서버리스] Google Cloud Functions에서 환경변수 사용하는 방법 (Using Environment variables)

서버리스 프레임워크에서 구글 클라우드 함수(Google Cloud Functions)를 사용할 때 함수에 환경 변수를 추가하고 싶은 경우가 생깁니다. 이러한 상황에서 환경 변수를 추가하는 방법에 대해서 살펴보도록 하겠습니다.

기본적으로 구글 클라우드 함수(Google Cloud Functions)에서 환경 변수를 사용하는 방법은 아래와 같습니다.

 

환경 변수 사용  |  Cloud Functions 문서  |  Google Cloud

배포 시 Cloud Functions에 임의의 키-값 쌍을 설정할 수 있습니다. 이러한 키-값 쌍은 런타임 시 코드에서 액세스할 수 있는 리터럴 환경 변수 또는 빌드팩 시스템의 구성 정보로 표시됩니다. 키-값

cloud.google.com

서버리스(Serverless) 프레임워크에서 구현한 구글 클라우드 함수에서 환경 변수를 사용하기 위해서는 아래와 같은 설정이 필요합니다. serverless.yml에서 functions에 environmnet를 추가합니다. 구글 클라우드 함수의 환경 변수는 아래와 같이 설정한 후 실제 사용할 때는 모두 대문자로 사용하시면 됩니다.

// serverless.yml
functions:
  write-post:
    handler: writePost
    memorySize: 1024
    timeout: 120s
    environment:
      url: https://www.github.com/ruden91
      name: 베이스캠프
    events:
      - http: path
exports.writePost = async (req, res) => {
	// process.env.URL
	// process.env.NAME    
}

만약 구글 클라우드 함수에서 사용되고 있는 예약어를 등록해서 사용하려고 한다면 아래와 같은 에러가 발생합니다. 구글 클라우드 함수에서 사용되고 있는 예약어를 사용하지 않게 유의하세요.

  Error --------------------------------------------------
 
  Error: Deployment failed: RESOURCE_ERROR
  
       {"ResourceType":"gcp-types/cloudfunctions-v1:projects.locations.functions","ResourceErrorCode":"400","ResourceErrorMessage":{"code":400,"message":"The request has errors","status":"INVALID_ARGUMENT","details":[{"@type":"type.googleapis.com/google.rpc.BadRequest","fieldViolations":[{"field":"environment_variables","description":"environment variable name PWD is reserved by the system: it cannot be set by users"}]}],"statusMessage":"Bad Request","requestPath":"https://cloudfunctions.googleapis.com/v1/projects/webruden-api/locations/asia-northeast3/functions/posts-prod-write-post","httpMethod":"PATCH"}}
      at throwErrorIfDeploymentFails (/Users/ruden/Desktop/development/webruden-api/node_modules/serverless-google-cloudfunctions/shared/monitorDeployment.js:71:11)
      at /Users/ruden/Desktop/development/webruden-api/node_modules/serverless-google-cloudfunctions/shared/monitorDeployment.js:42:17
      at processTicksAndRejections (internal/process/task_queues.js:97:5)

구글 클라우드 함수에서 사용하고 있는 예약어를 사용했을 때 발생하는 에러

구글 클라우드 함수 세부정보를 살펴보면 아래와 같이 함수에 런타임 환경 변수가 추가되었다면 정상적으로 배포가 완료된 것입니다.

구글 클라우드 함수 세부정보 런타임 환경 변수 반영된 예시

또다른 방법

serverless-dotenv-plugin 플러그인을 활용하면 .env에 설정해놓은 환경 변수가 배포될 때 자동으로 포함되어 배포됩니다.

yarn add --dev serverless-dotenv-plugin
// serverless.yml

plugins:
  - serverless-google-cloudfunctions
  - serverless-dotenv-plugin // 추가
sls deploy
Serverless: Deprecation warning: Detected ".env" files. Note that Framework now supports loading variables from those files when "useDotenv: true" is set (and that will be the default from next major release)
            More Info: https://www.serverless.com/framework/docs/deprecations/#LOAD_VARIABLES_FROM_ENV_FILES
Serverless: DOTENV: Loading environment variables from .env:

아래와 같은 문구와 함께 .env에 존재하는 환경 변수가 같이 deploy 된다.

728x90
반응형
그리드형

💖 저자에게 암호화폐로 후원하기 💖

아이콘을 클릭하면 지갑 주소가자동으로 복사됩니다