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

2024-08-22Python开发问题
4

本文介绍了使用Python SDK for Azure在创建虚拟机操作中添加用户数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我正在使用Python SDK进行Azure创建虚拟机操作。我希望在VM启动时执行一些脚本。因此,我尝试在使用Python创建VM时添加自定义数据。

我的目录:

  • user-data.sh
  • create_VM.py

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
Message: Custom data in OSProfile must be in Base64 encoding and with a maximum length of 87380 characters.
Target: customData

如何解决此问题?

推荐答案

请试试这件,它在我的身上起作用。

import base64

...

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

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

这篇关于使用Python SDK for Azure在创建虚拟机操作中添加用户数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

在xarray中按单个维度的多个坐标分组
groupby multiple coords along a single dimension in xarray(在xarray中按单个维度的多个坐标分组)...
2024-08-22 Python开发问题
15

Pandas中的GROUP BY AND SUM不丢失列
Group by and Sum in Pandas without losing columns(Pandas中的GROUP BY AND SUM不丢失列)...
2024-08-22 Python开发问题
17

pandas 有从特定日期开始的按月分组的方式吗?
Is there a way of group by month in Pandas starting at specific day number?( pandas 有从特定日期开始的按月分组的方式吗?)...
2024-08-22 Python开发问题
10

GROUP BY+新列+基于条件的前一行抓取值
Group by + New Column + Grab value former row based on conditionals(GROUP BY+新列+基于条件的前一行抓取值)...
2024-08-22 Python开发问题
18

PANDA中的Groupby算法和插值算法
Groupby and interpolate in Pandas(PANDA中的Groupby算法和插值算法)...
2024-08-22 Python开发问题
11

PANAS-基于列对行进行分组,并将NaN替换为非空值
Pandas - Group Rows based on a column and replace NaN with non-null values(PANAS-基于列对行进行分组,并将NaN替换为非空值)...
2024-08-22 Python开发问题
10