深入探索 cloud-init

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

若要深入瞭解 cloud-init 或更深層次進行疑難排解,您必須瞭解其運作方式。 此文件會強調重要部分,並說明 Azure 細節。

當 cloud-init 包含在一般化映像中,並從該映像建立 VM 時,它會在初始開機期間處理設定並執行五個階段。 這些階段會展示 cloud-init 在什麼時候套用其設定。

瞭解 Cloud-Init 設定

設定 VM 以在平台上執行,會使用 cloud-init 來套用多個設定。 您與之互動的主要設定是 User data (customData),其支援多種格式。 如需詳細資訊,請參閱 User-Data Formats 和 cloud-init 21.2 文件。 您也可以新增並執行其他設定的指令碼 (/var/lib/cloud/scripts)。

預先設定的 Azure Marketplace 映像

某些設定已內嵌在 Cloud-init 隨附的 Azure Marketplace 映像中。

  • 雲端資料來源 – cloud-init 包含可與雲端平台互動的程式碼,這些程式碼稱為「資料來源」。 從 Azure 中 cloud-init 映像建立 VM 時,cloud-init 會載入 Azure 資料來源,其與 Azure 中繼資料端點互動以取得 VM 特定設定。

  • 執行階段設定 (/run/cloud-init)。

  • 映像設定 (/etc/cloud),例如 /etc/cloud/cloud.cfg/etc/cloud/cloud.cfg.d/*.cfg。 在 Azure 中使用此設定的範例中,使用 cloud-init 的 Linux OS 映像通常會有 Azure 資料來源指示詞,告知 cloud-init 應該使用哪些資料來源,此設定可節省 cloud-init 時間:

    sudo cat /etc/cloud/cloud.cfg.d/90_dpkg.cfg
    
    # to update this file, run dpkg-reconfigure cloud-init
    datasource_list: [ Azure ]
    

Cloud-init 開機階段 (處理設定)

當您使用 cloud-init 佈建 VM 時,有五個設定開機階段。 這些階段的輸出會顯示在記錄中。

  1. 產生器階段:cloud-init 系統產生器會啟動,並判斷 cloud-init 應該包含在開機目標中,如果是的話,它會啟用 cloud-init。

  2. Cloud-init 本機階段:在這裡,cloud-init 會尋找本機 "Azure" 資料來源,讓 cloud-init 能夠與 Azure 進行介接,並套用網路設定,包括後援。

  3. Cloud-init 初始階段 (網路):網路應該上線,而且應該產生 NIC 和路由表資訊。 在這個階段中,會執行 /etc/cloud/cloud.cfgcloud_init_modules 中所列出的模組。 Azure 中的 VM 會掛接、暫時性磁碟格式化、設定主機名稱以及其他工作。

    以下是一些 cloud_init_modules

    - migrator
    - seed_random
    - bootcmd
    - write-files
    - growpart
    - resizefs
    - disk_setup
    - mounts
    - set_hostname
    - update_hostname
    - ssh
    

    在此階段之後,cloud-init 會將信號傳送至 Azure 平台,指出 VM 已成功佈建。 某些模組可能失敗,但並非所有模組失敗都自動導致佈建失敗。

  4. Cloud-init 設定階段:在這個階段,cloud_config_modules 中的模組,定義並列在 /etc/cloud/cloud.cfg 執行中。

  5. Cloud-init 最終階段:在這個最後階段,cloud_final_modules中的模組會列在 /etc/cloud/cloud.cfg 中,並執行。 以下是在開機流程執行後期必須執行的模組,例如套件安裝及執行指令碼等。

    • 在此階段中,您可以將指令碼放在 /var/lib/cloud/scripts 底下的目錄中:
      • per-boot – 此目錄中的指令碼,在每個重新啟動時執行
      • per-instance– 首次啟動新執行個體時執行此目錄中的指令碼
      • per-once – 此目錄中的指令碼僅執行一次

下一步

針對 cloud-init 進行疑難排解