Compartilhar via


Configurar e implantar o Airflow no AKS (Serviço de Kubernetes do Azure)

Neste artigo, você configurará e implantará um cluster do Apache Airflow no AKS (Serviço de Kubernetes do Azure) usando o Helm.

Configurar identidade de carga de trabalho

  1. Crie um namespace para o cluster do Airflow usando o comando kubectl create namespace.

    kubectl create namespace ${AKS_AIRFLOW_NAMESPACE} --dry-run=client --output yaml | kubectl apply -f -
    

    Saída de exemplo:

    namespace/airflow created
    
  2. Crie uma conta de serviço e configure a identidade da carga de trabalho usando o comando kubectl apply.

    export TENANT_ID=$(az account show --query tenantId -o tsv)
    cat <<EOF | kubectl apply -f -
    apiVersion: v1
    kind: ServiceAccount
    metadata:
      annotations:
        azure.workload.identity/client-id: "${MY_IDENTITY_NAME_CLIENT_ID}"
        azure.workload.identity/tenant-id: "${TENANT_ID}"
      name: "${SERVICE_ACCOUNT_NAME}"
      namespace: "${AKS_AIRFLOW_NAMESPACE}"
    EOF
    

    Saída de exemplo:

    serviceaccount/airflow created
    

Instalar o Operador de Segredos Externos

Nesta seção, usaremos o Helm para instalar o Operador de Segredos Externos. O Operador de Segredos Externos é um operador do Kubernetes que gerencia o ciclo de vida de segredos externos armazenados em repositórios de segredos externos, como o Azure Key Vault.

  1. Adicione o repositório Helm de Segredos Externos e atualize o repositório usando os comandos helm repo add e helm repo update.

    helm repo add external-secrets https://charts.external-secrets.io
    helm repo update
    

    Saída de exemplo:

    Hang tight while we grab the latest from your chart repositories...
    ...Successfully got an update from the "external-secrets" chart repository
    
  2. Instale o Operador de Segredos Externos usando o comando helm install.

    helm install external-secrets \
    external-secrets/external-secrets \
    --namespace ${AKS_AIRFLOW_NAMESPACE} \
    --create-namespace \
    --set installCRDs=true \
    --wait
    

    Saída de exemplo:

    NAME: external-secrets
    LAST DEPLOYED: Thu Nov  7 11:16:07 2024
    NAMESPACE: airflow
    STATUS: deployed
    REVISION: 1
    TEST SUITE: None
    NOTES:
    external-secrets has been deployed successfully in namespace airflow!
    
    In order to begin using ExternalSecrets, you will need to set up a SecretStore
    or ClusterSecretStore resource (for example, by creating a 'vault' SecretStore).
    
    More information on the different types of SecretStores and how to configure them
    can be found in our Github: https://github.com/external-secrets/external-secrets
    

