# First steps

> Set up an Apache Airflow cluster using Stackable Operator, PostgreSQL, and Redis. Run and monitor example workflows (DAGs) via the web UI or command line.

Once you have followed the steps in the [Installation](https://docs.stackable.tech/home/stable/airflow/getting_started/installation/index.md) section to install the Operator and its dependencies, deploy an Airflow cluster and its dependencies. Afterward you can [verify that it works](https://docs.stackable.tech/home/stable/airflow/getting_started/first_steps/index.md) by running and tracking an example DAG.

## Setup

With the external dependencies required by Airflow (Postgresql and Redis) installed, install the Airflow Stacklet itself.

Supported versions for PostgreSQL and Redis can be found in the [Airflow documentation](https://airflow.apache.org/docs/apache-airflow/stable/installation/prerequisites.html#prerequisites).

## Airflow secrets

Secrets are required for the mandatory metadata database connection and the Airflow admin user. When using celery executors it’s also required to provide information for the celery database and broker. Create a file called `airflow-credentials.yaml`:

```yaml
---
apiVersion: v1
kind: Secret
metadata:
  name: airflow-admin-credentials
type: Opaque
stringData:
  adminUser.username: airflow
  adminUser.firstname: Airflow
  adminUser.lastname: Admin
  adminUser.email: airflow@airflow.com
  adminUser.password: airflow
---
apiVersion: v1
kind: Secret
metadata:
  name: airflow-postgresql-credentials
stringData:
  username: airflow
  password: airflow
---
# Only needed when using celery workers (instead of Kubernetes executors)
apiVersion: v1
kind: Secret
metadata:
  name: airflow-redis-credentials
stringData:
  username: ""
  password: redis
```

And apply it:

```bash
kubectl apply -f airflow-credentials.yaml
```

`airflow-postgresql-credentials` contains credentials for the SQL database storing the Airflow metadata. In this example we will use the same database for both the Airflow job metadata as well as the Celery broker metadata.

`airflow-redis-credentials` contains credentials for the the Redis instance used for queuing the jobs submitted to the Airflow executor(s).

`airflow-admin-credentials`: the `adminUser.*` fields are used to create the initial admin user.

> **Note:** The admin user is disabled if you use a non-default authentication mechanism like LDAP or OIDC.

## Airflow

An Airflow cluster is made up of several components, two of which are optional:

-   `webserver`: this provides the main UI for user-interaction

-   `executors`: the CeleryExecutor or KubernetesExecutor nodes over which the job workload is distributed by the scheduler

-   `scheduler`: responsible for triggering jobs and persisting their metadata to the backend database

-   `dagProcessors`: (Optional) responsible for monitoring, parsing and preparing DAGs for processing. If this role is not specified then the process will be started as a scheduler subprocess (Airflow 2.x), or as a standalone process in the same container as the scheduler (Airflow 3.x+)

-   `triggerers`: (Optional) DAGs making use of deferrable operators can be used together with one or more triggerer processes to free up worker slots. This deferral process is also useful for providing a measure of high availability


Create a file named `airflow.yaml` with the following contents:

```yaml
---
apiVersion: airflow.stackable.tech/v1alpha1
kind: AirflowCluster
metadata:
  name: airflow
spec:
  image:
    productVersion: 3.2.2
    pullPolicy: IfNotPresent
  clusterConfig:
    loadExamples: true
    exposeConfig: false
    credentialsSecretName: airflow-admin-credentials
    metadataDatabase:
      postgresql:
        host: airflow-postgresql
        database: airflow
        credentialsSecretName: airflow-postgresql-credentials
    celeryResultsBackend:
      postgresql:
        host: airflow-postgresql
        database: airflow
        credentialsSecretName: airflow-postgresql-credentials
    celeryBroker:
      redis:
        host: airflow-redis-master
        credentialsSecretName: airflow-redis-credentials
  webservers:
    roleConfig:
      listenerClass: external-unstable
    roleGroups:
      default:
        replicas: 1
  celeryExecutors:
    roleGroups:
      default:
        replicas: 1
  schedulers:
    roleGroups:
      default:
        replicas: 1
  dagProcessors:
    roleGroups:
      default:
        replicas: 1
  triggerers:
    roleGroups:
      default:
        replicas: 1
```

And apply it:

```
kubectl apply -f airflow.yaml
```

Where:

-   `metadata.name`: contains the name of the Airflow cluster.

-   `spec.clusterConfig.metadataDatabase`: specifies one of the supported database types (in this case, `postgresql`) along with references to the host, database and the secret containing the connection credentials.

-   the product version of the Docker image provided by Stackable must be set in `spec.image.productVersion`.

-   `spec.celeryExecutors`: deploy executors managed by Airflow’s Celery engine. Alternatively you can use `kuberenetesExectors` that use Airflow’s Kubernetes engine for executor management. For more information see [https://airflow.apache.org/docs/apache-airflow/stable/executor/index.html#executor-types](https://airflow.apache.org/docs/apache-airflow/stable/executor/index.html#executor-types)).

-   `spec.celeryExecutors.resultBackend`: specifies one of the supported database types (in this case, `postgresql`) along with references to the host, database and the secret containing the connection credentials.

-   `spec.celeryExecutors.broker`: specifies one of the supported queue/broker types (in this case, `redis`) along with references to the host and the secret containing the connection credentials.

-   `spec.clusterConfig.loadExamples`: this key is optional and defaults to `false`. It is set to `true` here as the example DAGs are used when verifying the installation.

-   `spec.clusterConfig.exposeConfig`: this key is optional and defaults to `false`. It is set to `true` only as an aid to verify the configuration and should never be used as such in anything other than test or demo clusters.

-   `spec.clusterConfig.credentialsSecretName`: specifies the secret containing the Airflow admin user information.


> **Note:** The version you need to specify for `spec.image.productVersion` is the desired version of Apache Airflow. You can optionally specify the `spec.image.stackableVersion` to a certain release like `23.11.0` but it is recommended to leave it out and use the default provided by the operator. Check our [image registry](https://oci.stackable.tech/) for a list of available versions. Information on how to browse the registry can be found [here](https://docs.stackable.tech/home/stable/contributor/project-overview/index.md). It should generally be safe to simply use the latest version that is available.

> **Note:** Refer to [Database connections](https://docs.stackable.tech/home/stable/airflow/usage-guide/database-connections/index.md) for more information about database/broker connections.

This creates the actual Airflow cluster.

After a while, all the Pods in the StatefulSets should be ready:

```bash
kubectl get statefulset
```

The output should show all pods ready, including the external dependencies:

```
NAME                            READY   AGE
airflow-postgresql              1/1     16m
airflow-redis-master            1/1     16m
airflow-redis-replicas          1/1     16m
airflow-scheduler-default       1/1     11m
airflow-webserver-default       1/1     11m
airflow-celery-executor-default 1/1     11m
airflow-dagprocessor-default    1/1     11m
airflow-triggerer-default       1/1     11m
```

When the Airflow cluster has been created and the database is initialized, Airflow can be opened in the browser: the webserver UI port defaults to `8080` can be forwarded to the local host:

```
kubectl port-forward svc/airflow-webserver 8080 2>&1 >/dev/null &
```

## Verify that it works

The Webserver UI can now be opened in the browser with `[http://localhost:8080](http://localhost:8080)`. Enter the admin credentials from the Kubernetes secret:

![Airflow login screen](https://docs.stackable.tech/home/stable/airflow/_images/getting_started/airflow_login.png)

Since the examples were loaded in the cluster definition, they appear under the DAGs tabs:

![Example Airflow DAGs](https://docs.stackable.tech/home/stable/airflow/_images/getting_started/airflow_dags.png)

Select one of these DAGs by clicking on the name in the left-hand column e.g. `example_trigger_target_dag`. Click on the arrow in the top right of the screen, select "Trigger DAG" and the DAG nodes are automatically highlighted as the job works through its phases.

![Airflow DAG in action](https://docs.stackable.tech/home/stable/airflow/_images/getting_started/airflow_running.png)

Great! You have set up an Airflow cluster, connected to it and run your first DAG!

Alternative: Using the command line

If you prefer to interact directly with the API instead of using the web interface, you can use the following commands. The DAG is one of the example DAGs named `example_trigger_target_dag`. To trigger a DAG run via the API requires an initial extra step to ensure that the DAG is not in a paused state:

```bash
  ACCESS_TOKEN=$(
    curl -s -XPOST http://localhost:8080/auth/token \
    -H 'Content-Type: application/json' \
        -d '{
        "username": "airflow",
        "password": "airflow"
        }' | jq '.access_token' | tr -d '"'
  )
  curl -s -H "Authorization: Bearer $ACCESS_TOKEN" -H "Content-Type: application/json" \
  -XPATCH http://localhost:8080/api/v2/dags/example_trigger_target_dag \
  -d '{"is_paused": false}' | jq '.is_paused'
```

A DAG can then be triggered by providing the DAG name (in this case, `example_trigger_target_dag`). The response identifies the DAG identifier, which can be parse out of the JSON like this:

```bash
  ACCESS_TOKEN=$(
    curl -s -XPOST http://localhost:8080/auth/token \
    -H 'Content-Type: application/json' \
        -d '{
        "username": "airflow",
        "password": "airflow"
        }' | jq '.access_token' | tr -d '"'
  )
  curl -s -H "Authorization: Bearer $ACCESS_TOKEN" -H "Content-Type: application/json" \
  -XPOST http://localhost:8080/api/v2/dags/example_trigger_target_dag/dagRuns \
    -d '{"logical_date": null,"conf": {"message": "Hello World"}}' | jq -r '.dag_run_id'
```

If this identifier is stored in a variable such as `dag_id` (manually replaced in the command) you can run this command to access the status of the DAG run:

```bash
  ACCESS_TOKEN=$(
    curl -s -XPOST http://localhost:8080/auth/token \
    -H 'Content-Type: application/json' \
        -d '{
        "username": "airflow",
        "password": "airflow"
        }' | jq '.access_token' | tr -d '"'
  )
  curl -s -H "Authorization: Bearer $ACCESS_TOKEN" -H 'Content-Type:application/json' \
    -XGET http://localhost:8080/api/v2/dags/example_trigger_target_dag/dagRuns/"$dag_id" | jq -r '.state'
```

## What’s next

Look at the [Usage guide](https://docs.stackable.tech/home/stable/airflow/usage-guide/index.md) to find out more about configuring your Airflow Stacklet and loading your own DAG files.
