Linux初次開機期間時會呼叫 Cloud-init,因此不需要使用任何額外的步驟或必要的代理程式,就可以套用您的設定。如需如何正確地設定 #cloud-config 檔案格式的詳細資訊,請參閱 cloud-init 文件網站 (英文)。#cloud-config 檔案是以 base64 編碼的文字檔。
不是所有的linux版本都有支援,Cloud-init系統的支援版本及詳細的說明可以參考https://docs.microsoft.com/zh-tw/azure/virtual-machines/linux/using-cloud-init
利用portal建立VM的時候就可以在“進階”的選項中就可以輸入Cloud-init、也可以在Cloud Shell中將腳本建立為txt檔案,然後使用az vm create配合–custom-data上述的txt檔案建立VM。
官方範例:在Portal建立VM並安裝 NGINX 並執行簡單 ‘Hello World’ Node.js 應用程式
1.在Portal中建立Ubuntu 18.04,Port至少要開啟80port,在進階的部分的Cloud-init輸入以下內容
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
#cloud-config package_upgrade: true packages: - nginx - nodejs - npm write_files: - owner: www-data:www-data path: /etc/nginx/sites-available/default content: | server { listen 80; location / { proxy_pass http://localhost:3000; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection keep-alive; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; } } - owner: azureuser:azureuser path: /home/azureuser/myapp/index.js content: | var express = require('express') var app = express() var os = require('os'); app.get('/', function (req, res) { res.send('Hello World from host ' + os.hostname() + '!') }) app.listen(3000, function () { console.log('Hello world app listening on port 3000!') }) runcmd: - service nginx restart - cd "/home/azureuser/myapp" - npm init - npm install express -y - nodejs index.js |
建立完畢後查看ip為52.167.44.86
等待一會後打開瀏覽器訪問http://52.167.44.86,可以看到已經建立好的網站
ssh連線到VM中,可以通過/var/log/cloud-init.log和cloud-init-output.log查看相關的執行記錄。