Airflow
Macro

About Macro

  • macro 변수의 필요성
select name, address
from tbl_reg
where reg_date between ?? and ?? 
 

from date time -> data_interval_start

to date tiem -> data_interval_end

![[SCR-20250302-lggw.png]]

  • Template 변수 기반 다양하 날짜 연산이 가능하도록 연산 모듈을 제공하고 있음
  • Macro를 잘 쓰려면 파이썬 datetime 및 dateutil 라이브러리에 익숙해져야 함

Macros (opens in a new tab)

Macros are a way to expose objects to your templates and live under the macros namespace in your templates.

A few commonly used libraries and methods are made available.

VariableDescription
macros.datetimeThe standard lib’s datetime.datetime (opens in a new tab)
macros.timedeltaThe standard lib’s datetime.timedelta (opens in a new tab)
macros.dateutilA reference to the dateutil package
macros.timeThe standard lib’s datetime.time (opens in a new tab)
macros.uuidThe standard lib’s uuid (opens in a new tab)
macros.randomThe standard lib’s random (opens in a new tab)

3. Bash Operator With Macro 실습해보기

  • 예시 1 ) 매월 말일 수행되는 Dag에서 변수 START_DATE: 전월 말일, 변수 END_DATE : 어제로 env 셋팅하기
  • 예시 2) 매월 둘째주 토요일에 수행되는 Dag에서 변수 START_DATE: 2주 전 월요일 변수 END_DATE: 2주 전 토요일로 env 셋팅하기
from airflow import DAG
import pendulum
from airflow.operators.bash import BashOperator
 
  
 
with DAG(
	dag_id="dags_bash_with_macro_eg2",
	schedule="10 0 * * 6#2", # 매월 둘째 주 토요일 00:10 실행
	start_date=pendulum.datetime(2025, 3, 2, tz="Asia/Seoul"),
	catchup=False,
) as dag:
 
  
 
bash_task_2 = BashOperator(
 
	task_id="bash_task_2",
	env={
		'START_DATE': '{{ (data_interval_start.in_timezone("Asia/Seoul") - macros.dateutil.relativedelta.relativedelta(days=19)) | ds }}',
		'END_DATE': '{{ (data_interval_end.in_timezone("Asia/Seoul") - macros.dateutil.relativedelta.relativedelta(days=14)) | ds }}',
},
	bash_command='echo "START_DATE: $START_DATE" && echo "END_DATE: $END_DATE"',
)