Criar segredos

  1. Crie um recurso SecretStore para acessar as senhas do Airflow armazenadas no seu cofre de chaves usando o comando kubectl apply.

    kubectl apply -f - <<EOF
    apiVersion: external-secrets.io/v1beta1
    kind: SecretStore
    metadata:
      name: azure-store
      namespace: ${AKS_AIRFLOW_NAMESPACE}
    spec:
      provider:
        # provider type: azure keyvault
        azurekv:
          authType: WorkloadIdentity
          vaultUrl: "${KEYVAULTURL}"
          serviceAccountRef:
            name: ${SERVICE_ACCOUNT_NAME}
    EOF
    

    Saída de exemplo:

    secretstore.external-secrets.io/azure-store created
    
  2. Crie um recurso ExternalSecret, que cria um Secret do Kubernetes no namespace airflow com os segredos Airflow armazenados no seu cofre de chaves, usando o comando kubectl apply.

    kubectl apply -f - <<EOF
    apiVersion: external-secrets.io/v1beta1
    kind: ExternalSecret
    metadata:
      name: airflow-aks-azure-logs-secrets
      namespace: ${AKS_AIRFLOW_NAMESPACE}
    spec:
      refreshInterval: 1h
      secretStoreRef:
        kind: SecretStore
        name: azure-store
    
      target:
        name: ${AKS_AIRFLOW_LOGS_STORAGE_SECRET_NAME}
        creationPolicy: Owner
    
      data:
        # name of the SECRET in the Azure KV (no prefix is by default a SECRET)
        - secretKey: azurestorageaccountname
          remoteRef:
            key: AKS-AIRFLOW-LOGS-STORAGE-ACCOUNT-NAME
        - secretKey: azurestorageaccountkey
          remoteRef:
            key: AKS-AIRFLOW-LOGS-STORAGE-ACCOUNT-KEY
    EOF
    

    Saída de exemplo:

    externalsecret.external-secrets.io/airflow-aks-azure-logs-secrets created
    
  3. Crie uma credencial federada usando o comando az identity federated-credential create.

    az identity federated-credential create \
        --name external-secret-operator \
        --identity-name ${MY_IDENTITY_NAME} \
        --resource-group ${MY_RESOURCE_GROUP_NAME} \
        --issuer ${OIDC_URL} \
        --subject system:serviceaccount:${AKS_AIRFLOW_NAMESPACE}:${SERVICE_ACCOUNT_NAME} \
        --output table
    

    Saída de exemplo:

    Issuer                                                                                                                   Name                      ResourceGroup            Subject
    -----------------------------------------------------------------------------------------------------------------------  ------------------------  -----------------------  -------------------------------------
    https://$MY_LOCATION.oic.prod-aks.azure.com/c2c2c2c2-dddd-eeee-ffff-a3a3a3a3a3a3/aaaa0a0a-bb1b-cc2c-dd3d-eeeeee4e4e4e/  external-secret-operator  $MY_RESOURCE_GROUP_NAME  system:serviceaccount:airflow:airflow
    
  4. Conceda permissão à identidade atribuída pelo usuário para acessar o segredo usando o comando az keyvault set-policy.

    az keyvault set-policy --name $MY_KEYVAULT_NAME --object-id $MY_IDENTITY_NAME_PRINCIPAL_ID --secret-permissions get --output table
    

    Saída de exemplo:

    Location       Name                    ResourceGroup
    -------------  ----------------------  -----------------------
    $MY_LOCATION   $MY_KEYVAULT_NAME       $MY_RESOURCE_GROUP_NAME
    

Criar um volume persistente para logs do Apache Airflow

  • Crie um volume persistente usando o comando kubectl apply.

    kubectl apply -f - <<EOF
    apiVersion: v1
    kind: PersistentVolume
    metadata:
      name: pv-airflow-logs
      labels:
        type: local
    spec:
      capacity:
        storage: 5Gi
      accessModes:
        - ReadWriteMany
      persistentVolumeReclaimPolicy: Retain # If set as "Delete" container would be removed after pvc deletion
      storageClassName: azureblob-fuse-premium
      mountOptions:
        - -o allow_other
        - --file-cache-timeout-in-seconds=120
      csi:
        driver: blob.csi.azure.com
        readOnly: false
        volumeHandle: airflow-logs-1
        volumeAttributes:
          resourceGroup: ${MY_RESOURCE_GROUP_NAME}
          storageAccount: ${AKS_AIRFLOW_LOGS_STORAGE_ACCOUNT_NAME}
          containerName: ${AKS_AIRFLOW_LOGS_STORAGE_CONTAINER_NAME}
        nodeStageSecretRef:
          name: ${AKS_AIRFLOW_LOGS_STORAGE_SECRET_NAME}
          namespace: ${AKS_AIRFLOW_NAMESPACE}
    EOF
    

    Saída de exemplo:

    persistentvolume/pv-airflow-logs created
    

