authoring-dags

Fluxo de trabalho guiado para criação de DAGs do Apache Airflow com integração de validação e testes. Abordagem estruturada em seis fases: descobrir o ambiente e padrões existentes, planejar a estrutura da DAG, implementar seguindo as melhores práticas, validar com comandos da CLI af, testar com consentimento do usuário e iterar em correções. Comandos da CLI para descoberta (af config connections, af config providers, af dags list) e validação (af dags errors, af dags get, af dags explore) fornecem feedback imediato sobre a DAG...

npx skills add https://github.com/astronomer/agents --skill authoring-dags

DAG Authoring Skill

This skill guides you through creating and validating Airflow DAGs using best practices and af CLI commands.

For testing and debugging DAGs, see the testing-dags skill which covers the full test -> debug -> fix -> retest workflow.


Running the CLI

These commands assume af is on PATH. Run via astro otto to get it automatically, or install standalone with uv tool install astro-airflow-mcp.


Workflow Overview

+-----------------------------------------+
| 1. DISCOVER                             |
|    Understand codebase & environment    |
+-----------------------------------------+
                 |
+-----------------------------------------+
| 2. PLAN                                 |
|    Propose structure, get approval      |
+-----------------------------------------+
                 |
+-----------------------------------------+
| 3. IMPLEMENT                            |
|    Write DAG following patterns         |
+-----------------------------------------+
                 |
+-----------------------------------------+
| 4. VALIDATE                             |
|    Check import errors, warnings        |
+-----------------------------------------+
                 |
+-----------------------------------------+
| 5. TEST (with user consent)             |
|    Trigger, monitor, check logs         |
+-----------------------------------------+
                 |
+-----------------------------------------+
| 6. ITERATE                              |
|    Fix issues, re-validate              |
+-----------------------------------------+

Phase 1: Discover

Before writing code, understand the context.

Explore the Codebase

Use file tools to find existing patterns:

  • Glob for **/dags/**/*.py to find existing DAGs
  • Read similar DAGs to understand conventions
  • Check requirements.txt for available packages

Query the Airflow Environment

Use af CLI commands to understand what's available:

CommandPurpose
af config connectionsWhat external systems are configured
af config variablesWhat configuration values exist
af config providersWhat operator packages are installed
af config versionVersion constraints and features
af dags listExisting DAGs and naming conventions
af config poolsResource pools for concurrency

Example discovery questions:

  • "Is there a Snowflake connection?" -> af config connections
  • "What Airflow version?" -> af config version
  • "Are S3 operators available?" -> af config providers

Phase 2: Plan

Based on discovery, propose:

  1. DAG structure - Tasks, dependencies, schedule
  2. Operators to use - Based on available providers
  3. Connections needed - Existing or to be created
  4. Variables needed - Existing or to be created
  5. Packages needed - Additions to requirements.txt

Get user approval before implementing.


Phase 3: Implement

Write the DAG following best practices (see below). Key steps:

  1. Create DAG file in appropriate location
  2. Update requirements.txt if needed
  3. Save the file

Phase 4: Validate

Use af CLI as a feedback loop to validate your DAG.

Step 1: Check Import Errors

After saving, check for parse errors (Airflow will have already parsed the file):

af dags errors
  • If your file appears -> fix and retry
  • If no errors -> continue

Common causes: missing imports, syntax errors, missing packages.

Step 2: Verify DAG Exists

af dags get <dag_id>

Check: DAG exists, schedule correct, tags set, paused status.

Step 3: Check Warnings

af dags warnings

Look for deprecation warnings or configuration issues.

Step 4: Explore DAG Structure

af dags explore <dag_id>

Returns in one call: metadata, tasks, dependencies, source code.

On Astro

If you're running on Astro, you can also validate locally before deploying:

  • Parse check: Run astro dev parse to catch import errors and DAG-level issues without starting a full Airflow environment
  • DAG-only deploy: Once validated, use astro deploy --dags for fast DAG-only deploys that skip the Docker image build — ideal for iterating on DAG code

Phase 5: Test

See the testing-dags skill for comprehensive testing guidance.

Once validation passes, test the DAG using the workflow in the testing-dags skill:

  1. Get user consent -- Always ask before triggering
  2. Trigger and wait -- af runs trigger-wait <dag_id> --timeout 300
  3. Analyze results -- Check success/failure status
  4. Debug if needed -- af runs diagnose <dag_id> <run_id> and af tasks logs <dag_id> <run_id> <task_id>

Quick Test (Minimal)

# Ask user first, then:
af runs trigger-wait <dag_id> --timeout 300

For the full test -> debug -> fix -> retest loop, see testing-dags.


Phase 6: Iterate

If issues found:

  1. Fix the code
  2. Check for import errors: af dags errors
  3. Re-validate (Phase 4)
  4. Re-test using the testing-dags skill workflow (Phase 5)

CLI Quick Reference

PhaseCommandPurpose
Discoveraf config connectionsAvailable connections
Discoveraf config variablesConfiguration values
Discoveraf config providersInstalled operators
Discoveraf config versionVersion info
Validateaf dags errorsParse errors (check first!)
Validateaf dags get <dag_id>Verify DAG config
Validateaf dags warningsConfiguration warnings
Validateaf dags explore <dag_id>Full DAG inspection

