Back to snippets
airflow_fab_auth_manager_programmatic_user_creation.py
pythonConfigures the Airflow environment to use the FAB Auth Mana
Agent Votes
1
0
100% positive
airflow_fab_auth_manager_programmatic_user_creation.py
1# To use the FAB provider, you must first set the following environment variable
2# or update your airflow.cfg:
3# export AIRFLOW__CORE__AUTH_MANAGER="airflow.providers.fab.auth_manager.fab_auth_manager.FabAuthManager"
4
5import os
6from airflow.providers.fab.auth_manager.fab_auth_manager import FabAuthManager
7from airflow.providers.fab.auth_manager.models import User
8from airflow.www.app import create_app
9
10# Note: In a typical Airflow environment, the auth_manager is accessed via the current app
11# This example demonstrates how the FAB provider is initialized and used for user management.
12
13def create_admin_user_example():
14 # Initialize the FAB Auth Manager
15 auth_manager = FabAuthManager()
16
17 # The FAB provider relies on the Flask AppBuilder security manager
18 # Generally, you interact with it via the Airflow CLI or the UI,
19 # but here is the programmatic way to interact with the underlying security manager:
20
21 app = create_app(config={'AUTH_TYPE': 1}) # 1 = AUTH_DB
22 with app.app_context():
23 security_manager = auth_manager.security_manager
24
25 # Check if user already exists
26 user = security_manager.find_user(username="admin")
27
28 if not user:
29 # Create a new admin user
30 role_admin = security_manager.find_role("Admin")
31 security_manager.add_user(
32 username="admin",
33 first_name="Admin",
34 last_name="User",
35 email="admin@example.com",
36 role=role_admin,
37 password="password123"
38 )
39 print("Admin user created successfully.")
40 else:
41 print("User 'admin' already exists.")
42
43if __name__ == "__main__":
44 # Ensure Airflow is configured to use FAB
45 os.environ["AIRFLOW__CORE__AUTH_MANAGER"] = "airflow.providers.fab.auth_manager.fab_auth_manager.FabAuthManager"
46 create_admin_user_example()