[英]Unable to trigger composer/airflow dag from Cloud function that triggers when there are changes in cloud storage
[英]Google Cloud Composer: How to trigger a DAG Run from a local dev machine?
我有一个在 GCP 上运行的Google Cloud Composer 1环境。
我编写了一个Google Cloud Function ,当它在云端运行时,它会在我的 Composer 环境中成功触发 DAG 运行。 我的代码基于 GCP 文档中的Trigger DAGs with Cloud Functions指南中的代码,并且几乎完全相同。
这是与我的问题最相关的代码部分( 来源):
from google.auth.transport.requests import Request
from google.oauth2 import id_token
import requests
def make_iap_request(url, client_id, method='GET', **kwargs):
"""Makes a request to an application protected by Identity-Aware Proxy.
Args:
url: The Identity-Aware Proxy-protected URL to fetch.
client_id: The client ID used by Identity-Aware Proxy.
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.
Returns:
The page body, or raises an exception if the page couldn't be retrieved.
"""
# Set the default timeout, if missing
if 'timeout' not in kwargs:
kwargs['timeout'] = 90
# Obtain an OpenID Connect (OIDC) token from metadata server or using service
# account.
open_id_connect_token = id_token.fetch_id_token(Request(), client_id)
# Fetch the Identity-Aware Proxy-protected URL, including an
# Authorization header containing "Bearer " followed by a
# Google-issued OpenID Connect token for the service account.
resp = requests.request(
method, url,
headers={'Authorization': 'Bearer {}'.format(
open_id_connect_token)}, **kwargs)
if resp.status_code == 403:
raise Exception('Service account does not have permission to '
'access the IAP-protected application.')
elif resp.status_code != 200:
raise Exception(
'Bad response from application: {!r} / {!r} / {!r}'.format(
resp.status_code, resp.headers, resp.text))
else:
return resp.text
我希望能够在我的开发机器上本地运行相同的 Cloud Function。 当我尝试这样做时,function 崩溃并显示以下错误消息:
google.auth.exceptions.DefaultCredentialsError:找不到元数据服务器或有效的服务帐户凭据。
这是有道理的,因为抛出错误的行是:
google_open_id_connect_token = id_token.fetch_id_token(Request(), client_id)
实际上,当在本地运行时,元数据服务器不可用,我不知道如何使有效的服务帐户凭据可用于调用fetch_id_token()
。
我的问题是 - 我需要更改什么才能在本地运行 function 时安全地获取OpenID Connect令牌?
我已经能够在不更改代码的情况下在本地运行我的代码。 以下是详细信息,但我不确定这是完成它的最安全选项。
GOOGLE_APPLICATION_CREDENTIALS
环境变量设置为放置 JSON 文件的路径。 更多细节在这里: https://cloud.google.com/docs/authentication/production 执行此操作后,对id_token.fetch_id_token()
的调用从密钥文件中获取服务帐户详细信息并成功返回令牌。
* - 在我的例子中,我在 PyCharm 调试配置中设置了环境变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.