为什么我的 VM 实例的启动脚本不是 运行?

Why is my VM instance's startup script not running?

我正在玩 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")

你需要在脚本的开头添加shebang来告诉操作系统使用哪个解释器。在你的情况下是:

{
  ...
  "metadata": {
    "items": [
      {
       "key": "startup-script",
       "value": "#! /bin/bash\n\nsudo 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"
      }
    ]
  }
  ...
}

它本质上是通过 API 发送的,如 here 所述。

请注意,您可以通过检查该 VM 实例的 Cloud Logging 或直接在该实例的串行控制台日志中解决启动脚本问题。

当您 运行 启动脚本时,它 运行 作为 root。

所以,首先,sudo 没用。然后,您的 home 目录是 /root 并且该目录是只写的。所以,当你在/root目录下写你的index.html文件时,这是不可能的

首选众所周知的位置,使用 /tmp 进行测试。

AND 因为您确实以 root 模式写入文件,所以文件的所有者也将是 root。如果它阻碍了您的其余进程,请执行 chown 更改此设置。