【发布时间】:2021-04-04 20:26:52
【问题描述】:
我在玩 Compute Engine。我编写了一个 Python 脚本,它调用 Compute Engine API 并尝试使用随附的启动脚本创建一个 VM 实例。启动脚本旨在使用 echo 命令创建一个简单的 HTML 文件。
Python 脚本正在成功创建 VM 实例。但是,当我通过 SSH 连接到 VM 实例时,没有 HTML 文件的踪迹。
但是,如果我在安全 shell 中手动运行 echo 命令...
echo "<html><body><h1>Hello World</h1><p>This page was created from a startup scri
pt.</p></body></html>" > index.html
...文件创建成功。
为什么这在我的启动脚本中不起作用?我需要在下面的 Python 代码中调整什么吗?
service = discovery.build('compute', 'v1', credentials=credentials)
def create_instance(compute, project, zone, name):
# Get the latest Debian Jessie image.
image_response = (
compute.images()
.getFromFamily(project="debian-cloud", family="debian-9")
.execute()
)
source_disk_image = image_response["selfLink"]
# Configure the machine
machine_type = "zones/%s/machineTypes/n1-standard-1" % zone
config = {
"name": name,
"machineType": machine_type,
# Specify the boot disk and the image to use as a source.
"disks": [
{
"boot": True,
"autoDelete": True,
"initializeParams": {
"sourceImage": source_disk_image,
},
}
],
"networkInterfaces": [
{
"network": "global/networks/default",
"accessConfigs": [{"type": "ONE_TO_ONE_NAT", "name": "External NAT"}],
}
],
"metadata": {
"kind": "compute#metadata",
"items": [
{
"key": "startup-script",
"value": 'sudo apt-get update\nexport DEBIAN_FRONTEND=noninteractive\necho "<html><body><h1>Hello World</h1><p>This page was created from a startup script.</p></body></html>" > index.html'
}
]
},
"tags": {"items": ["http-server", "https-server"]},
}
return compute.instances().insert(project=project, zone=zone, body=config).execute()
create_instance(service, project_id, zone, "pandora-instance")
【问题讨论】:
-
尝试在您的启动脚本中将
\n替换为&&,不确定换行符是在此上下文中链接命令的正确方式。用&&分隔命令意味着如果第一个命令没有“失败”(使用 0 以外的代码退出),则第二个命令将运行 -
感谢@IainShelvington,我尝试使用 && 但仍未创建 html 文件。
标签: python shell google-cloud-platform google-api google-compute-engine