如何为Azure ARM模板添加CustomScriptForLinux扩展修改Linux VM的/etc/hosts
Add CustomScriptForLinux Extension to Edit /etc/hosts in ARM Template
Got it, let's get that CustomScript extension set up to modify your /etc/hosts file right in your ARM template. Here's how to complete and refine the snippet you shared, plus key details to make it work smoothly:
Full Extension Resource Definition
Add this complete block to your template.json (make sure it's placed alongside your VM resource, or within the resources array):
{ "name": "[concat(parameters('virtualMachineName'),'/edithosts')]", "type": "Microsoft.Compute/virtualMachines/extensions", "apiVersion": "2023-07-01", "location": "[parameters('location')]", "dependsOn": [ "[resourceId('Microsoft.Compute/virtualMachines', parameters('virtualMachineName'))]" ], "properties": { "publisher": "Microsoft.Azure.Extensions", "type": "CustomScript", "typeHandlerVersion": "2.1", "autoUpgradeMinorVersion": true, "settings": {}, "protectedSettings": { "commandToExecute": "echo '192.168.1.100 my-custom-host.local' >> /etc/hosts" } } }
Critical Notes for Your Setup
- DependsOn: This ensures the extension only runs after the VM is fully created—no race conditions here.
- Command Customization: Replace the example
'192.168.1.100 my-custom-host.local'with the exact IP and hostname you want to add. For multiple lines, chain commands with&&:"commandToExecute": "echo 'line1' >> /etc/hosts && echo 'line2' >> /etc/hosts" - Dynamic Values: If you want to use parameterized values (like a hostname from your
parameters.json), tweak the command with template expressions:
Just remember to add those new parameters ("commandToExecute": "[concat('echo ''', parameters('targetHostIp'), ' ', parameters('targetHostname'), ''' >> /etc/hosts')]"targetHostIpandtargetHostname) to yourparameters.jsonfile.
Verify It Works
Run your existing deployment command as usual:
New-AzureRmResourceGroupDeployment -TemplateFile .\template.json -TemplateParameterFile .\parameters.json -ResourceGroupName my-rg -virtualMachineName my-test-vm
Once deployed, SSH into the VM and check /etc/hosts—your new line should be there.
内容的提问来源于stack exchange,提问作者Paul Croarkin
相关产品推荐
相关产品推荐

