Attivare i DAG di Managed Service for Apache Airflow con le funzioni Cloud Run e l'API REST di Airflow

Managed Airflow (Gen 3) | Managed Airflow (Gen 2) | Managed Airflow (Legacy Gen 1)

Questa pagina descrive come utilizzare le funzioni Cloud Run per attivare i DAG di Managed Service for Apache Airflow in risposta agli eventi.

Apache Airflow è progettato per eseguire i DAG in base a una pianificazione regolare, ma puoi anche attivare i DAG in risposta agli eventi. Un modo per farlo è utilizzare Cloud Run Functions per attivare i DAG di Managed Airflow quando si verifica un evento specificato.

Inoltre puoi:

L'esempio in questa guida mostra una funzione che attiva un DAG in risposta a un evento:

  1. Configura i trigger per la funzione in Cloud Run Functions.
  2. Quando la funzione viene attivata, effettua una richiesta per attivare un DAG tramite l'API REST Airflow del tuo ambiente Managed Airflow. La richiesta contiene l'identificatore e il tipo dell'evento, nonché il relativo payload.
  3. Airflow elabora questa richiesta ed esegue il DAG specificato nella richiesta. Il DAG restituisce i dati che gli sono stati passati dalla funzione.

Prima di iniziare

Questa sezione elenca i passaggi preparatori.

Controlla la configurazione di rete del tuo ambiente

Questa soluzione non funziona nelle configurazioni di IP privato e Controlli di servizio VPC perché non è possibile configurare la connettività dalle funzioni Cloud Run al server web Airflow in queste configurazioni.

In Managed Airflow (2ª gen.), puoi utilizzare un altro approccio: attivare i DAG utilizzando le funzioni Cloud Run e i messaggi Pub/Sub.

Abilitare le API per il progetto

Console

Abilita le API Managed Airflow e Cloud Run Functions, se non sono già abilitate.

Ruoli richiesti per abilitare le API

Per abilitare le API, devi disporre dell'autorizzazione serviceusage.services.enable. Se hai creato il progetto, probabilmente disponi già di questa autorizzazione tramite il ruolo Proprietario (roles/owner). In caso contrario, puoi ottenere questa autorizzazione tramite il ruolo Amministratore utilizzo dei servizi (roles/serviceusage.serviceUsageAdmin). Scopri come concedere i ruoli.

Abilita le API

gcloud

Abilita le API Managed Airflow e Cloud Run Functions, se non sono già abilitate:

Ruoli richiesti per abilitare le API

Per abilitare le API, devi disporre dell'autorizzazione serviceusage.services.enable. Se hai creato il progetto, probabilmente disponi già di questa autorizzazione tramite il ruolo Proprietario (roles/owner). In caso contrario, puoi ottenere questa autorizzazione tramite il ruolo Amministratore utilizzo dei servizi (roles/serviceusage.serviceUsageAdmin). Scopri come concedere i ruoli.

gcloud services enable cloudfunctions.googleapis.com composer.googleapis.com

Abilita l'API REST Airflow

Per Airflow 2, l'API REST stabile è già abilitata per impostazione predefinita. Se nel tuo ambiente l'API stabile è disabilitata, abilita l'API REST stabile.

Consenti chiamate API all'API REST Airflow utilizzando controllo dell'accesso alla rete del server web

Le funzioni Cloud Run possono raggiungere l'API REST di Airflow tramite un indirizzo IPv4 o IPv6.

Se non hai la certezza di quale sarà l'intervallo IP di chiamata, utilizza un'opzione di configurazione predefinita in Controllo dell'accesso al web server, ovvero All IP addresses have access (default), per non bloccare accidentalmente le tue funzioni Cloud Run. Puoi sempre configurare l'accesso alla rete del server web in un secondo momento.

Ottieni l'URL del server web Airflow

Questo esempio effettua richieste API REST all'endpoint del server web Airflow. Utilizzi l'URL del server web Airflow nel codice della Cloud Function.