Testing commands -- See the testing-dags skill for af runs trigger-wait, af runs diagnose, af tasks logs, etc.


Best Practices & Anti-Patterns

For code patterns and anti-patterns, see reference/best-practices.md.

Read this reference when writing new DAGs or reviewing existing ones. It covers what patterns are correct (including Airflow 3-specific behavior) and what to avoid.


Related Skills

  • testing-dags: For testing DAGs, debugging failures, and the test -> fix -> retest loop
  • debugging-dags: For troubleshooting failed DAGs
  • deploying-airflow: For deploying DAGs to production (Astro or open-source)
  • migrating-airflow-2-to-3: For migrating DAGs to Airflow 3

Mais skills de astronomer

airflow
astronomer
Consulte, gerencie e solucione problemas de DAGs, execuções, tarefas e configuração de sistema do Apache Airflow. Suporta mais de 30 comandos para inspeção de DAGs, gerenciamento de execuções, registro de tarefas, consultas de configuração e acesso direto à API REST. Gerencie múltiplas instâncias do Airflow com configuração persistente; descubra automaticamente implantações locais e Astro. Dispare execuções de DAG de forma síncrona (aguardando conclusão) ou assíncrona, diagnostique falhas, limpe execuções para repetição e acesse logs de tarefas com filtragem por repetição/índice de mapa. Saída...
official
airflow-hitl
astronomer
Portões de aprovação humana, entradas de formulário e ramificações em DAGs do Airflow usando operadores adiáveis. Quatro tipos de operadores: ApprovalOperator para decisões de aprovar/rejeitar, HITLOperator para seleção de múltiplas opções com formulários, HITLBranchOperator para roteamento de tarefas orientado por humanos e HITLEntryOperator para coleta de dados de formulário. Todos os operadores são adiáveis, liberando slots de worker enquanto aguardam resposta humana via a aba Ações Necessárias da interface do Airflow ou API REST. Suporta recursos opcionais incluindo personalização...
official
airflow-plugins
astronomer
Crie plugins do Airflow 3.1+ que incorporam aplicativos FastAPI, páginas de UI personalizadas, componentes React, middleware, macros e links de operador diretamente na interface do Airflow. Use…
official
analyzing-data
astronomer
Consulte seu data warehouse para responder perguntas de negócios com padrões em cache e mapeamentos de conceitos. Suporta busca de padrões e cache para tipos de perguntas repetidas, com registro de resultados para melhorar consultas futuras. Inclui cache de mapeamento conceito-tabela e descoberta de esquemas de tabela via INFORMATION_SCHEMA ou grep no código-fonte. Fornece funções de kernel run_sql() e run_sql_pandas() que retornam DataFrames Polars ou Pandas para análise. Comandos CLI para gerenciar caches de conceitos, padrões e tabelas, além de...
official
annotating-task-lineage
astronomer
Anotar tarefas do Airflow com linhagem de dados usando inlets e outlets. Suporta objetos OpenLineage Dataset, Assets do Airflow e Datasets do Airflow para definir entradas e saídas em bancos de dados, data warehouses e armazenamento em nuvem. Use como fallback quando operadores não possuem extratores OpenLineage integrados; segue um sistema de precedência de quatro níveis onde extratores personalizados e métodos OpenLineage têm prioridade. Inclui auxiliares de nomenclatura de datasets para Snowflake, BigQuery, S3 e PostgreSQL para garantir consistência...
official
blueprint
astronomer
Defina modelos reutilizáveis de grupos de tarefas do Airflow com validação Pydantic e componha DAGs a partir de YAML. Use ao criar modelos de blueprint, compor DAGs a partir de…
official
checking-freshness
astronomer
Verifique a atualização dos dados analisando os timestamps das tabelas e os padrões de atualização em relação a uma escala de obsolescência. Identifica colunas de timestamp usando padrões comuns de nomenclatura ETL (_loaded_at, _updated_at, created_at, etc.) e consulta seus valores máximos para determinar a idade. Classifica os dados em quatro status de atualização: Atualizados (< 4 horas), Desatualizados (4–24 horas), Muito Desatualizados (> 24 horas) ou Desconhecido (nenhum timestamp encontrado). Fornece modelos SQL para verificar o horário da última atualização e as tendências de contagem de linhas nos dias recentes para...
official
cosmos-dbt-core
astronomer
Converta projetos dbt Core em DAGs ou TaskGroups do Airflow usando o Astronomer Cosmos. Suporta três padrões de montagem: DbtDag independente, DbtTaskGroup dentro de DAGs existentes e operadores Cosmos individuais para controle refinado. Escolha entre oito modos de execução (WATCHER, LOCAL, VIRTUALENV, KUBERNETES, AIRFLOW_ASYNC e outros) com base nas necessidades de isolamento e desempenho. Oferece três estratégias de parsing (dbt_manifest, dbt_ls, dbt_ls_file, automática) para equilibrar velocidade e complexidade do seletor...
official