[Airflow] Airflow context variable
Airflow context variable
- airflow는 task가 실행되는 특정 간격을 정의할 수 있는 추가 매개변수를 제공
-> 즉, 별도의 변수를 선언하지 않더라도 마치 환경변수처럼 사용할 수 있는 것이라고 이해하면 됨
- 이러한 매개변수 중 가장 중요한 변수는 DAG이 실행되는 날짜와 시간을 나타내는 execution_datedla
- execution_date는 DAG을 시작하는 시간의 특정 날짜가 아닌 스케줄 간격으로 실행되는 시작 시간을 나타내는 타임스탬프
- daily로 스케줄링이 되어 있다면 실행날짜가 1월 10일인데, 최근 실행된 job_date가 1월5일이라면, execution_date는 1월 6일로 찍히는 개념
-> backfill 까지 고려한 개념으로 execution_date와 같은 매개변수를 쓰면 backfill에서 날짜 리스트를 따로 고려하지 않아도 됨
- context variable을 쓰기 위해선 DAG에 설정해줘야하는 것이 있다!!!
-> provide_context=True 로 설정해주는것 꼭 해주자!!! -> DAG을 설정할때 default_args로 넣어줘도 상관없다.
## DAG전체에서 활용할 때
default_args = {
'start_date': datetime(2016, 1, 1),
'owner': 'airflow',
provide_context=True,
}
dag = DAG('my_dag', default_args=default_args)
op = DummyOperator(task_id='dummy', dag=dag)
## task operator 안에서 활용할 때
PythonOperator(
task_id="pass_context",
python_callable=_pass_context,
provide_context=True,
dag=dag,
)
- context variable은 진자 템플릿을 제공해서 간편하게 변수를 가져올 수 있음
def _get_data(year, month, day, hour, output_path, **_):
url = (
"https://dumps.wikimedia.org/other/pageviews/"
f"{year}/{year}-{month:0>2}/”
f"pageviews-{year}{month:0>2}{day:0>2}-{hour:0>2}0000.gz"
)
request.urlretrieve(url, output_path)
get_data = PythonOperator(
task_id="get_data",
python_callable=_get_data,
op_kwargs={
"year": "{{ execution_date.year }}",
"month": "{{ execution_date.month }}",
"day": "{{ execution_date.day }}",
"hour": "{{ execution_date.hour }}",
"output_path": "/tmp/wikipageviews.gz",
},
dag=dag,
)
context variable 종류
참조
https://livebook.manning.com/book/data-pipelines-with-apache-airflow/chapter-4/54
4 Templating tasks using the Airflow context · Data Pipelines with Apache Airflow
Rendering variables at runtime with templating · Variable templating with the PythonOperator versus other operators · Rendering templated variables for debugging purposes · Performing operations on external systems
livebook.manning.com
https://towardsdatascience.com/airflow-schedule-interval-101-bbdda31cc463
Airflow Schedule Interval 101
The airflow schedule interval could be a challenging concept to comprehend, even for developers work on Airflow for a while find difficult…
towardsdatascience.com