티스토리 뷰

ansible 등을 사용하면 필요 없을 것 같지만.. direnv를 통한 환경변수 사용을 정리합니다. 

direnv

 

프로젝트별로 환경변수를 관리하게 해주는 shell extension이다.

프로젝트 경로에 들어갔을 때. envrc에 있는 환경 변수들을 set 해준다. 프로젝트를 나오면 unset을 자동으로 해주기 때문에 편리하다. 

Install

$ brew install direnv
$ echo 'eval "$(direnv hook zsh)"' > ~/.zshrc

Usage

프로젝트 폴더에서 .envrc 파일을 만들고 direnv allow를 해주면 된다.

$ echo export env=local >> .envrc
$ direnv allow

global gitignore

프로젝트별로 따로 추가 해줄 수 있지만 global로 ignore 해줄 수 있다.

$ touch ~/.gitignore_global
$ git config --global core.excludesfile ~/.gitignore_global
$ echo '.env*' >> ~/.gitignore_global
$ echo '.direnv' >> ~/.gitignore_global

vscode

 

환경 분리

방법 1.

development, staging, production 환경에 따른 다른 값을 불러오고 싶을 때 사용할 수 있는 방법이다.

  1. 우선 환경에 따라 .envrc.<환경이름> 등으로 환경변수 값들을 파일로 분리한다.
  2. 사용할 환경 이름을 .envrc.context 파일에 넣어준다.
    $ echo <환경이름> > .envrc.context​
  3. $HOME 경로에 .direnvrc 파일을 만들어 아래 코드를 넣어준다.
    context=
    [[ -f .envrc.context ]] && context=$(< .envrc.context)
    watch_file ".envrc.context"
    
    if [[ -n "$context" ]]; then
      context_file=".envrc.$context"
      if [[ -f "$context_file" ]]; then
       echo "Loading context $context"
       source_env "$context_file"
      else
        echo "$context_file missing"
      fi
    fi​
     

direnv는. direnvrc를 먼저 읽게 되고. envrc.context에 있는 내용으로 파일을 찾아 환경변수들을 불러오게 된다.

 

방법 2.

direnv는 dotenv 지시자를 갖고 있기 때문에 dotenv를 실행시킬 수 있다.

watch_file .env

if test -e .env; then
dotenv .env.$(cat .env)
fi

dotenv-linter

reust로 작성된 env linter이다. 

# Installs the latest stable release
$ brew install dotenv-linter
$ dotenv-linter
Checking .env
.env:2 DuplicatedKey: The FOO key is duplicated
.env:3 UnorderedKey: The BAR key should go before the FOO key

Checking .env.test
.env.test:1 LeadingCharacter: Invalid leading character detected

Found 3 problems

Reference

반응형
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함