Criar uma declaração de volume persistente para logs do Apache Airflow

  • Crie uma declaração do volume persistente usando o comando kubectl apply.

    kubectl apply -f - <<EOF
    apiVersion: v1
    kind: PersistentVolumeClaim
    metadata:
      name: pvc-airflow-logs
      namespace: ${AKS_AIRFLOW_NAMESPACE}
    spec:
      storageClassName: azureblob-fuse-premium
      accessModes:
        - ReadWriteMany
      resources:
        requests:
          storage: 5Gi
      volumeName: pv-airflow-logs
    EOF
    

    Saída de exemplo:

    persistentvolumeclaim/pvc-airflow-logs created
    

Implantar o Apache Airflow usando o Helm

  1. Configure um arquivo airflow_values.yaml para alterar as configurações de implantação padrão para o gráfico e atualize o registro de contêiner para as imagens.

    cat <<EOF> airflow_values.yaml
    
    images:
      airflow:
        repository: $MY_ACR_REGISTRY.azurecr.io/airflow
        tag: 2.9.3
        # Specifying digest takes precedence over tag.
        digest: ~
        pullPolicy: IfNotPresent
      # To avoid images with user code, you can turn this to 'true' and
      # all the 'run-airflow-migrations' and 'wait-for-airflow-migrations' containers/jobs
      # will use the images from 'defaultAirflowRepository:defaultAirflowTag' values
      # to run and wait for DB migrations .
      useDefaultImageForMigration: false
      # timeout (in seconds) for airflow-migrations to complete
      migrationsWaitTimeout: 60
      pod_template:
        # Note that `images.pod_template.repository` and `images.pod_template.tag` parameters
        # can be overridden in `config.kubernetes` section. So for these parameters to have effect
        # `config.kubernetes.worker_container_repository` and `config.kubernetes.worker_container_tag`
        # must be not set .
        repository: $MY_ACR_REGISTRY.azurecr.io/airflow
        tag: 2.9.3
        pullPolicy: IfNotPresent
      flower:
        repository: $MY_ACR_REGISTRY.azurecr.io/airflow
        tag: 2.9.3
        pullPolicy: IfNotPresent
      statsd:
        repository: $MY_ACR_REGISTRY.azurecr.io/statsd-exporter
        tag: v0.26.1
        pullPolicy: IfNotPresent
      pgbouncer:
        repository: $MY_ACR_REGISTRY.azurecr.io/airflow
        tag: airflow-pgbouncer-2024.01.19-1.21.0
        pullPolicy: IfNotPresent
      pgbouncerExporter:
        repository: $MY_ACR_REGISTRY.azurecr.io/airflow
        tag: airflow-pgbouncer-exporter-2024.06.18-0.17.0
        pullPolicy: IfNotPresent
      gitSync:
        repository: $MY_ACR_REGISTRY.azurecr.io/git-sync
        tag: v4.1.0
        pullPolicy: IfNotPresent
    
    
    # Airflow executor
    executor: "KubernetesExecutor"
    
    # Environment variables for all airflow containers
    env:
      - name: ENVIRONMENT
        value: dev
    
    extraEnv: |
      - name: AIRFLOW__CORE__DEFAULT_TIMEZONE
        value: 'America/New_York'
    
    # Configuration for postgresql subchart
    # Not recommended for production! Instead, spin up your own Postgresql server and use the `data` attribute in this
    # yaml file.
    postgresql:
      enabled: true
    
    # Enable pgbouncer. See https://airflow.apache.org/docs/helm-chart/stable/production-guide.html#pgbouncer
    pgbouncer:
      enabled: true
    
    dags:
      gitSync:
        enabled: true
        repo: https://github.com/donhighmsft/airflowexamples.git
        branch: main
        rev: HEAD
        depth: 1
        maxFailures: 0
        subPath: "dags"
        # sshKeySecret: airflow-git-ssh-secret
        # knownHosts: |
        #   github.com ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQCj7ndNxQowgcQnjshcLrqPEiiphnt+VTTvDP6mHBL9j1aNUkY4Ue1gvwnGLVlOhGeYrnZaMgRK6+PKCUXaDbC7qtbW8gIkhL7aGCsOr/C56SJMy/BCZfxd1nWzAOxSDPgVsmerOBYfNqltV9/hWCqBywINIR+5dIg6JTJ72pcEpEjcYgXkE2YEFXV1JHnsKgbLWNlhScqb2UmyRkQyytRLtL+38TGxkxCflmO+5Z8CSSNY7GidjMIZ7Q4zMjA2n1nGrlTDkzwDCsw+wqFPGQA179cnfGWOWRVruj16z6XyvxvjJwbz0wQZ75XK5tKSb7FNyeIEs4TT4jk+S4dhPeAUC5y+bDYirYgM4GC7uEnztnZyaVWQ7B381AK4Qdrwt51ZqExKbQpTUNn+EjqoTwvqNj4kqx5QUCI0ThS/YkOxJCXmPUWZbhjpCg56i+2aB6CmK2JGhn57K5mj0MNdBXA4/WnwH6XoPWJzK5Nyu2zB3nAZp+S5hpQs+p1vN1/wsjk=
    
    logs:
      persistence:
        enabled: true
        existingClaim: pvc-airflow-logs
        storageClassName: azureblob-fuse-premium
    
    # We disable the log groomer sidecar because we use Azure Blob Storage for logs, with lifecyle policy set.
    triggerer:
      logGroomerSidecar:
        enabled: false
    
    scheduler:
      logGroomerSidecar:
        enabled: false
    
    workers:
      logGroomerSidecar:
        enabled: false
    
    EOF
    
  2. Adicione o repositório Helm do Apache Airflow e atualize o repositório usando os comandos helm repo add e helm repo update.

    helm repo add apache-airflow https://airflow.apache.org
    helm repo update
    

    Saída de exemplo:

    "apache-airflow" has been added to your repositories
    Hang tight while we grab the latest from your chart repositories...
    ...Successfully got an update from the "apache-airflow" chart repository
    
  3. Pesquise no repositório Helm o gráfico do Apache Airflow usando o comando helm search repo.

    helm search repo airflow
    

    Saída de exemplo:

    NAME                    CHART VERSION   APP VERSION     DESCRIPTION
    apache-airflow/airflow  1.15.0          2.9.3           The official Helm chart to deploy Apache Airflo...
    
  4. Instale o gráfico do Apache Airflow usando o comando helm install.

    helm install airflow apache-airflow/airflow --namespace airflow --create-namespace -f airflow_values.yaml --debug
    

    Saída de exemplo:

    NAME: airflow
    LAST DEPLOYED: Fri Nov  8 11:59:43 2024
    NAMESPACE: airflow
    STATUS: deployed
    REVISION: 1
    TEST SUITE: None
    NOTES:
    Thank you for installing Apache Airflow 2.9.3!
    
    Your release is named airflow.
    You can now access your dashboard(s) by executing the following command(s) and visiting the corresponding port at localhost in your browser:
    
    Airflow Webserver:     kubectl port-forward svc/airflow-webserver 8080:8080 --namespace airflow
    Default Webserver (Airflow UI) Login credentials:
        username: admin
        password: admin
    Default Postgres connection credentials:
        username: postgres
        password: postgres
        port: 5432
    
    You can get Fernet Key value by running the following:
    
        echo Fernet Key: $(kubectl get secret --namespace airflow airflow-fernet-key -o jsonpath="{.data.fernet-key}" | base64 --decode)
    
    ###########################################################
    #  WARNING: You should set a static webserver secret key  #
    ###########################################################
    
    You are using a dynamically generated webserver secret key, which can lead to
    unnecessary restarts of your Airflow components.
    
    Information on how to set a static webserver secret key can be found here:
    https://airflow.apache.org/docs/helm-chart/stable/production-guide.html#webserver-secret-key
    
  5. Verifique a instalação usando o comando kubectl get pods.

    kubectl get pods -n airflow
    

    Saída de exemplo:

    NAME                                                READY   STATUS      RESTARTS   AGE
    airflow-create-user-kklqf                           1/1     Running     0          12s
    airflow-pgbouncer-d7bf9f649-25fnt                   2/2     Running     0          61s
    airflow-postgresql-0                                1/1     Running     0          61s
    airflow-run-airflow-migrations-zns2b                0/1     Completed   0          60s
    airflow-scheduler-5c45c6dbdd-7t6hv                  1/2     Running     0          61s
    airflow-statsd-6df8564664-6rbw8                     1/1     Running     0          61s
    airflow-triggerer-0                                 2/2     Running     0          61s
    airflow-webserver-7df76f944c-vcd5s                  0/1     Running     0          61s
    external-secrets-748f44c8b8-w7qrk                   1/1     Running     0          3h6m
    external-secrets-cert-controller-57b9f4cb7c-vl4m8   1/1     Running     0          3h6m
    external-secrets-webhook-5954b69786-69rlp           1/1     Running     0          3h6m
    

