使用 Python SDK for Azure 在创建 VM 操作中添加用户数据

Adding userdata on create VM operation with Python SDK for Azure

我正在使用 Python sdk 进行 azure creation 虚拟机操作。我希望在 VM 启动时执行一些脚本。因此,我尝试在使用 Python.

创建 VM 时添加自定义数据

我的目录:

user-data.sh 文件将类似于:

#!/bin/bash
sudo apt install apache2 -y
sudo apt install git -y

我在 create_VM.py 文件上使用了 base64 包,它看起来像:

import base64

...

file = open("user-data.sh", "r")
a = file.read().encode()
encoded_string = base64.b64encode(a)

...

poller = compute_client.virtual_machines.create_or_update(RESOURCE_GROUP_NAME, VM_NAME,
    {
        "location": LOCATION,
        "storage_profile": {
            "image_reference": {
                "publisher": 'Canonical',
                "offer": "UbuntuServer",
                "sku": "16.04.0-LTS",
                "version": "latest"
            }
        },
        "hardware_profile": {
            "vm_size": "Standard_DS1_v2"
        },
        "os_profile": {
            "computer_name": VM_NAME,
            "admin_username": USERNAME,
            "admin_password": PASSWORD,
            "custom_data": encoded_string
        },
        "network_profile": {
            "network_interfaces": [{
                "id": nic_result.id,
            }]
        }
    }
)
...

我得到的错误是:

Azure Error: InvalidParameter\nMessage: Custom data in OSProfile must be in Base64 encoding and with a maximum length of 87380 characters.\nTarget: customData

我该如何解决这个问题?

请试试这个,它对我有用。

import base64

...

file = open("user-data.sh", "r")
a = file.read().encode()

...
                
CUSTOM_DATA = base64.b64encode(a.encode('utf-8')).decode('latin-1')