Console

  1. Nella console Google Cloud , vai alla pagina Ambienti.

    Vai ad Ambienti

  2. Fai clic sul nome del tuo ambiente.

  3. Nella pagina Dettagli ambiente, vai alla scheda Configurazione ambiente.

  4. L'URL del server web Airflow è elencato nell'elemento UI web di Airflow.

gcloud

Esegui questo comando:

gcloud composer environments describe ENVIRONMENT_NAME \
    --location LOCATION \
    --format='value(config.airflowUri)'

Sostituisci:

  • ENVIRONMENT_NAME con il nome dell'ambiente.
  • LOCATION con la regione in cui si trova l'ambiente.

Caricare un DAG nel tuo ambiente

Carica un DAG nel tuo ambiente. Il seguente DAG di esempio restituisce la configurazione di esecuzione del DAG ricevuta. Attiverai questo DAG da una funzione, che creerai più avanti in questa guida.

import datetime

import airflow
from airflow.operators.bash_operator import BashOperator

with airflow.DAG(
        'composer_sample_trigger_response_dag',
        start_date=datetime.datetime(2026, 1, 1),
        # Not scheduled, trigger only
        schedule=None) as dag:

    # Print the dag_run's configuration, which includes information about the
    # Cloud Storage object change.
    print_gcs_info = BashOperator(
        task_id='print_gcs_info', bash_command='echo {{ dag_run.conf }}}}')

Esegui il deployment di una funzione che attiva il DAG

Puoi eseguire il deployment di una funzione utilizzando il linguaggio che preferisci supportato da Cloud Run Functions o Cloud Run. Questo tutorial mostra una Cloud Functions implementata in Python e Java.

Specifica i parametri di configurazione della funzione

  • Trigger: seleziona uno o più trigger Eventarc per la tua funzione.

    Per saperne di più sulla creazione di trigger, consulta Creare trigger con Eventarc. Ad esempio, puoi attivare funzioni da Cloud Storage utilizzando Eventarc.

  • Service account: il account di servizio specificato per il trigger deve disporre di autorizzazioni sufficienti per attivare i DAG negli ambienti Managed Airflow.

    Ti consigliamo di seguire il principio del privilegio minimo e di concedere solo il ruolo Utente Composer (composer.user). Per saperne di più sulla configurazione delle autorizzazioni, consulta Ruoli e autorizzazioni per le destinazioni Cloud Run.

  • Entry point della funzione:

    • (Python) Quando aggiungi il codice per questo esempio, seleziona il runtime Python 3.10 o versioni successive e specifica trigger_dag_with_gcf come punto di ingresso.

    • (Java) Quando aggiungi il codice per questo esempio, seleziona il runtime Java 17 e specifica functions.TriggerDagExample come punto di ingresso.

Aggiungere requisiti

Python

Specifica le dipendenze nel file requirements.txt:

google-auth>=2.38.0
requests>=2.34.2
functions-framework==3.*

Java

Aggiungi le seguenti dipendenze alla sezione dependencies in pom.xml:

    <dependency>
      <groupId>com.google.apis</groupId>
      <artifactId>google-api-services-docs</artifactId>
      <version>v1-rev20250917-2.0.0</version>
    </dependency>
    <dependency>
      <groupId>com.google.api-client</groupId>
      <artifactId>google-api-client</artifactId>
      <version>2.9.0</version>
    </dependency>
    <dependency>
      <groupId>com.google.auth</groupId>
      <artifactId>google-auth-library-credentials</artifactId>
      <version>1.49.0</version>
    </dependency>
    <dependency>
      <groupId>com.google.auth</groupId>
      <artifactId>google-auth-library-oauth2-http</artifactId>
      <version>1.49.0</version>
    </dependency>

Aggiungi codice per la funzione

Python

Inserisci il seguente codice nel file main.py:

  • Sostituisci il valore della variabile web_server_url con l'indirizzo del server web Airflow che hai ottenuto in precedenza.

  • Se attivi un DAG diverso, sostituisci il valore della variabile dag_id.

