我正在使用python与谷歌计算引擎进行交互。我可以直接使用python创建/停止机器。我已经将此示例代码用于此目的,并且工作正常。
现在我想打开一些端口与外界的机器进行交互。
我已经看到了以下问题,我知道我们可以通过Google控制台web和gcloud命令轻松完成,因此我的问题特定于python API
How to open a specific port such as 9090 in Google Compute Engine
有人可以帮帮我吗?
答案 0 :(得分:1)
下面是一些示例代码,可以帮助您入门,但是我建议您检查一下计算API的entire firewalls portion,以确保您使用了所需的所有选项:
这可以在使用应用程序默认凭据的云外壳上成功运行。您可能需要authenticate in a different way。
import googleapiclient.discovery
if __name__ == '__main__':
MY_PROJECT = 'your-project-name'
# Get the firewalls resource
firewalls = googleapiclient.discovery.build('compute', 'v1').firewalls()
# Build the REST parameters for a port 9090 ingress allow-all firewall.
firewall_definition = {
"name": "default-allow-9090",
"direction": "INGRESS",
# targetTags: "add tags here if you need them -- default is apply to all",
"sourceRanges" : "0.0.0.0/0",
"allowed": { "IPProtocol": "tcp", "ports": [ 9090 ] },
"priority": 1000,
"network": "https://www.googleapis.com/compute/v1/projects/%s/global/networks/default" % MY_PROJECT,
}
# Execute the call.
result = firewalls.insert(project=MY_PROJECT, body=firewall_definition).execute()
# View Response
print(result)