E-NO
Apache Airflow security 8 Min Read

Apache Airflow Security Hardening: Practical Examples for Safe Operations

calendar_today Published: 2026-11-01
update Last Updated: 2026-11-02
analytics SEO Efficiency: 100%
Technical guide illustration for Apache Airflow Security Hardening: Practical Examples for Safe Operations.

Intro

Operators who harden Apache Airflow need more than a list of configuration flags. They need a reproducible path from an observed problem to a verified result. That path starts with knowing the installed version, deployment topology, prerequisites, and the exact component being inspected. Without that, a security change is just a guess with a blast radius.

This article is written for developers, DevOps consultants, and technical startup teams who manage their own Airflow deployments. It connects Airflow hardening, access control, secrets handling, and permissions to concrete commands, expected output, failure signals, and recovery decisions. The focus is Apache Airflow 2 and 3, including the important architectural differences between them.

The operational goal is safety: observe before changing, limit the blast radius, use placeholders instead of secrets, verify the result, and document how to recover if the expected state is not reached. Each section walks through a specific aspect of hardening and gives you a hands-on example you can adapt to your environment.

Version and Environment Inventory

Before touching any security setting, document the exact environment. Airflow 2 and Airflow 3 look similar from the outside but behave differently under the hood. Airflow 3 introduced an API server as a separate component and a dedicated DAG processor, so commands and health checks differ.

Run the following read-only commands and record the output:

airflow version
airflow info

Expected output for airflow version is a single line such as 2.10.3 or 3.0.2. The airflow info command prints a large diagnostic block. Save it to a file for later comparison:

airflow info > airflow-info-before-change.txt

Key fields to capture from airflow info: the Airflow version, executor (e.g. CeleryExecutor, KubernetesExecutor, LocalExecutor), metadata database type and version (e.g. PostgreSQL 16.4), and the list of installed providers. In Airflow 3, also note the API server and DAG processor status if shown.

Inspect the deployment topology: how are scheduler, webserver, workers, and metadata database deployed? For Airflow 3, confirm whether the API server is deployed as a separate service. This matters because security controls like API authentication and network segmentation apply differently if the API server is exposed independently.

Read-only health checks are the first line of diagnosis. In Airflow 3, do not treat an HTTP 200 from /health as proof that all services are healthy. Instead, inspect the detailed health endpoint:

curl -s http://airflow-api-server:8080/api/v2/monitor/health

A healthy response includes per-component status:

{
  "metadatabase": {"status": "healthy"},
  "scheduler": {"status": "healthy"},
  "triggerer": {"status": "healthy"},
  "dag_processor": {"status": "healthy"},
  "api_server": {"status": "healthy"}
}

If one component shows unhealthy or its status is missing, investigate that component before making any security changes.

For Airflow 2, use the command-line checks available in your version. In Airflow 2.2+, you can run:

airflow jobs check --job-type SchedulerJob
airflow db check

The scheduler check returns exit code 0 if the scheduler has recently recorded a heartbeat. The database check performs a simple connection test. Both are safe to run repeatedly and do not alter state.

Version-specific upgrades require a planned migration path. For Airflow 2.7+ and any Airflow 3.x, follow this sequence before upgrading:

  1. Review release notes and provider compatibility. Some providers require minimum Airflow versions.
  2. Back up the metadata database:
   pg_dump -Fc airflow_db > airflow_db_backup_$(date +%Y%m%d).dump

Adjust for your database engine (e.g. mysqldump for MySQL).

  1. Test representative DAGs in a staging environment with the new Airflow version.
  2. Run database migrations explicitly:
   airflow db migrate
  1. Do not restart services until the migration completes successfully. A restart does not replace a migration; it can leave the database schema inconsistent.

Document the exact commands and expected outputs for your environment. This inventory is the baseline for every hardening step that follows.

Safe Configuration Path

Airflow configuration is spread across airflow.cfg, environment variables, and the metadata database (for some settings like connections and variables). A safe configuration path means changing only what you intend, in a reversible way, and verifying the change after applying it.

Where configuration lives

Airflow reads configuration in this order of precedence (highest first):

  1. Environment variables with AIRFLOW__{SECTION}__{KEY} format
  2. airflow.cfg in the AIRFLOW_HOME directory
  3. Default values baked into the application

For example, to set the Fernet key used for encrypting connection passwords, you can use an environment variable:

export AIRFLOW__CORE__FERNET_KEY='your-base64-encoded-fernet-key-here'

Or set it in airflow.cfg under [core]:

[core]
fernet_key = your-base64-encoded-fernet-key-here

