Use cloud-init to run a bash script in a Linux VM in Azure

Gäller för: ✔️ Flexibla skalningsuppsättningar för virtuella Linux-datorer ✔️

This article shows you how to use cloud-init to run an existing bash script on a Linux virtual machine (VM) or virtual machine scale sets (VMSS) at provisioning time in Azure. Dessa cloud-init-skript körs vid första uppstarten när resurserna har tillhandahållits av Azure. Mer information om hur cloud-init fungerar internt i Azure och vilka Linux-distributioner som stöds finns i översikten över cloud-init

Run a bash script with cloud-init

With cloud-init you do not need to convert your existing scripts into a cloud-config, cloud-init accepts multiple input types, one of which is a bash script.

If you have been using the Linux Custom Script Azure Extension to run your scripts, you can migrate them to use cloud-init. However, Azure Extensions have integrated reporting to alert to script failures, a cloud-init image deployment will NOT fail if the script fails.

To see this functionality in action, create a simple bash script for testing. Like the cloud-init #cloud-config file, this script must be local to where you will be running the AzureCLI commands to provision your virtual machine. For this example, create the file in the Cloud Shell not on your local machine. You can use any editor you wish. Make sure that the whole cloud-init file is copied correctly, especially the first line.

#!/bin/sh
echo "this has been written via cloud-init" + $(date) >> /tmp/myScript.txt

Before deploying this image, you need to create a resource group with the az group create command. En Azure-resursgrupp är en logisk container där Azure-resurser distribueras och hanteras. I följande exempel skapas en resursgrupp med namnet myResourceGroup i regionen eastus.

az group create --name myResourceGroup --location eastus

Now, create a VM with az vm create and specify the bash script file with --custom-data simple_bash.sh as follows:

az vm create \
  --resource-group myResourceGroup \
  --name vmName \
  --image imageCIURN \
  --custom-data simple_bash.sh \
  --generate-ssh-keys

Anmärkning

Replace myResourceGroup, vmName, and imageCIURN values accordingly. Make sure an image with Cloud-init is chosen.

Verify bash script has run

SSH to the public IP address of your VM shown in the output from the preceding command. Enter your own user and publicIpAddress as follows:

ssh <user>@<publicIpAddress>

Verify that /tmp/myScript.txt file exists and has the appropriate text inside of it.

sudo cat /tmp/myScript

If it does not, you can check the /var/log/cloud-init.log for more details. Search for the following entry:

sudo cat /var/log/cloud-init.log
Running config-scripts-user using lock Running command ['/var/lib/cloud/instance/scripts/part-001']

Nästa steg

Ytterligare moln-init-exempel på konfigurationsändringar finns i följande: