問題描述
重啟使用 Linux 系統的云主機后發現 /etc/hosts 文件被全部重寫或被添加了主機名和回環地址(例:127.0.0.1、127.0.1.1)的解析,導致域名解析不符合預期或出現問題。
問題原因
云平臺 Linux 鏡像中的一個核心組件是 cloud-init。作為開源的云初始化程序,cloud-init 主要用于對主機名、初始密碼等一些自定義信息進行初始化配置。若 cloud-init 配置中存在對 manage_etc_hosts 的配置,則 cloud-init 會根據具體配置值決定如何調整 /etc/hosts 文件。公共鏡像默認不啟用 cloud-init 對 /etc/hosts 的修改功能,即 manage_etc_hosts 不做配置或配置為 false(默認值)。若您使用了公共鏡像并修改了 cloud-init 配置或使用了私有鏡像,則可參考此指導來嘗試解決問題。
問題排查思路
/etc/hosts 文件被全部重寫可能是因為 cloud-init 配置中將 manage_etc_hosts 配置成了true(若您安裝的 cloud-init 版本低于22.3,則還可能是配置成了 template)。此時,cloud-init 會根據/etc/cloud/templates/hosts.tmpl 來重寫 /etc/hosts 文件。
而 /etc/hosts 文件被添加主機名解析可能是因為 cloud-init 配置中將 manage_etc_hosts 配置成了 localhost。
解決步驟
-
Cloud-init 配置文件是 /etc/cloud/cloud.cfg,您可能還將自定義配置放于 /etc/cloud/cloud.cfg.d/ 目錄下。搜索包含 manage_etc_hosts 配置的文件可使用以下命令:
grep -rn ‘manage_etc_hosts’ /etc/cloud/*返回結果示例:

-
以上述返回結果為例,可以看到在/etc/cloud/cloud.cfg 文件中的第20 行將 manage_etc_hosts 配置成了 localhost,此時您需要修改 cloud.cfg 中的 manage_etc_hosts 配置,即:
原文:
manage_etc_hosts: localhost修改后:
# manage_etc_hosts: localhost或者也可:
manage_etc_hosts: false -
按您的業務需求修改 /etc/hosts。