
Shell 스크립트란?
▪ Unix/Linux Shell 명령을 이용해 만들어지고, 인터프리터에 의해 한줄씩 처리되는 파일
▪ Echo, mkdir, cd 등 기본적인 Shell 명령어를 입력하여 작성하며, 변수 입력, For 문, if 문, 함수도 사용 가능
▪ 주로 파일명에 .sh 확장자를 붙임
Shell 스크립트가 필요한 이유
▪ 복잡한 로직을 처리하는 경우 Shell 명령어의 재사용을 위해
Worker 컨테이너가 Shell 스크립트를 실행하기 위해서는..
▪ 컨테이너는 외부의 파일을 인식할 수 없으며, 컨테이너 안에 파일을 만들 경우 컨테이너 재시작시 파일이 사라짐
▪ 따라서 plugins에 Shell 스크립트를 저장해야함

1. Shell 스크립트 만들기
▪ 해당 directory로 이동하고 shell 파일 만들기
cd ./airflow/plugins/shell # shell directory로 이동 vi select_fruit.sh # vi 편집기로 shell 파일 생성

▪ "i"를 눌러서 아래의 shell 명령어를 입력하고 ":wq!" 명령어로 쓰고 나오기
FRUIT=$1 if [ $FRUIT == APPLE ]; then echo "You selected Apple" elif [ $FRUIT == ORANGE ]; then echo "You selected Orange!" elif [ $FRUIT == GRAPE ]; then echo "You selected Grape!" else echo "Yout selected other Fruit!" fi

▪ shell 파일에 실행 권한 추가
▪ "ls -al"로 확인해보면 실행 권한이 추가되었음
chmod +x select_fruit.sh # 실행 권한 추가

▪ 다음과 같이 shell 파일을 실행할 수 있음
./select_fruit.sh ORANGE ./select_fruit.sh GRAPE ./select_fruit.sh else

2. Shell 파일 git push
▪ 처음 git push 할 경우 GitHub 아이디와 비밀번호을 입력해서 인증
▪ 이때 보안 문제로 비밀번호 대신 토큰을 입력해야함
▪ 토큰 생성은 해당 링크 참고 -> https://blog.pocu.academy/ko/2022/01/06/how-to-generate-personal-access-token-for-github.html
# airflow 디렉토리로 이동 cd cd airflow git add plugins/ git commit -m "plugins 폴더 추가" # 처음 commit할 경우 이메일 정보와 유저이름 입력하기 git config --global user.email "user@email.com" git config --global user.name "username" git commit -m "plugins 폴더 추가" # 처음 git push할 경우 아이디와 토큰값 입력하라고 나옴 git push
3. docker-compose.yaml 파일 수정
▪ Shell 파일을 docker 컨테이너가 인식할 수 있도록 volumes 항목 수정이 필요함
▪ vi 편집기로 docker-compose.yaml 파일 열고, plugins 디렉토리를 다음과 같이 변경
▪ ":wq!" 명령어 입력해서 저장하고 나오기
cd vi docker-compose.yaml

4. dags_bash_select_fruit.py
▪ Shell 파일을 실행하는 BashOperator로 구성된 DAG 파일
▪ 매월 첫번째 주 토요일 0시 10분에 작업하도록 스케줄링
▪ 업로드했던 Shell 파일 git pull하고, 해당 dag 파일 git push
from airflow import DAG from airflow.operators.bash import BashOperator import datetime import pendulum with DAG( dag_id="dags_bash_select_fruit", schedule="10 0 * * 6#1", start_date=pendulum.datetime(2023, 11, 17, tz="Asia/Seoul"), catchup=False, ) as dag: t1_orange = BashOperator( task_id="t1_orange", bash_command="/opt/airflow/plugins/shell/select_fruit.sh ORANGE", ) t2_avocado = BashOperator( task_id="t2_avocado", bash_command="/opt/airflow/plugins/shell/select_fruit.sh AVOCADO", ) t1_orange >> t2_avocado
5. Dag 실행하기
▪ dag파일 git pull 한뒤 airflow 서비스 올리기
▪ webserver에 접속해서 확인해보면 dag이 정상적으로 올라왔음

▪ dag을 unpause시키고, log를 확인해보면 다음과 같이 Shell 파일이 실행됨


참고:
Airflow 마스터 클래스 강의 - 인프런
데이터 파이프라인을 효율적으로 만들고 관리하기 위한 Orchestration 도구인 Airflow에 대해 배우는 강의입니다. 초보자도 차근차근 배울 수 있는 Airflow 마스터 클래스, 환영합니다!, 데이터 파이프
www.inflearn.com
'Data Engineering > Airflow' 카테고리의 다른 글
[Airflow] Python Operator 기본 (0) | 2024.01.21 |
---|---|
[Airflow] Email Operator 사용하기 (1) | 2024.01.21 |
[Airflow] Task 연결하기 (2) | 2024.01.16 |
[Airflow] Cron 스케줄 (0) | 2024.01.16 |
[Airflow] Postgres 컨테이너 설치 및 network 설정 (0) | 2024.01.05 |