pve虚拟机cloud-init配置实现web控制台修改密码IP等

目标:给 Ubuntu 22.04 模板 VM 装上 cloud-init,克隆后在 PVE 界面 / qm set --cipassword 改密码即可生效(密码、hostname、SSH 公钥、IP 等都能由 PVE 下发)。

环境:PVE 9.2.2 116.19.21.200;源模板 VM 100(mo-ban-xun-ni-ji,用户名 jiyun / 密码 123,Ubuntu 22.04 live-server 安装)。

一句话原理:PVE 通过 cloudinit 盘(ide2 的 NoCloud CD-ROM)把 ciuser/cipassword 等用户数据喂给 guest 里的 cloud-init,克隆时 PVE 换新 instance-id,cloud-init 检测到新实例就重新应用密码。

上传常规的镜像此处以ubuntu-22.04.4-live-server-amd64.iso为例子

一、删除 subiquity 安装器残留(关键)

1
2
3
4
5
6
7
8
# 删两个残留文件(这一步是 cloud-init 生效的根因)
rm -f /etc/cloud/cloud.cfg.d/99-installer.cfg
rm -f /etc/cloud/cloud.cfg.d/subiquity-disable-cloudinit-networking.cfg
# 验证 datasource 已恢复默认(NoCloud 第一)
grep -r datasource_list /etc/cloud/cloud.cfg.d/
# /etc/cloud/cloud.cfg.d/90_dpkg.cfg:datasource_list: [ NoCloud, ConfigDrive, OpenNebula, DigitalOcean, Azure, AltCloud, OVF, MAAS, GCE, OpenStack, CloudSigma, SmartOS, Bigstep, Scaleway, AliYun, Ec2, CloudStack, Hetzner, IBMCloud, Oracle, Exoscale, RbxCloud, UpCloud, VMware, Vultr, LXD, NWCS, Akamai, None ]
# 重启
systemctl restart cloud-init

删掉的这两个文件是 subiquity(Ubuntu live-server 安装器)留下的:

  • 99-installer.cfg 里 datasource_list: [ None ] 把 cloud-init 锁死,导致密码改不动。
  • subiquity-disable-cloudinit-networking.cfg 里 network: {config: disabled} 禁用了 cloud-init 网络管理。

最后关机 > 硬件添加 cloudinit设备即可实现开关机、接下来制作成模板就行。

至此可以对虚拟机进行修改密码 配置IP等操作。

比如使用cloudinit配置IP 系统内会自动生成如下网卡配置

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
40
41
42
43
44
root@cloudinit-demo:/etc/netplan# cat 00-installer-config.yaml 
# This is the network config written by 'subiquity'
network:
ethernets:
enp6s18:
dhcp4: true
version: 2
root@cloudinit-demo:/etc/netplan# cat 50-cloud-init.yaml
# This file is generated from information provided by the datasource. Changes
# to it will not persist across an instance reboot. To disable cloud-init's
# network configuration capabilities, write a file
# /etc/cloud/cloud.cfg.d/99-disable-network-config.cfg with the following:
# network: {config: disabled}
network:
version: 2
ethernets:
eth0:
addresses:
- 10.10.10.100/24
match:
macaddress: bc:24:11:2f:eb:a6
nameservers:
addresses:
- 223.5.5.5
search:
- '1'
routes:
- to: default
via: 10.10.10.1
set-name: eth0
eth1:
addresses:
- 10.20.10.100/24
match:
macaddress: bc:24:11:30:58:52
nameservers:
addresses:
- 223.5.5.5
search:
- '1'
routes:
- to: default
via: 10.20.10.1
set-name: eth1