如何使用Python3打开/关闭CloudSQL实例

问题描述 投票:0回答:1

我正在尝试使用Python脚本来打开/关闭GoogleCloud中的CloudSQL实例。我终于在Shell中找到了一种使用GoogleCloudAPI的方法:

### shell script
ACCESS_TOKEN="$(gcloud auth print-access-token)"
ACTIVATION_POLICY="ALWAYS/NEVER" # Use 'ALWAYS' to turn on, 'NEVER' to turn off
curl --header "Authorization: Bearer ${ACCESS_TOKEN}"  --header 'Content-Type: application/json' --data '{"settings" : {"activationPolicy" : "${ACTIVATION_POLICY}"}}' -X PATCH https://www.googleapis.com/sql/v1beta4/projects/${PROJECT_ID}/instances/${INSTANCE_ID}

所以,很好,已解决了问题……除了我不能在正在运行脚本的计算机上使用'gcloud auth print-access-token',因此无法解决任何问题。我发现question from 2017也试图使用Python生成此“访问令牌”,这显然也不起作用。

我需要能够使用Python本身生成此“访问令牌”。我一直在Google的文档中四处寻找,但仍然找不到任何相关的东西,我发现最接近的是使用oauth2和googleapiclient来获取正在运行的实例的列表,但似乎无法从那里:

### python3 script
from google.oauth2 import service_account
import googleapiclient.discovery
SCOPES = ['https://www.googleapis.com/auth/sqlservice.admin']
SERVICE_ACCOUNT_FILE = '/path/to/service.json'
credentials = service_account.Credentials.from_service_account_file(
        SERVICE_ACCOUNT_FILE, scopes=SCOPES)
sqladmin = googleapiclient.discovery.build('sqladmin', 'v1beta4', credentials=credentials)
response = sqladmin.instances().get(project=PROJECT_ID, instance=INSTANCE_ID).execute()

文档没有明确说明如何使用任何一种工具来关闭CloudSQL实例,或者至少找不到我可以找到的工具。上面的代码返回了一个JSON文件,并且可以在设置下看到“ activationPolicy”。我找不到“更改它”的方法。

设法遵循@norbjd的建议并找到一个'patch'方法,并为我的凭据授予了'SQL Admin'权限,因此它现在可以使用sqladmin API。尝试使用以下代码对其进行修补:

instance = sqladmin.instances().patch(project=PROJECT_ID, instance=INSTANCE_ID)
instance.data = {"settings" : {"activationPolicy" : "NEVER"}} #also tried with it in a string, like this: instance.data = {"settings" : {"activationPolicy" : "NEVER"}}
instance.headers['Content-Type'] = 'application/json'
instance.execute()

之前没有考虑过instance.data,但是instance.headers确实存在:

{'accept': 'application/json', 'accept-encoding': 'gzip, deflate', 'user-agent': '(gzip)', 'x-goog-api-client': 'gdcl/1.7.11 gl-python/3.6.9'}

但是,执行后似乎什么也没发生。它没有更改实际的activationPolicy。

python python-3.x google-api google-cloud-sql google-oauth2
1个回答
0
投票

最后,使用ACCESS_TOKEN解决了问题,并使用请求模块发出了Python请求。如果您尝试在生成凭据后立即从其凭据中获取ACCESS_TOKEN,则不会获取任何凭据,但是如果您将凭据与googleapiclient.discovery一起实际使用,则会使用有效的访问令牌更新该对象,然后可以在Python请求中使用,如下所示:

from google.oauth2 import service_account
import googleapiclient.discovery
import json
import requests

PROJECT_ID = '{PROJECT_ID_HERE}'
INSTANCE_ID = '{INSTANCE_ID_HERE}'

SCOPES = ['https://www.googleapis.com/auth/sqlservice.admin']
SERVICE_ACCOUNT_FILE = '/path/to/service.json'
credentials = service_account.Credentials.from_service_account_file(
        SERVICE_ACCOUNT_FILE, scopes=SCOPES)

sqladmin = googleapiclient.discovery.build('sqladmin', 'v1beta4', credentials=credentials)
response = sqladmin.instances().get(project=PROJECT_ID, instance=INSTANCE_ID).execute()
print(json.dumps(response))

access_token = credentials.token # Now that the credentials were used, they have a valid access_token associated with them!

activation_policy = 'NEVER' # or 'ALWAYS'

url = "https://www.googleapis.com/sql/v1beta4/projects/{PROJECT_ID}/instances/{INSTANCE_ID}".format(PROJECT_ID=PROJECT_ID, INSTANCE_ID=INSTANCE_ID)
header = {
    "Authorization" : "Bearer {}".format(access_token), 
    "Content-Type" : "application/json"
}
data = {
    "settings" : {
        "activationPolicy" : activation_policy
    }
}
response = requests.patch(url, headers=header, data=json.dumps(data))
print(response.text)

所要做的就是在尝试检索ACCESS_TOKEN之前实际将凭据用于某些用途>

© www.soinside.com 2019 - 2024. All rights reserved.