But never put a real secret in a file that is checked into version control. Use a secret manager or environment injection from your deployment system. The example above uses a placeholder; replace it with a value from your secret store.

Read-only checks before configuration changes

Before editing configuration, capture the effective settings in use. You can view the current configuration with:

airflow config list

To see a specific section:

airflow config get-value core fernet_key

This prints the currently active Fernet key. In a hardened environment, you may not want to print secrets to the terminal. Instead, check that it is set without revealing the value:

airflow config get-value core fernet_key | sed 's/./*/g'

This shows a masked version, useful for confirming the key is present without exposing it in logs or screen output.

Minimal safe change: example with API authentication

Airflow 3 enables API authentication by default for the API server. In Airflow 2, the experimental API is disabled by default but can be enabled. The more common API is the stable REST API at /api/v1/, which requires authentication if [api] auth_backends is set.

To verify API authentication is enabled, check the effective configuration:

airflow config get-value api auth_backends

Expected output for a secured deployment:

airflow.api.auth.backend.basic_auth,airflow.api.auth.backend.session

If the output is empty or shows only airflow.api.auth.backend.default, API endpoints may be accessible without authentication. To enable basic authentication, set the environment variable:

export AIRFLOW__API__AUTH_BACKENDS='airflow.api.auth.backend.basic_auth,airflow.api.auth.backend.session'

Then restart the webserver (Airflow 2) or API server (Airflow 3) for the change to take effect. Verify with a request to a protected endpoint:

curl -u admin:your-password http://airflow-webserver:8080/api/v1/dags

You should receive a JSON list of DAGs. Without the -u flag, you should receive a 401 Unauthorized response. If you receive 200 without credentials, authentication is not enforced.

Reversibility

For each change, document the rollback command. For example, to revert the API authentication setting, unset the environment variable and restart the service:

unset AIRFLOW__API__AUTH_BACKENDS
systemctl restart airflow-webserver

In Airflow 3, restart the API server service instead. The key is that the rollback is one command away, not a multi-step recovery.

Verification and Diagnostics

Verification means confirming that a security control is active and behaving as intended, without disrupting the system. This section covers concrete diagnostic commands and what their output should look like.

Access control verification

Airflow uses role-based access control (RBAC) with five default roles: Admin, User, Op, Viewer, and Public. To list users and their roles, use the Airflow CLI:

airflow users list

Sample output:

ID  | Username    | Email                 | First Name | Last Name | Roles
1   | admin       | [email protected]     | Admin      | User      | Admin
2   | data-engine | [email protected]      | Data       | Engineer  | User
3   | analyst     | [email protected]   | Ana        | Lyst      | Viewer

Confirm that each user has the minimum necessary role. The User role can create and edit DAGs but cannot manage connections or users. Viewer can only read. For operational tasks, create a custom role with granular permissions instead of granting Admin.

To list permissions for a role, query the Airflow metadata database directly (read-only):

SELECT r.name AS role, p.name AS permission
FROM ab_role r
JOIN ab_permission_view_role pvr ON r.id = pvr.role_id
JOIN ab_permission_view pv ON pvr.permission_view_id = pv.id
JOIN ab_permission p ON pv.permission_id = p.id
WHERE r.name = 'User';

Expected result includes permissions like can_read, can_edit, and can_delete on DAG and TaskInstance resources, but not on Connection or User resources. If you see can_create on Connection for the User role, that is a misconfiguration to fix.

Secrets handling verification

Airflow stores connection passwords and variable values encrypted at rest using the Fernet key. The encryption only works if the Fernet key is set correctly. Verify that the key is a valid Fernet key by using Python:

from cryptography.fernet import Fernet
import os
key = os.getenv('AIRFLOW__CORE__FERNET_KEY')
try:
    Fernet(key)
    print("Fernet key is valid")
except Exception as e:
    print(f"Invalid Fernet key: {e}")

A valid key is 32 URL-safe base64-encoded bytes. You can generate one with:

python -c "from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())"

Store this key in a secret manager, not in airflow.cfg. Rotation requires re-encrypting all connection passwords and variable values; Airflow provides airflow connections rotate-fernet-key and airflow variables rotate-fernet-key to help.

Verify that a connection is encrypted in the metadata database. Query the connection table:

SELECT conn_id, conn_type, password FROM connection LIMIT 5;

Password values should be a base64 blob (starting with gAAAA for Fernet-encrypted data), not plaintext. If you see plaintext passwords, the Fernet key is missing or the connection was created without encryption.

Network exposure verification

Check which ports are listening and from which interfaces. On the Airflow host, run:

ss -tulpn | grep -E '8080|8793|5555'