Acessar a interface do usuário do Airflow

  1. Acesse com segurança a interface do usuário do Airflow por meio do encaminhamento de porta usando o comando kubectl port-forward.

    kubectl port-forward svc/airflow-webserver 8080:8080 -n airflow
    
  2. Abra o navegador e navegue até localhost:8080 para acessar a interface do usuário do Airflow.

  3. Use a URL do servidor Web padrão e as credenciais de logon fornecidas durante a instalação do gráfico do Helm do Airflow para fazer logon.

  4. Explore e gerencie seus fluxos de trabalho com segurança por meio da interface do usuário do Airflow.

Integrar o Git ao Airflow

A integração do Git com o Apache Airflow permite o controle de versão contínuo e o gerenciamento simplificado de suas definições de fluxo de trabalho, garantindo que todos os DAGs sejam organizados e facilmente auditáveis.

  1. Configurar um repositório Git para DAGs. Crie um repositório Git dedicado para abrigar todas as definições de DAG do Airflow. Esse repositório serve como a fonte central de verdade para seus fluxos de trabalho, permitindo que você gerencie, acompanhe e colabore em DAGs com eficiência.
  2. Configure o Airflow para sincronizar DAGs do Git. Atualize a configuração do Airflow para efetuar pull automático de DAGs do repositório Git definindo a URL do repositório Git e as credenciais de autenticação necessárias diretamente nos arquivos de configuração do Airflow ou por meio de valores de gráfico do Helm. Essa configuração permite a sincronização automatizada de DAGs, garantindo que o Airflow esteja sempre atualizado com a versão mais recente de seus fluxos de trabalho.

