Airflow 在气流中跨不同任务重用参数值
如何重用在任务之间运行DAG时计算的值 我正在尝试在我的DAG中生成一个时间戳,并在多个任务中使用它。到目前为止,我尝试设置一个变量和一个params值-没有任何效果,每个任务运行都是唯一的 这是我的密码:Airflow 在气流中跨不同任务重用参数值,airflow,Airflow,如何重用在任务之间运行DAG时计算的值 我正在尝试在我的DAG中生成一个时间戳,并在多个任务中使用它。到目前为止,我尝试设置一个变量和一个params值-没有任何效果,每个任务运行都是唯一的 这是我的密码: from datetime import datetime, timedelta from airflow import DAG from airflow.models import Variable from airflow.utils.dates import days_ago fr
from datetime import datetime, timedelta
from airflow import DAG
from airflow.models import Variable
from airflow.utils.dates import days_ago
from airflow.providers.amazon.aws.operators.athena import AWSAthenaOperator
from airflow.providers.amazon.aws.operators.glue import AwsGlueJobOperator
default_args = {
"sla": timedelta(hours=1),
}
config = Variable.get("config", deserialize_json=True)
athena_output_bucket = config["athena_output_bucket"]
glue_db = config["glue_db"]
bucket = config["bucket"]
region = config["region"]
def get_snapshot_timestamp(time_of_run=None):
if not time_of_run:
time_of_run = datetime.now()
timestamp = time_of_run.timestamp() * 1000
return str(int(timestamp))
class TemplatedArgsGlueOperator(AwsGlueJobOperator):
template_fields = ("script_args",)
table = "my_table"
with DAG(
"my-table-export",
default_args=default_args,
description="Export my table from DynamoDB to S3",
schedule_interval=timedelta(days=1),
start_date=days_ago(1),
params={
"snapshot_ts": get_snapshot_timestamp(),
"athena_output_location": f"s3://{athena_output_bucket}/{table}",
"table": table,
},
) as dag:
my_table_export_to_s3 = TemplatedArgsGlueOperator(
task_id="my_table_export_to_s3",
job_name="my-table-export-to-s3",
num_of_dpus=2,
region_name=region,
script_args={"--snapshot_ts": "{{ params.snapshot_ts }}"},
)
add_new_partition = AWSAthenaOperator(
task_id="add_new_partition",
query="""
ALTER TABLE {{ params.table }} ADD PARTITION (snapshot_ts = '{{ params.snapshot_ts }}')
LOCATION 's3://{{ var.json.config.bucket }}/{{ params.table }}/snapshot_ts={{ params.snapshot_ts }}'
""",
database=glue_db,
output_location="{{ params.athena_output_location }}",
)
update_latest_view = AWSAthenaOperator(
task_id="update_latest_view",
query="""
CREATE OR REPLACE VIEW {{ params.table }}_latest AS
SELECT * from {{ params.table }}
WHERE snapshot_ts = '{{ params.snapshot_ts }}'
""",
database=glue_db,
output_location="{{ params.athena_output_location }}",
)
my_table_export_to_s3 >> add_new_partition >> update_latest_view
我希望所有三个任务的快照都相同,但不同。我做错了什么?这应该可以通过xcom实现。xCom正是用来在各种任务之间交换信息的。引用 XCOM允许任务交换消息,允许更细微的消息形式 控制和共享状态。这个名字是的缩写 “交叉交流”。XCOM主要由键、值、, 和时间戳,但也跟踪属性,如 创建了XCom,并且它应该在何时可见。任何物体 可以作为XCom值使用,所以用户应该确保 使用适当大小的对象 在xCom中,pythonoperator用于调用函数。该函数将一些值推送到元数据数据库中名为xcom的表中。然后通过其他DAG或任务进行访问 下面是一个如何做到这一切的例子-