> ## Documentation Index
> Fetch the complete documentation index at: https://astronomer.io/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Programmatically generate Dags in Apache Airflow®

> Get to know how to programmatically (dynamically) generate Dags in Apache Airflow® using Python or YAML.

In Airflow, [Dags](https://airflow.apache.org/docs/apache-airflow/stable/core-concepts/dags.html) are defined as code. Most commonly, that code is Python, but other [language SDKs](https://astronomer.io/docs/airflow/airflow-multilanguage.md) let you write Dags and tasks in other languages, for example in Go or Java. No matter which language you use, the Dag processor runs the code in the Dag files in your [Dag bundle](https://astronomer.io/docs/airflow/airflow-dag-versioning.md#dag-bundles) and loads the Dags that the code creates.

If you want to create a large number of Dags, or create Dags based on configuration files, you can use code to generate them instead of defining every Dag and task explicitly.

In this guide, you'll learn about three main ways to generate Dags programmatically:

* [Single-file methods](#single-file-methods): One Python file creates many Dags.
* [Multiple-file methods](#multiple-file-methods): A script writes one Python file per Dag.
* [Define Dags in YAML](#define-dags-in-yaml): A Python package or, experimentally, Airflow itself turns YAML files into Dags.

> [!TIP]
>
> If you need to create tasks at runtime based on information that is only available at runtime, you can use:
>
> * [Dynamic task mapping](https://astronomer.io/docs/airflow/dynamic-tasks.md), which creates one task instance for each element of an input, for example one task per file in a folder. The mapped task instances run in parallel. You can also [dynamically map entire task groups](https://astronomer.io/docs/airflow/dynamic-tasks.md#map-over-task-groups).
> * [Task loops](https://astronomer.io/docs/airflow/airflow-task-loops.md), which run a task group repeatedly, one iteration after another, up to a maximum number of iterations. Optionally, you can define a condition that stops the loop earlier.

> [!TIP]
>
> **Other ways to learn**
>
> There are multiple resources for learning about this topic. See also:
>
> * Astronomer Academy: [Airflow: Dynamic Dags](https://academy.astronomer.io/path/airflow-dag-authoring/astro-runtime-dynamic-dags).
> * Airflow Summit 2026 talk by Volker Janz: [The Rise of Abstraction in Dag Authoring: From YAML to Minecraft](https://www.youtube.com/watch?v=fP-XcSs5FCU).

## Assumed knowledge

To get the most out of this guide, you should have an understanding of:

* Basic Python. See the [Python Documentation](https://docs.python.org/3/tutorial/index.html).
* Airflow Dags. See [Introduction to Airflow Dags](https://astronomer.io/docs/airflow/dags.md).

## When to dynamically generate Dags

Writing each Dag as a static Python file is the simplest option. Generating Dags can make sense when you want to:

* Create a large number of Dags that do similar things, with only a set of parameters changing between them.
* Enable other teams in your organization to write Dags in YAML, even if they don't know Airflow or Python.
* Standardize your Dags with your preferred defaults and only expose selected parameters.

This guide shows how to generate Dags with single and multiple Python files, from JSON config files, and from YAML. In theory, any input that you can translate into Python Dag code can be used to generate Dags, even blocks in [Minecraft](https://www.youtube.com/watch?v=fP-XcSs5FCU).

> [!NOTE]
>
> If you're looking to programmatically generate Dags because you prefer a different language to Python, check whether a [language SDK](https://astronomer.io/docs/airflow/airflow-multilanguage.md) is available for that language.
>
> If you're looking for standardization, you can also reuse [custom operators](https://astronomer.io/docs/airflow/airflow-importing-custom-hooks-operators.md) and [custom task group classes](https://astronomer.io/docs/airflow/task-groups.md#custom-task-group-classes) across Dags. [Blueprint](https://astronomer.io/docs/airflow/blueprint-overview) lets you define reusable multi-task templates in Python and use them in YAML.

> [!WARNING]
>
> Avoid [top-level code](https://airflow.apache.org/docs/apache-airflow/stable/best-practices.html#top-level-python-code) in your Dag files that connects to other systems, for example to query a database or call an API. Top-level code runs every time the Dag processor parses the file, so these connections are made again every `[dag_processor] min_file_process_interval`. This puts load on the other system, can incur costs for each request, and slows down Dag parsing.

## Single-file methods

One method for dynamically generating Dags is to have a single Python file which generates Dags based on some input parameter(s). For example, a list of APIs or tables. A common use case for this is an ETL or ELT-type pipeline where there are many data sources or destinations. This requires creating many Dags that all follow a similar pattern.

Some benefits of the single-file method:

* It's straightforward to implement.
* It can accommodate input parameters from many different sources.

The single-file method has the following disadvantages:

* Your visibility into the code behind any specific Dag is limited because a Dag file isn't created.
* Generation code is executed every time the Dag is parsed because this method requires a Python file in your [Dag bundle](https://astronomer.io/docs/airflow/airflow-dag-versioning.md#dag-bundles). How frequently this occurs is controlled by the [`[dag_processor] min_file_process_interval`](https://airflow.apache.org/docs/apache-airflow/stable/configurations-ref.html#config-dag-processor-min-file-process-interval) parameter. This can cause performance issues if the total number of Dags is large, or if the code is connecting to an external system such as a database.

In the following examples, the single-file method is implemented differently based on which input parameters are used for generating Dags.

### Example: Use a `create_dag` function

To dynamically create Dags from a file, you need to define a Python function that will generate the Dags based on an input parameter. In this case, you're going to define a Dag template within a `create_dag` function. The code here is very similar to what you would use when creating a single Dag, but it is wrapped in a function that allows for custom parameters to be passed in.

In this example, the input parameters can come from any source that the Python script can access. You can then set a simple loop (`range(1, 4)`) to generate these parameters and create one Dag for each set of parameters:

> [tab] TaskFlow
>
> ```python expandable wrap theme={null}
> from airflow.sdk import dag, task
> from pendulum import datetime
>
>
> def create_dag(dag_id, schedule, dag_number, default_args):
>     @dag(dag_id=dag_id, schedule=schedule, default_args=default_args)
>     def hello_world_dag():
>         @task()
>         def hello_world(*args):
>             print("Hello World")
>             print("This is DAG: {}".format(str(dag_number)))
>
>         hello_world()
>
>     generated_dag = hello_world_dag()
>
>     return generated_dag
>
>
> # build a dag for each number in range(1, 4)
> for n in range(1, 4):
>     dag_id = "hello_world_{}".format(str(n))
>
>     default_args = {"owner": "airflow", "start_date": datetime(2026, 10, 18)}
>
>     schedule = "@daily"
>
>     dag_number = n
>
>     globals()[dag_id] = create_dag(dag_id, schedule, dag_number, default_args)
> ```

> [tab] Traditional
>
> ```python expandable wrap theme={null}
> from pendulum import datetime
> from airflow.sdk import DAG
> from airflow.providers.standard.operators.python import PythonOperator
>
>
> def create_dag(dag_id, schedule, dag_number, default_args):
>     def hello_world_py():
>         print("Hello World")
>         print("This is DAG: {}".format(str(dag_number)))
>
>     generated_dag = DAG(dag_id, schedule=schedule, default_args=default_args)
>
>     with generated_dag:
>         PythonOperator(task_id="hello_world", python_callable=hello_world_py)
>
>     return generated_dag
>
>
> # build a dag for each number in range(1, 4)
> for n in range(1, 4):
>     dag_id = "hello_world_{}".format(str(n))
>
>     default_args = {"owner": "airflow", "start_date": datetime(2026, 10, 18)}
>
>     schedule = "@daily"
>     dag_number = n
>
>     globals()[dag_id] = create_dag(dag_id, schedule, dag_number, default_args)
> ```

The code above generates the following three Dags:

![Dags list in the Airflow UI filtered to the dynamic\_dags/basic folder, showing the three generated Dags hello\_world\_1, hello\_world\_2, and hello\_world\_3.](https://mintcdn.com/astronomer/nZJYjkS-_OYo057R/images/img/guides/3-4_dynamically-generating-dags_from_range.png?fit=max\&auto=format\&n=nZJYjkS-_OYo057R\&q=85\&s=270dce48421250d5c486c84f43ec8c26)

### Example: Generate Dags from environment variables

As mentioned previously, the input parameters don't have to be defined in the Dag file. Another common form of generating Dags is by setting values using environment variables.

You can define environment variables locally in the `.env` file of your Astro project or in the [Astro UI](https://astronomer.io/docs/astro/manage-env-vars.md) for your Astro deployments.

```text wrap theme={null}
DYNAMIC_DAG_NUMBER=9
```

You can retrieve this value by fetching the environment variable and passing it into your `range`. The `default` is set to 3 because you want the interpreter to register this file as valid regardless of whether the variable exists.

> [tab] TaskFlow
>
> ```python expandable wrap theme={null}
> from airflow.sdk import dag, task
> from pendulum import datetime
> import os
>
>
> def create_dag(dag_id, schedule, dag_number, default_args):
>     @dag(dag_id=dag_id, schedule=schedule, default_args=default_args)
>     def hello_world_dag():
>         @task()
>         def hello_world(*args):
>             print("Hello World")
>             print("This is DAG: {}".format(str(dag_number)))
>
>         hello_world()
>
>     generated_dag = hello_world_dag()
>
>     return generated_dag
>
>
> number_of_dags = os.getenv("DYNAMIC_DAG_NUMBER", default=3)
> number_of_dags = int(number_of_dags)
>
> for n in range(1, number_of_dags + 1):
>     dag_id = "hello_world_{}_env_var".format(str(n))
>
>     default_args = {"owner": "airflow", "start_date": datetime(2026, 10, 18)}
>
>     schedule = "@daily"
>     dag_number = n
>
>     globals()[dag_id] = create_dag(dag_id, schedule, dag_number, default_args)
> ```

> [tab] Traditional
>
> ```python expandable wrap theme={null}
> from airflow.sdk import DAG
> from airflow.providers.standard.operators.python import PythonOperator
> from pendulum import datetime
> import os
>
>
> def create_dag(dag_id, schedule, dag_number, default_args):
>     def hello_world_py():
>         print("Hello World")
>         print("This is DAG: {}".format(str(dag_number)))
>
>     generated_dag = DAG(dag_id, schedule=schedule, default_args=default_args)
>
>     with generated_dag:
>         PythonOperator(task_id="hello_world", python_callable=hello_world_py)
>
>     return generated_dag
>
>
> number_of_dags = os.getenv("DYNAMIC_DAG_NUMBER", default=3)
> number_of_dags = int(number_of_dags)
>
> for n in range(1, number_of_dags + 1):
>     dag_id = "hello_world_{}_env_var".format(str(n))
>
>     default_args = {"owner": "airflow", "start_date": datetime(2026, 10, 18)}
>
>     schedule = "@daily"
>     dag_number = n
>     globals()[dag_id] = create_dag(dag_id, schedule, dag_number, default_args)
> ```

With `DYNAMIC_DAG_NUMBER=9`, the code above generates the following nine Dags:

![Dags list in the Airflow UI filtered to the dynamic\_dags/env\_var folder, showing nine generated Dags from hello\_world\_1\_env\_var to hello\_world\_9\_env\_var.](https://mintcdn.com/astronomer/nZJYjkS-_OYo057R/images/img/guides/3-4_dynamically-generating-dags_from_env_var.png?fit=max\&auto=format\&n=nZJYjkS-_OYo057R\&q=85\&s=c878f7fa6edfc1139ef64484f8081953)

## Multiple-file methods

Another method for dynamically generating Dags is to use code to generate full Python files for each Dag. The end result of this method is having one Python file per generated Dag in your Dag bundle.

One way of implementing this method in production is to have a Python script that generates Dag files when executed as part of a CI/CD workflow. The Dags are generated during the CI/CD build and then deployed to Airflow.

Some benefits of this method:

* It's more scalable than single-file methods. Because the Dag files aren't being generated by parsing code in the Dag bundle, the Dag generation code isn't executed every time the Dag processor parses the files.
* Since Dag files are being explicitly created before deploying to Airflow, you have full visibility into the Dag code, including from the **Code** tab in the Airflow UI.

### Example: Generate Dags from JSON config files

One way of implementing the multiple-file method is by using a Python script to generate Dag files based on a set of JSON configuration files.

To start, you'll create a Dag 'template' file that defines the Dag's structure. This looks just like a regular Dag file, but specific variables have been added where information is going to be dynamically generated, namely `dag_id_to_replace`, `schedule_to_replace`, `bash_command_to_replace` and `env_var_to_replace`.

```python expandable wrap theme={null}
from airflow.sdk import dag
from airflow.providers.standard.operators.bash import BashOperator
from pendulum import datetime

@dag(
    dag_id=dag_id_to_replace,
    start_date=datetime(2026, 10, 18),
    schedule=schedule_to_replace,
)
def dag_from_config():
    BashOperator(
        task_id="say_hello",
        bash_command=bash_command_to_replace,
        env={"ENVVAR": env_var_to_replace},
    )

dag_from_config()

```

Next, you create a `dag-config` folder that contains a JSON config file for each Dag. Each config file defines the values for the placeholders in the Dag template file: the Dag ID, schedule, Bash command, and environment variable.

```json wrap theme={null}
{
    "dag_id": "dag_file_1",
    "schedule": "'@daily'",
    "bash_command": "'echo $ENVVAR'",
    "env_var": "'Hello! :)'"
}
```

A Python script creates the Dag files from the template and the config files. For every config file in the `dag-config` folder, the script copies the template into your Dag bundle and replaces the placeholders in the copy with the values from the config file.

```python expandable wrap theme={null}
import json
import os
import shutil
import fileinput

config_filepath = "include/dag-config/"
dag_template_filename = "include/dag-template.py"

for filename in os.listdir(config_filepath):
    f = open(config_filepath + filename)
    config = json.load(f)

    new_filename = "dags/" + config["dag_id"] + ".py"
    shutil.copyfile(dag_template_filename, new_filename)

    for line in fileinput.input(new_filename, inplace=True):
        line = line.replace("dag_id_to_replace", "'" + config["dag_id"] + "'")
        line = line.replace("schedule_to_replace", config["schedule"])
        line = line.replace("bash_command_to_replace", config["bash_command"])
        line = line.replace("env_var_to_replace", config["env_var"])
        print(line, end="")
```

To generate your Dag files, you can either run this script on demand or as part of your CI/CD workflow. After running the script, your project structure will be similar to the example below, where the `include` directory contains the files from which the Dags are generated, and the `dags` directory contains the two dynamically generated Dags:

```text expandable wrap theme={null}
.
├── dags
│   ├── dag_file_1.py
│   └── dag_file_2.py
└── include
    ├── dag-config
    │   ├── dag1-config.json
    │   └── dag2-config.json
    ├── dag-template.py
    └── generate-dag-files.py
```

## Define Dags in YAML

Instead of directly writing Python code that generates Dags, you can also define Dags in YAML, which an additional Python package or, experimentally, Airflow itself turns into Dags.

> [!TIP]
>
> If you prefer a different language to Python, check whether a [language SDK](https://astronomer.io/docs/airflow/airflow-multilanguage.md) is available for that language.

> [!NOTE]
>
> Airflow 3.4 adds an experimental way to define Dags in YAML without an additional package. See [YAML Dags](https://astronomer.io/docs/airflow/airflow-multilanguage.md#yaml-dags).

### Blueprint

[Blueprint](https://github.com/astronomer/blueprint) is an open source package for composing Dags from reusable templates. Data engineers define blueprints, which are multi-task templates, in Python, and other team members combine them into Dags in YAML or in a no-code interface in the [Astro IDE](https://astronomer.io/docs/astro/ide-overview.md). See [Blueprint](https://astronomer.io/docs/airflow/blueprint-overview). The following YAML combines two steps that use the same `my_math_etl_blueprint` template, defined in Python:

```yaml title="dags/my_math_etl.dag.yaml" wrap theme={null}
dag_id: my_math_etl
schedule: "@daily"

steps:
  my_math_etl:
    blueprint: my_math_etl_blueprint
    my_number: 23
    my_name: "Kathryn"

  my_second_math_etl:
    blueprint: my_math_etl_blueprint
    my_number: 19
    my_name: "Dominik"
    depends_on:
      - my_math_etl
```

### DAG Factory

[DAG Factory](https://github.com/astronomer/dag-factory) is an open source package that creates Dags from YAML files. Its YAML stays close to Airflow primitives: you set Dag parameters, tasks, operators, and dependencies in YAML. See the [DAG Factory tutorial](https://astronomer.io/docs/airflow/dag-factory.md). The following YAML defines a Dag with a task group and four tasks:

```yaml expandable wrap theme={null}
basic_example_dag:
  default_args:
    owner: "astronomer"
    start_date: 2026-10-18
  description: "Basic example DAG"
  tags: ["demo", "etl"]
  schedule: "@hourly"

  task_groups:
    extract:
      tooltip: "data extraction"

  tasks:
    extract_data_from_a:
      decorator: airflow.sdk.task
      python_callable: include.tasks.basic_example_tasks._extract_data
      task_group_name: extract

    extract_data_from_b:
      decorator: airflow.sdk.task
      python_callable: include.tasks.basic_example_tasks._extract_data
      task_group_name: extract

    store_data:
      decorator: airflow.sdk.task
      python_callable: include.tasks.basic_example_tasks._store_data
      processed_at: "{{ logical_date }}"
      data_a: +extract_data_from_a
      data_b: +extract_data_from_b
      dependencies: [extract]

    validate_data:
      operator: airflow.providers.standard.operators.bash.BashOperator
      bash_command: "echo data is valid"
      dependencies: [store_data]
```

## Scalability

Dynamically generating Dags can cause performance issues when used at scale. Whether or not any particular method will cause problems is dependent on your total number of Dags, your Airflow configuration, and your infrastructure. Methods where code generates Dags every time a file is parsed, such as the single-file method, are more likely to cause performance issues at scale.

The following Dag processor settings affect how Airflow handles generated Dags:

| Setting | Default | What it controls and when to change it |
| - | - | - |
| `[core] dagbag_import_timeout` | 30 seconds | How long the import of one Python file can take. Increase it if your files take a long time to parse, for example because they generate many Dags. |
| `[dag_processor] dag_file_processor_timeout` | 50 seconds | How long one Dag file processor can run, including the file import. Increase it if your Dags are heavy, for example highly complex Dags. If you increase `dagbag_import_timeout` above this value, increase this setting as well. |
| `[dag_processor] refresh_interval` | 300 seconds | How often the Dag processor looks for new files in a Dag bundle. Raise it to reduce bundle fetches, file scans, and metadata database writes. Lower it to reduce the wait time for new Dags, for example in a local development environment. |
| `[dag_processor] min_file_process_interval` | 30 seconds | How often the Dag processor parses known files again for changes. Every parse runs the code in the file. Raise it to lower the CPU load on the Dag processor in production. Lower it to reduce the wait time for changes to existing Dags during development. |
| `[dag_processor] parsing_processes` | 2 | How many processes parse Dag files in parallel. Increase it to speed up parsing if you have many Dag files. |

For more information, see [Fine-tuning your Dag processor performance](https://airflow.apache.org/docs/apache-airflow/stable/administration-and-deployment/dagfile-processing.html#fine-tuning-your-dag-processor-performance) in the Airflow documentation.
