1

I am new to airflow and got a task to add basic auth for Airflow Webserver. I implemented that using the below python code(from https://airflow.apache.org/docs/apache-airflow/1.10.1/security.html#password). I was able to create a user and authenticate to Airflow Webserver using that user/password.

# navigate to the airflow installation directory
$ cd ~/airflow
$ python
Python 2.7.9 (default, Feb 10 2015, 03:28:08)
Type "help", "copyright", "credits" or "license" for more information.
>>> import airflow
>>> from airflow import models, settings
>>> from airflow.contrib.auth.backends.password_auth import PasswordUser
>>> user = PasswordUser(models.User())
>>> user.username = 'new_user_name'
>>> user.email = 'new_user_email@example.com'
>>> user.password = 'set_the_password'
>>> session = settings.Session()
>>> session.add(user)
>>> session.commit()
>>> session.close()
>>> exit()

However, now I need to make sure that I only update the user instead of creating if the user already exists in airflow DB. Is there an attribute for the session object like get or getusers to know if the user already exists.

I am able to see the user created in airflowdb.users table in the database. But, I need to check from Python code instead.

Thanks in advance for your help.

hardy
  • 49
  • 1
  • 3

1 Answers1

1

session is an instance of the SQLAlchemy Session. Its execute() method allows you to run SQL expressions. So, you can simply select from the users table:

from airflow import settings
session = settings.Session()
users = session.execute("SELECT * FROM users").fetchall()
print(users)
session.close()

Output:

[(1, 'new_user_name', 'new_user_email@example.com', '$2b$12$qr7bCywAv4kTeakli.fTXuNUXonqSzXUqZIX/ZVIMceZDEIsKhgNO', 0)]
SergiyKolesnikov
  • 7,369
  • 2
  • 26
  • 47