I am using Python sdk for azure creation virtual machine operation. I want some script to be executed whenever the VM starts. So, I have tried adding the custom-data while creating VM with Python.
My directory:
user-data.sh file will be similar to this:
#!/bin/bash
sudo apt install apache2 -y
sudo apt install git -y
I have used the base64 package on create_VM.py file, which looks like:
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,
}]
}
}
)
...
The error I am getting is:
Azure Error: InvalidParameter\nMessage: Custom data in OSProfile must be in Base64 encoding and with a maximum length of 87380 characters.\nTarget: customData
How can I fix the issue?
please try this one, it's working on mine.
import base64
...
file = open("user-data.sh", "r")
a = file.read().encode()
...
CUSTOM_DATA = base64.b64encode(a.encode('utf-8')).decode('latin-1')