如何使用Python3打开/关闭CloudSQL实例 [英] How to turn on/off CloudSQL instances using Python3

查看:64
本文介绍了如何使用Python3打开/关闭CloudSQL实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to use a Python script to turn on/off a CloudSQL Instance in GoogleCloud. I've finally found a way to do it, using the GoogleCloudAPI, in Shell:

### 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",因此无法解决任何问题.我发现了一个 2017年以来的问题也尝试使用Python生成此访问令牌",这显然也不起作用.

So, great, problem solved... except I cannot use 'gcloud auth print-access-token' on the machine I'm running the script in, so that solves nothing. I found a question from 2017 trying to generate this 'access-token' using Python as well, which apparently didn't work either.

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

I need to be able to generate this 'access-token' using Python itself. I've been looking around in the Google's documentation but I still haven't managed to find anything related to that, closest I found was using oauth2 and googleapiclient to get the list of instances running, but can't seem to change activation policies from there:

### 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".不过,我找不到更改它"的方法.

The documentation doesn't make it clear how to use either tool to turn off the CloudSQL instance though, or at least none that I could find do. The above code returns me a JSON file and I can see the 'activationPolicy' there, under settings. I can't find a way to 'change it' though.

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

Managed to follow @norbjd suggestion and find a 'patch' method, and gave 'SQL Admin' permission to my credentials, so it can now use the sqladmin API. Tried to patch it using the following code:

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确实存在:

Considering instance.data didn't exist prior to that, but instance.headers did:

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

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

After the execute, though, nothing seemed to happen. It did not change the actual activationPolicy.

推荐答案

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

In the end, the problem was solved using the ACCESS_TOKEN and making a Python request using the requests module. If you try to get an ACCESS_TOKEN from your credentials just after generating them, you won't be getting any, but if you actually use your credentials with the googleapiclient.discovery, this updates that object with a valid access token, that can then be used in a Python request, as follows:

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之前实际将凭据用于某些用途

All it took was to actually use the credentials for something before attempting to retrieve the ACCESS_TOKEN

这篇关于如何使用Python3打开/关闭CloudSQL实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