from __future__ import annotations

from typing import Any

from datetime import datetime, timezone
import google.auth
from google.auth.transport.requests import AuthorizedSession
import requests
import functions_framework

# Following Google Cloud best practices, these credentials should be
# constructed at start-up time and used throughout
# https://cloud.google.com/apis/docs/client-libraries-best-practices
AUTH_SCOPE = "https://www.googleapis.com/auth/cloud-platform"
CREDENTIALS, _ = google.auth.default(scopes=[AUTH_SCOPE])

def make_managed_airflow_web_server_request(
    url: str, method: str = "GET", **kwargs: Any
) -> google.auth.transport.Response:
    """
    Make a request to environment's web server.
    Args:
      url: The URL to fetch.
      method: The request method to use ('GET', 'OPTIONS', 'HEAD', 'POST',
      'PUT', 'PATCH', 'DELETE')
      **kwargs: Any of the parameters defined for the request function:
                https://github.com/requests/requests/blob/master/requests/api.py
                  If no timeout is provided, it is set to 90 by default.
    """

    authed_session = AuthorizedSession(CREDENTIALS)

    # Set the default timeout, if missing
    if "timeout" not in kwargs:
        kwargs["timeout"] = 90

    return authed_session.request(method, url, **kwargs)

def trigger_dag_request(web_server_url: str, airflow_version: str, dag_id: str, data: dict, logical_date: str) -> str:
    """
    Make a request to trigger a dag using the Airflow REST API.
    https://airflow.apache.org/docs/apache-airflow/stable/stable-rest-api-ref.html

    Args:
      web_server_url: The URL of the Airflow web server.
      airflow_version: Major version of Airflow. Determines the API endpoint.
      dag_id: The DAG ID.
      data: Additional configuration parameters for the DAG run (json).
      logical_date: Data interval for which to run the DAG.
    """

    if airflow_version == "2":
        endpoint = f"api/v1/dags/{dag_id}/dagRuns"
    elif airflow_version == "3":
        endpoint = f"api/v2/dags/{dag_id}/dagRuns"
    else:
        raise ValueError(
          f"Invalid Airflow version: {airflow_version}. Expected: 2 or 3.")

    request_url = f"{web_server_url}/{endpoint}"
    json_data = {
        "conf": data,
        "logical_date": logical_date,
    }

    response = make_managed_airflow_web_server_request(
        request_url, method="POST", json=json_data
    )

    if response.status_code == 403:
        raise requests.HTTPError(
            "You do not have a permission to perform this operation. "
            "Check Airflow RBAC roles for your account."
            f"{response.headers} / {response.text}"
        )
    elif response.status_code != 200:
        response.raise_for_status()
    else:
        return response.text

@functions_framework.cloud_event
def trigger_dag_with_gcf(cloud_event: CloudEvent) -> None:
    """
    Entry point for the Cloud Function. Triggers a DAG and passes event data.
    """

    # cloud_event.data contains the resource payload (e.g., storage object
    # details or pub/sub body)
    event_data = {
        "id": cloud_event["id"],
        "subject": cloud_event["subject"],
        "type": cloud_event["type"],
        "data": cloud_event.data
    }

    # TODO(developer): replace with your values
    # Replace web_server_url with the Airflow web server address. To obtain this
    # URL, run the following command for your environment:
    # gcloud composer environments describe example-environment \
    #  --location=your-composer-region \
    #  --format="value(config.airflowUri)"
    web_server_url = (
        "https://example-airflow-ui-url-dot-us-central1.composer.googleusercontent.com"
    )

    # TODO(developer): If your environment uses Airflow 3, replace with "3"
    airflow_major_version = "2"

    # Replace with the ID of the DAG that you want to run.
    dag_id = "composer_sample_trigger_response_dag"

    # The data interval for which to run the DAG
    # Format example: "2026-07-15T15:00:00Z"
    now = datetime.now(timezone.utc)
    logical_date = now.strftime("%Y-%m-%dT%H:%M:%SZ")

    trigger_dag_request(web_server_url, airflow_major_version, dag_id, event_data, logical_date)