Common ports: 8080 for webserver/API, 8793 for worker logs, 5555 for Flower (Celery monitoring). The output should show bind addresses like 127.0.0.1:8080 if accessed through a reverse proxy, or 0.0.0.0:8080 if directly exposed. For hardening, bind to localhost and put a TLS-terminating proxy in front.

Check TLS configuration for the API/webserver. In Airflow 3, the API server can be configured to serve HTTPS directly. In airflow.cfg:

[api]
ssl_cert = /etc/ssl/certs/airflow.crt
ssl_key = /etc/ssl/private/airflow.key

Then verify with curl:

curl -v https://airflow.example.com/api/v2/health

Look for SSL connection using TLSv1.3 in the verbose output. If you see SSL certificate problem, the certificate chain is broken.

Failure Modes and Recovery

Hardening changes can break workflow execution, lock out users, or leak secrets. Anticipate these failure modes and have a recovery path ready. This section outlines common failures, how to detect them, and how to recover.

Locked out of UI due to authentication change

Symptom: After changing auth backends or user roles, you cannot log in to the Airflow UI. The webserver may show 500 errors or redirect loops.

Detection: Check webserver logs for authentication errors. Tail the log file:

tail -n 100 /var/log/airflow/webserver.log | grep -i 'auth'

Look for messages like Authentication failed or No auth backend configured.

Recovery: Revert the configuration change. If you changed auth_backends, set it back to the previous value and restart the webserver. If you accidentally removed your admin user's role, use the CLI to recreate or modify the user:

airflow users reset-password --username admin --password 'new-password'

If the user list is corrupt, you can create a new admin directly:

airflow users create --username recovery-admin --firstname Recover --lastname Admin --email [email protected] --role Admin --password 'recovery-password'

Always keep a break-glass admin account with a strong password stored in a password manager, separate from your daily account.

Fernet key rotation breaks decryption

Symptom: After rotating the Fernet key, connections and variables cannot be decrypted. DAG runs that fetch secrets fail with errors like InvalidToken or Unable to decrypt.

Detection: Check task logs for decryption errors. Use airflow connections get to test:

airflow connections get my_conn_id

If the command shows an error or the password is garbled, decryption failed.

Recovery: Rotate back to the old Fernet key. You must have kept the old key accessible. Airflow does not store old keys by default; you need to manage rotation manually. To avoid this, use a secret backend such as HashiCorp Vault or AWS Secrets Manager. Airflow's Secrets Backend feature can be configured to retrieve secrets dynamically, avoiding Fernet encryption dependencies.

To migrate to a secret backend, install the provider, configure [secrets] backend and backend_kwargs. Example for Vault:

[secrets]
backend = airflow.providers.hashicorp.secrets.vault.VaultBackend
backend_kwargs = {"url": "https://vault.example.com:8200", "token": ""}

The token should come from an environment variable or file, not hardcoded.

Scheduler health check false negative

Symptom: airflow jobs check --job-type SchedulerJob returns a non-zero exit code even though the scheduler is running.

Detection: The command returns exit code 1 and prints an error like SchedulerJob is not healthy.

Possible cause: The scheduler heartbeat interval is longer than the check threshold. By default, the check expects a heartbeat within 60 seconds. If the scheduler is overloaded or paused, the heartbeat may be delayed.

Recovery: Investigate scheduler logs for delays. Check the scheduler's last heartbeat in the metadata database:

SELECT job_type, latest_heartbeat FROM job WHERE job_type = 'SchedulerJob';

If the heartbeat is old, the scheduler may be hung. Restart the scheduler service. If the command reports unhealthy but tasks are still being scheduled, adjust the check parameters (see airflow jobs check --help for --heartbeat-threshold).

Common Pitfalls

Operators repeatedly make the same mistakes when hardening Airflow. Here are the most frequent pitfalls, why they happen, and how to avoid or recover.

Ignoring Airflow 3 architectural changes

Airflow 3 separates the API server and DAG processor, but many operators apply Airflow 2 procedures directly. Commands like airflow webserver are replaced by airflow api-server and airflow dag-processor. Health checks and configuration sections differ.

How to avoid: Read the Airflow 3 migration guide. Check the actual services running with ps aux | grep airflow. In Airflow 3, you should see separate processes for api-server, scheduler, dag-processor, and possibly triggerer. Update monitoring and health checks accordingly.

Hardcoding secrets in DAG code

Developers often put connection strings or API keys directly in DAG files because it is quick. These secrets then appear in Git history, logs, and task instance views.

Example of bad practice:

from airflow import DAG
from airflow.operators.python import PythonOperator

