首页 > 解决方案 > 谷歌云部署功能在python中“允许未经身份验证”

问题描述

我正在使用 Python 从另一个云函数部署一个谷歌云函数。请参阅下面的代码:

import requests
import json


def make_func(request):


    # Get the access token from the metadata server
    metadata_server_token_url = 'http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token?scopes=https://www.googleapis.com/auth/cloud-platform'
    token_request_headers = {'Metadata-Flavor': 'Google'}
    token_response = requests.get(metadata_server_token_url, headers=token_request_headers)
    token_response_decoded = token_response.content.decode("utf-8")
    jwt = json.loads(token_response_decoded)['access_token']

    # Use the api to create the function
    response = requests.post('https://cloudfunctions.googleapis.com/v1/projects/myproject/locations/us-central1/functions',
                               json={"name":"projects/my-project/locations/us-central1/functions/funct","runtime":"python37","sourceArchiveUrl":"gs://bucket/main.zip","entryPoint":"hello_world","httpsTrigger": {} },
                               headers={'Accept': 'application/json', 
                                        'Content-Type': 'application/json',
                                        'Authorization': 'Bearer {}'.format(jwt)} )   
    if response:
         return 'Success! Function Created'
    else:
         return str(response.json())  

但是,此功能不会自动启用“允许未经身份验证”。因此,不允许来自外部的请求。在部署新功能时,如何更改我的 Python 代码以添加此功能?

谢谢

标签: pythonauthenticationgoogle-cloud-platformgoogle-cloud-functions

解决方案


您还需要为allUsers成员指定Cloud Functions Invoker角色:

from googleapiclient.discovery import build
service = build('cloudfunctions', 'v1')

project_id = ...
location_id = ...
function_id = ...
resource = f'projects/{project_id}/locations/{location_id}/functions/{function_id}'

set_iam_policy_request_body = {
    'policy': {
        "bindings": [
            {
              "role": "roles/cloudfunctions.invoker",
              "members": ["allUsers"],
            },
        ],
    },
}

request = service.projects().locations().functions().setIamPolicy(
    resource=resource,
    body=set_iam_policy_request_body,
)
response = request.execute()

print(response)

这使用google-api-python-client包。


推荐阅读