Java

Inserisci il seguente codice nel file TriggerDagExample.java (inserisci questo file nella directory src/main/java/gcfv2/):

  • Sostituisci il valore della variabile webServerUrl con l'indirizzo del server web Airflow che hai ottenuto in precedenza.

  • Se attivi un DAG diverso, sostituisci il valore della variabile dagName.

package gcfv2;

import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpContent;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpResponseException;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.http.json.JsonHttpContent;
import com.google.api.client.json.gson.GsonFactory;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.cloud.functions.CloudEventsFunction;
import com.google.gson.Gson;
import io.cloudevents.CloudEvent;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.logging.Logger;
import java.util.HashMap;
import java.util.Map;

/**
 * Function that triggers an Airflow DAG in response to an event ad passes data.
 */
public class TriggerDagExample implements CloudEventsFunction {
  private static final Logger logger = Logger.getLogger(TriggerDagExample.class.getName());

  @Override
  public void accept(CloudEvent event) throws Exception{

    // TODO(developer): replace with your values
    // Replace webServerUrl with the Airflow web server address. To obtain this
    // URL, run the following command for your environment:
    // gcloud composer environments describe example-environment \
    //  --location=your-composer-region \
    //  --format="value(config.airflowUri)"
    String webServerUrl = "https://example-airflow-ui-url-dot-us-central1.composer.googleusercontent.com";
    // TODO(developer): If your environment uses Airflow 3, replace with "3"
    String majorAirflowVersion = "2";

    String apiVersion = switch (majorAirflowVersion) {
      case "2" -> "v1";
      case "3" -> "v2";
      default  -> throw new IllegalArgumentException("Invalid Airflow version: " + majorAirflowVersion);
    };

    String dagName = "composer_sample_trigger_response_dag";
    String url = String.format("%s/api/%s/dags/%s/dagRuns", webServerUrl, apiVersion, dagName);

    logger.info(String.format("Triggering DAG %s as a result of an event on the object %s.",
      dagName, event.getSubject()));
    logger.info(String.format("Triggering DAG through the following URL: %s", url));

    GoogleCredentials googleCredentials = GoogleCredentials.getApplicationDefault()
        .createScoped("https://www.googleapis.com/auth/cloud-platform");
    HttpCredentialsAdapter credentialsAdapter = new HttpCredentialsAdapter(googleCredentials);
    HttpRequestFactory requestFactory =
      new NetHttpTransport().createRequestFactory(credentialsAdapter);

    Map<String, Object> conf = new HashMap<>();

    conf.put("id", event.getId());
    conf.put("subject", event.getSubject());
    conf.put("type", event.getType());

    if (event.getData() != null) {
      String dataJson = new String(event.getData().toBytes(), StandardCharsets.UTF_8);
      Gson gson = new Gson();
      Map<String, Object> dataMap = gson.fromJson(dataJson, Map.class);
      conf.put("data", dataMap);
    }

    String currentUtcTime = Instant.now().toString();

    Map<String, Object> json = new HashMap<>();
    json.put("conf", conf);
    json.put("logical_date", currentUtcTime);

    HttpContent content = new JsonHttpContent(new GsonFactory(), json);
    HttpRequest request = requestFactory.buildPostRequest(new GenericUrl(url), content);
    request.getHeaders().setContentType("application/json");

    HttpResponse response = null;
    try {
      response = request.execute();
      int statusCode = response.getStatusCode();
      logger.info("Response code: " + statusCode);
      logger.info(response.parseAsString());
    } catch (HttpResponseException e) {
      logger.info("Received HTTP exception");
      logger.info(e.getLocalizedMessage());
      logger.info("- 400 error: wrong arguments passed to Airflow API");
      logger.info("- 401 error: check if service account has Composer User role");
      logger.info("- 403 error: check Airflow RBAC roles assigned to service account");
      logger.info("- 404 error: check Web Server URL");
    } catch (Exception e) {
      logger.info("Received exception");
      logger.info(e.getLocalizedMessage());
    } finally {
      // Safely close and release the HTTP connection pool resource
      if (response != null) {
        try {
          response.disconnect();
        } catch (Exception e) {
          logger.warning("Failed to disconnect response: " + e.getMessage());
        }
      }
    }
  }
}