Essa integração aprimora o fluxo de trabalho de desenvolvimento e implantação introduzindo controle de versão completo, habilitando reversões e dando suporte à colaboração em equipe em uma configuração de nível de produção.

Fazer com que a classificação do Airflow no Kubernetes se torne em produção

As práticas recomendadas a seguir podem ajudar você a criar o Apache Airflow no nível de produção de implantação do Kubernetes:

  • Verifique se você tem uma configuração robusta focada em escalabilidade, segurança e confiabilidade.
  • Use nós dedicados e de dimensionamento automático e selecione um executor resiliente, como KubernetesExecutor, CeleryExecutor ou CeleryKubernetesExecutor.
  • Use um back-end de banco de dados gerenciado e de alta disponibilidade, como MySQL ou PostgreSQL.
  • Estabeleça monitoramento abrangente e registro em log centralizado para manter insights de desempenho.
  • Proteja seu ambiente com políticas de rede, SSL e RBAC (controle de acesso baseado em função) e configure componentes de fluxo de ar (Agendador, Servidor Web, Trabalhos) para alta disponibilidade.
  • Implemente pipelines de CI/CD para implantação de DAG suave e configure backups regulares para recuperação de desastre.

Próximas etapas

Para saber mais sobre como implantar software de código aberto no AKS (Serviço de Kubernetes do Azure), consulte os seguintes artigos:

Colaboradores

A Microsoft atualiza este artigo. Os seguintes colaboradores o escreveram originalmente:

  • Don High | Engenheiro de Cliente Principal
  • Satya Chandragiri | Arquiteto Sênior de Soluções de Nuvem Digital
  • Erin Schaffer | Desenvolvedora de Conteúdo 2