Share via


建立一般化映像而不佈建代理程式

適用於:✔️ Linux VM ✔️ 彈性擴展集

Microsoft Azure 會以 walinuxagentcloud-init 的形式為 Linux VM 提供佈建代理程式 (建議)。 但當您不想要針對佈建代理程式使用其中一個應用程式時,可能會有一個案例,例如:

  • 您的 Linux 散發/版本不支援 cloud-init/Linux 代理程式。
  • 您必須設定特定的 VM 屬性,例如主機名稱。

注意

如果您不需要設定任何屬性,或發生任何形式的佈建,則應該考慮建立特製化映像。

本文說明如何設定 VM 映像以滿足 Azure 平台需求,並設定主機名稱,而不安裝佈建代理程式。

網路和報告就緒

若要讓您的 Linux VM 與 Azure 元件通訊,需要 DHCP 用戶端。 用戶端可用來從虛擬網路擷取主機 IP、DNS 解析及路由管理。 大部分散發版本隨附於現成可用的公用程式。 Linux 散發版本廠商在 Azure 上測試的工具組包括 dhclientnetwork-managersystemd-networkd 和其他。

注意

目前建立未佈建代理程式的一般化映像僅支援啟用 DHCP 的 VM。

設定網路之後,選取 [報告就緒]。 這會向 Azure 告知 VM 已成功佈建。

重要

若無法向 Azure 報告就緒,則會導致您的 VM 重新開機!

示範/範例

已移除 Linux 代理程式 (walinuxagent) 的現有 Marketplace 映像 (在此案例中為 Debian Buster VM),並新增自訂 Python 指令碼是告知 Azure VM「就緒」的最簡單方式。

建立資源群組和基底 VM:

$ az group create --location eastus --name demo1

建立基底 VM:

$ az vm create \
    --resource-group demo1 \
    --name demo1 \
    --location eastus \
    --ssh-key-value <ssh_pub_key_path> \
    --public-ip-address-dns-name demo1 \
    --image "debian:debian-10:10:latest"

移除映像佈建代理程式

佈建 VM 之後,您可以透過 SSH 連線到 VM 並移除 Linux 代理程式:

$ sudo apt purge -y waagent
$ sudo rm -rf /var/lib/waagent /etc/waagent.conf /var/log/waagent.log

將必要的程式碼新增至 VM

此外,在 VM 內,因為我們已移除 Azure Linux 代理程式,所以我們需要提供一個機制來報告就緒。

Python 指令碼

import http.client
import sys
from xml.etree import ElementTree

wireserver_ip = '168.63.129.16'
wireserver_conn = http.client.HTTPConnection(wireserver_ip)

print('Retrieving goal state from the Wireserver')
wireserver_conn.request(
    'GET',
    '/machine?comp=goalstate',
    headers={'x-ms-version': '2012-11-30'}
)

resp = wireserver_conn.getresponse()

if resp.status != 200:
    print('Unable to connect with wireserver')
    sys.exit(1)

wireserver_goalstate = resp.read().decode('utf-8')

xml_el = ElementTree.fromstring(wireserver_goalstate)

container_id = xml_el.findtext('Container/ContainerId')
instance_id = xml_el.findtext('Container/RoleInstanceList/RoleInstance/InstanceId')
incarnation = xml_el.findtext('Incarnation')
print(f'ContainerId: {container_id}')
print(f'InstanceId: {instance_id}')
print(f'Incarnation: {incarnation}')

# Construct the XML response we need to send to Wireserver to report ready.
health = ElementTree.Element('Health')
goalstate_incarnation = ElementTree.SubElement(health, 'GoalStateIncarnation')
goalstate_incarnation.text = incarnation
container = ElementTree.SubElement(health, 'Container')
container_id_el = ElementTree.SubElement(container, 'ContainerId')
container_id_el.text = container_id
role_instance_list = ElementTree.SubElement(container, 'RoleInstanceList')
role = ElementTree.SubElement(role_instance_list, 'Role')
instance_id_el = ElementTree.SubElement(role, 'InstanceId')
instance_id_el.text = instance_id
health_second = ElementTree.SubElement(role, 'Health')
state = ElementTree.SubElement(health_second, 'State')
state.text = 'Ready'

out_xml = ElementTree.tostring(
    health,
    encoding='unicode',
    method='xml'
)
print('Sending the following data to Wireserver:')
print(out_xml)