Testare la funzione

Per verificare che la funzione e il DAG funzionino come previsto:

  1. Attendi il deployment della funzione.
  2. Attiva la funzione in base al trigger specificato. Puoi anche attivare la funzione manualmente selezionando l'azione Testa la funzione nella console Google Cloud .
  3. Controlla la pagina DAG nell'interfaccia web di Airflow. Il DAG deve avere un'esecuzione attiva o già completata.
  4. Nell'interfaccia utente di Airflow, controlla i log delle attività per questa esecuzione. Dovresti vedere che l'attività print_gcs_info restituisce i dati ricevuti dalla funzione ai log:

Esempio di comando per testare la funzione:

curl -X POST "https://service-id.region.run.app" \
-H "Authorization: bearer $(gcloud auth print-identity-token)" \
  -X POST \
  -H "Content-Type: application/json" \
  -H "ce-id: 1234567890" \
  -H "ce-specversion: 1.0" \
  -H "ce-type: google.cloud.storage.object.v1.finalized" \
  -H "ce-source: //storage.googleapis.com/projects/_/buckets/example-bucket" \
  -d '{
    "name": "example-file.csv",
    "bucket": "example-bucket"
  }'

Output di esempio:

[2026-07-14, 15:10:12 UTC] {subprocess.py:88} INFO - Running command: ['/usr/bin/bash', '-c', "echo {'data': {'name': 'example-file.csv', 'bucket': 'example-bucket'}, 'id': '1234567890', 'type': 'google.cloud.storage.object.v1.finalized'}"]
[2026-07-14, 15:10:12 UTC] {subprocess.py:99} INFO - Output:
[2026-07-14, 15:10:12 UTC] {subprocess.py:106} INFO - {data: {name: example-file.csv, bucket: my-bucket}, id: 1234567890, type: google.cloud.storage.object.v1.finalized}
[2026-07-14, 15:10:12 UTC] {subprocess.py:110} INFO - Command exited with return code 0

[2026-07-15, 10:06:32 UTC] {subprocess.py:88} INFO - Running command: ['/usr/bin/bash', '-c', "echo {'id': '1234567890', 'subject': 'objects/example-file.csv', 'type': 'google.cloud.storage.object.v1.finalized', 'data': {'name': 'example-file.csv', 'bucket': 'example-bucket'}}"]
[2026-07-15, 10:06:32 UTC] {subprocess.py:99} INFO - Output:
[2026-07-15, 10:06:32 UTC] {subprocess.py:106} INFO - {id: 1234567890, subject: objects/example-file.csv, type: google.cloud.storage.object.v1.finalized, data: {name: example-file.csv, bucket: example-bucket}}
[2026-07-15, 10:06:32 UTC] {subprocess.py:110} INFO - Command exited with return code 0

Risoluzione dei problemi:

  • Se la funzione non riesce e restituisce un errore NullPointerException: Null data e l'analisi dello stack punta alla funzione BackgroundFunctionExecutor.parseLegacyEvent, significa che l'evento ricevuto dalla funzione non ha intestazioni di metadati CloudEvent standard. La funzione presuppone che tu stia inviando un evento in background legacy, tenta di analizzare il campo data e non riesce. Ciò può accadere, ad esempio, se invii un payload di evento arbitrario quando testi la funzione.
  • Se la funzione non va a buon fine con 500 Internal Server Error: The server encountered an internal error and was unable to complete your request., controlla il valore della variabile airflow_major_version. Questa variabile determina l'endpoint dell'API REST Airflow, che è diverso in Airflow 2 e Airflow 3.

Passaggi successivi