def my_task():
    api_key = "sk_live_1234567890"  # Hardcoded secret
    # use api_key

with DAG(...):
    task = PythonOperator(task_id="call_api", python_callable=my_task)

How to avoid: Use Airflow Variables or Connections with encrypted storage, or a secret backend. For example:

from airflow.models import Variable

def my_task():
    api_key = Variable.get("my_api_key")
    # use api_key

Then set the variable via CLI or UI, ensuring it is encrypted at rest. Review DAG code for secrets using static analysis tools like detect-secrets or gitleaks as part of your CI pipeline.

Overly broad RBAC roles

Granting the Admin role to every team member is tempting for convenience but violates least privilege. A data engineer with Admin role can modify connections, create users, and delete DAGs, increasing the blast radius of a compromised account.

How to avoid: Audit roles regularly with:

airflow users list

Create custom roles for specific needs. For example, a role that allows only running DAGs and viewing logs:

airflow roles create --role-name dag_runner
airflow roles add-permission --role-name dag_runner --resource DAG --action can_trigger
airflow roles add-permission --role-name dag_runner --resource TaskInstance --action can_read

Assign users to the least privileged role. Re-audit monthly or after any team change.

Not securing the metadata database

The Airflow metadata database stores DAG definitions, task states, and sensitive variables. If the database is exposed with default credentials or no network restrictions, attackers can read and modify everything.

How to avoid: Put the database on a private subnet. Use strong authentication and TLS. Enable connection encryption. For PostgreSQL, set sslmode=require in the SQLAlchemy connection string:

postgresql+psycopg2://airflow:password@db-host:5432/airflow?sslmode=require

Restrict database user permissions. The Airflow database user only needs SELECT, INSERT, UPDATE, DELETE on the Airflow schema; it should not have DDL permissions except during migrations. Create a separate user for migrations.

Operations Checklist

Use this checklist as a runbook for hardening a new or existing Airflow deployment. Each item includes an action, verification, and owner. Assign a single accountable owner, not a group. Review the checklist monthly or whenever the environment changes.

#ActionVerificationOwnerReview Frequency
1Document Airflow version, executor, database, and topology (airflow info)Output saved to version control; compare on each releaseDevOps Engineer: Priya ShahMonthly
2Verify API authentication is enabled (curl without credentials returns 401)curl -s -o /dev/null -w "%{http_code}" http://airflow/api/v1/dags returns 401Security Engineer: Tom NguyenMonthly
3Audit users and roles (airflow users list)No active users with unnecessary Admin roleTeam Lead: Maria GarciaWeekly
4Check Fernet key validity and encryption of connectionsQuery connection table; passwords are not plaintextSecurity Engineer: Tom NguyenQuarterly
5Validate scheduler health (airflow jobs check --job-type SchedulerJob)Exit code 0DevOps Engineer: Priya ShahDaily (automated)
6Review DAG code for hardcoded secrets (static scan)CI pipeline passes gitleaks with zero findingsPlatform Architect: James WilsonOn every merge
7Test recovery procedures (e.g., restore metadata DB from backup)Restore test succeeds in stagingDevOps Engineer: Priya ShahQuarterly
8Review network exposure (ports, TLS)ss -tulpn shows only required ports bound; TLS certificate validNetwork Engineer: Alex ChenMonthly
9Ensure secret backend is configured if using oneairflow config get-value secrets backend returns expected backendSecurity Engineer: Tom NguyenMonthly
10Keep break-glass admin account available and test loginLogin succeeds with recovery account; password rotated regularlySecurity Engineer: Tom NguyenMonthly

Each verification should be scripted where possible. For example, a cron job can run airflow jobs check and alert if the exit code is non-zero. For user audits, a simple Python script can query the metadata database and email a report.

Conclusion

Apache Airflow security hardening is not a one-time configuration burst. It is an ongoing practice that combines version awareness, least privilege, secrets discipline, and rigorous verification. Each recommendation in this article is version-scoped where necessary, observable through commands or endpoints, and reversible when the technology permits.

Start with a single low-risk verification from the Operations Checklist. Record the current state, run the documented check, compare the result with the expected signal, and note any dependencies such as external services like Spark, NiFi, or Hop integrations. That small step establishes the habit of evidence-based hardening.

A reliable technical workflow makes failure visible, protects sensitive values, limits changes to the intended resource, and defines recovery verification before an incident forces the decision. The goal is not just a secure Airflow, but an operations team that can prove it is secure and recover confidently when something breaks.

Article Quality Score

Reader usefulness 100%
  • check_circle Reader-ready guide
  • check_circle Practical examples included
  • check_circle Clean SEO article URL