wireserver_conn.request(
    'POST',
    '/machine?comp=health',
    headers={
        'x-ms-version': '2012-11-30',
        'Content-Type': 'text/xml;charset=utf-8',
        'x-ms-agent-name': 'custom-provisioning'
    },
    body=out_xml
)

resp = wireserver_conn.getresponse()
print(f'Response: {resp.status} {resp.reason}')

wireserver_conn.close()

Bash 指令碼

#!/bin/bash

attempts=1
until [ "$attempts" -gt 5 ]
do
    echo "obtaining goal state - attempt $attempts"
    goalstate=$(curl --fail -v -X 'GET' -H "x-ms-agent-name: azure-vm-register" \
                                        -H "Content-Type: text/xml;charset=utf-8" \
                                        -H "x-ms-version: 2012-11-30" \
                                           "http://168.63.129.16/machine/?comp=goalstate")
    if [ $? -eq 0 ]
    then
       echo "successfully retrieved goal state"
       retrieved_goal_state=true
       break
    fi
    sleep 5
    attempts=$((attempts+1))
done

if [ "$retrieved_goal_state" != "true" ]
then
    echo "failed to obtain goal state - cannot register this VM"
    exit 1
fi

container_id=$(grep ContainerId <<< "$goalstate" | sed 's/\s*<\/*ContainerId>//g' | sed 's/\r$//')
instance_id=$(grep InstanceId <<< "$goalstate" | sed 's/\s*<\/*InstanceId>//g' | sed 's/\r$//')

ready_doc=$(cat << EOF
<?xml version="1.0" encoding="utf-8"?>
<Health xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <GoalStateIncarnation>1</GoalStateIncarnation>
  <Container>
    <ContainerId>$container_id</ContainerId>
    <RoleInstanceList>
      <Role>
        <InstanceId>$instance_id</InstanceId>
        <Health>
          <State>Ready</State>
        </Health>
      </Role>
    </RoleInstanceList>
  </Container>
</Health>
EOF
)

attempts=1
until [ "$attempts" -gt 5 ]
do
    echo "registering with Azure - attempt $attempts"
    curl --fail -v -X 'POST' -H "x-ms-agent-name: azure-vm-register" \
                             -H "Content-Type: text/xml;charset=utf-8" \
                             -H "x-ms-version: 2012-11-30" \
                             -d "$ready_doc" \
                             "http://168.63.129.16/machine?comp=health"
    if [ $? -eq 0 ]
    then
       echo "successfully register with Azure"
       break
    fi
    sleep 5 # sleep to prevent throttling from wire server
done

一般步驟 (如果未使用 Python 或 Bash)

如果您的 VM 未安裝 Python 或無法使用 Python,則可以使用下列步驟,以程式設計方式重現上述指令碼邏輯:

  1. 剖析 WireServer 的回應:curl -X GET -H 'x-ms-version: 2012-11-30' http://168.63.129.16/machine?comp=goalstate,藉此擷取 ContainerIdInstanceIdIncarnation

  2. 建構下列 XML 資料,並插入上述步驟中剖析的 ContainerIdInstanceIdIncarnation

    <Health>
      <GoalStateIncarnation>INCARNATION</GoalStateIncarnation>
      <Container>
        <ContainerId>CONTAINER_ID</ContainerId>
        <RoleInstanceList>
          <Role>
            <InstanceId>INSTANCE_ID</InstanceId>
            <Health>
              <State>Ready</State>
            </Health>
          </Role>
        </RoleInstanceList>
      </Container>
    </Health>
    
  3. 將此資料張貼到 WireServer:curl -X POST -H 'x-ms-version: 2012-11-30' -H "x-ms-agent-name: WALinuxAgent" -H "Content-Type: text/xml;charset=utf-8" -d "$REPORT_READY_XML" http://168.63.129.16/machine?comp=health

自動在第一次開機時執行程式碼

此示範是使用 systemd,這是新式 Linux 散發版本中最常見的 init 系統。 因此,確保此報告就緒機制在正確時間執行最簡單且最原生的方式,就是建立 systemd 服務單位。 您可以將下列單元檔案新增至 /etc/systemd/system (此範例會將單元檔案 azure-provisioning.service 命名為):

[Unit]
Description=Azure Provisioning

