如何从气流包装的DAG中读取配置文件?

时间:2018-08-13 22:36:39

标签: airflow google-cloud-composer

气流packaged DAGs似乎是合理部署生产气流的重要组成部分。

我有一个带有动态subDAG的DAG,由配置文件驱动,例如:

config.yaml:

imports:
  - project_foo
  - project_bar`

产生诸如imports.project_{foo|bar}.step{1|2|3}之类的子任务。

我通常使用python的open函数,例如config = open(os.path.join(os.path.split(__file__)[0], 'config.yaml')来读入配置文件

不幸的是,使用打包的DAG时,会导致错误:

Broken DAG: [/home/airflow/dags/workflows.zip] [Errno 20] Not a directory: '/home/airflow/dags/workflows.zip/config.yaml'

这里有什么想法/最佳做法推荐吗?

1 个答案:

答案 0 :(得分:1)

有点麻烦,但我最终还是回过头来通过ZipFile读取zip文件内容。

import yaml
from zipfile import ZipFile
import logging
import re

def get_config(yaml_filename):
  """Parses and returns the given YAML config file.

  For packaged DAGs, gracefully handles unzipping.
  """
  zip, post_zip = re.search(r'(.*\.zip)?(.*)', yaml_filename).groups()
  if zip:
    contents = ZipFile(zip).read(post_zip.lstrip('/'))
  else:
    contents = open(post_zip).read()
  result = yaml.safe_load(contents)
  logging.info('Parsed config: %s', result)
  return result

它可以像您期望的那样在主dag.py中工作:

get_config(os.path.join(path.split(__file__)[0], 'config.yaml'))
相关问题