[Service]
Type=oneshot
ExecStart=/usr/bin/python3 /usr/local/azure-provisioning.py
ExecStart=/bin/bash -c "hostnamectl set-hostname $(curl \
    -H 'metadata: true' \
    'http://169.254.169.254/metadata/instance/compute/name?api-version=2019-06-01&format=text')"
ExecStart=/usr/bin/systemctl disable azure-provisioning.service

[Install]
WantedBy=multi-user.target

此 systemd 服務會執行三項基本佈建工作:

  1. 準備好向 Azure 報告 (以指出其已成功)。
  2. Azure 執行個體中繼資料服務 (IMDS) 提取此資料,以根據使用者提供的 VM 名稱,將 VM 重新命名。 注意 IMDS 也提供其他執行個體中繼資料 (例如 SSH 公開金鑰),因此您可以設定超過主機名稱。
  3. 將本身停用,使其只在第一次開機時執行,而不會在後續重新開機時執行。

使用檔案系統上的單位,執行下列命令以將其啟用:

$ sudo systemctl enable azure-provisioning.service

現在已準備好將 VM 一般化,並從中建立映像。

完成映像的準備

回到開發電腦,執行下列命令以準備從基底 VM 建立映像:

$ az vm deallocate --resource-group demo1 --name demo1
$ az vm generalize --resource-group demo1 --name demo1

然後從此 VM 建立映像:

$ az image create \
    --resource-group demo1 \
    --source demo1 \
    --location eastus \
    --name demo1img

現在我們已經準備好從映像建立新的 VM。 這也可以用來建立多個 VM:

$ IMAGE_ID=$(az image show -g demo1 -n demo1img --query id -o tsv)
$ az vm create \
    --resource-group demo12 \
    --name demo12 \
    --location eastus \
    --ssh-key-value <ssh_pub_key_path> \
    --public-ip-address-dns-name demo12 \
    --image "$IMAGE_ID"
    --enable-agent false

注意

請務必將 --enable-agent 設定為 false,因為要從映像建立的這個 VM 上沒有 walinuxagent。

VM 應該已成功佈建。 登入新佈建的 VM 之後,您應該可以看到報告就緒 systemd 服務的輸出:

$ sudo journalctl -u azure-provisioning.service
-- Logs begin at Thu 2020-06-11 20:28:45 UTC, end at Thu 2020-06-11 20:31:24 UTC. --
Jun 11 20:28:49 thstringnopa systemd[1]: Starting Azure Provisioning...
Jun 11 20:28:54 thstringnopa python3[320]: Retrieving goal state from the Wireserver
Jun 11 20:28:54 thstringnopa python3[320]: ContainerId: 7b324f53-983a-43bc-b919-1775d6077608
Jun 11 20:28:54 thstringnopa python3[320]: InstanceId: fbb84507-46cd-4f4e-bd78-a2edaa9d059b._thstringnopa2
Jun 11 20:28:54 thstringnopa python3[320]: Sending the following data to Wireserver:
Jun 11 20:28:54 thstringnopa python3[320]: <Health><GoalStateIncarnation>1</GoalStateIncarnation><Container><ContainerId>7b324f53-983a-43bc-b919-1775d6077608</ContainerId><RoleInstanceList><Role><InstanceId>fbb84507-46cd-4f4e-bd78-a2edaa9d059b._thstringnopa2</InstanceId><Health><State>Ready</State></Health></Role></RoleInstanceList></Container></Health>
Jun 11 20:28:54 thstringnopa python3[320]: Response: 200 OK
Jun 11 20:28:56 thstringnopa bash[472]:   % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
Jun 11 20:28:56 thstringnopa bash[472]:                                  Dload  Upload   Total   Spent    Left  Speed
Jun 11 20:28:56 thstringnopa bash[472]: [158B blob data]
Jun 11 20:28:56 thstringnopa2 systemctl[475]: Removed /etc/systemd/system/multi-user.target.wants/azure-provisioning.service.
Jun 11 20:28:56 thstringnopa2 systemd[1]: azure-provisioning.service: Succeeded.
Jun 11 20:28:56 thstringnopa2 systemd[1]: Started Azure Provisioning.

支援

如果您實作自己的佈建程式碼/代理程式,則您就擁有此程式碼的支援,Microsoft 支援只會調查佈建介面無法使用的相關問題。 我們會持續在此區域中進行改善和變更,因此您必須監視 cloud-init 和 Azure Linux 代理程式中的變更,以佈建 API 變更。

下一步

如需詳細資訊,請參閱 Linux 佈建