class VMConfig: def init(self, name): self.name = name self.box = "" self.memory = 1024 self.cpus = 1 self.private_ip = "" self.provision_scripts = [] def parse_vagrantfile(text): """Parse VM definitions from a simplified Vagrantfile""" configs = [] current = None for line in text.splitlines(): line = line.strip() if "config.vm.define" in line: if current: configs.append(current) current = VMConfig(line.split('"')[1]) elif "config.vm.box" in line: current.box = line.split('"')[1] elif "vb.memory" in line: current.memory = int(line.split("=")[1].strip()) elif "vb.cpus" in line: current.cpus = int(line.split("=")[1].strip()) elif "private_network" in line: current.private_ip = line.split('"')[1] elif "config.vm.provision" in line: current.provision_scripts.append(line.split('"')[1]) if current: configs.append(current) return configs def check_environment(env_name, configs): """Simulate verifying each VM matches the Vagrantfile blueprint""" report = [] for cfg in configs: report.append(f"[{env_name}] VM '{cfg.name}' matches Vagrantfile") report.append(f" box: {cfg.box}") report.append(f" memory: {cfg.memory}MB | cpus: {cfg.cpus}") if cfg.private_ip: report.append(f" private ip: {cfg.private_ip}") for script in cfg.provision_scripts: report.append(f" provision: {script}") report.append(" => check passed") return report def main(): vagrantfile = """ config.vm.define "master" do |m| m.vm.box = "ubuntu/focal64" m.vm.network "private_network", ip: "192.168.56.10" m.vm.provision "install-python.sh" end config.vm.define "worker" do |w| w.vm.box = "ubuntu/focal64" w.vm.provision "install-cuda.sh" end """ configs = parse_vagrantfile(vagrantfile) print(f"Parsed {len(configs)} VMs from Vagrantfile\n") for env in ["CI-01", "CI-02", "CI-03"]: for line in check_environment(env, configs): print(line) print("---") if name == "main": main() ```
代码用途:这个Python脚本模拟CI流水线中的环境检查步骤——解析Vagrantfile中定义的虚拟机配置,并在多个CI环境中验证每台虚拟机是否与蓝图一致。它演示了“环境即代码”的理念:环境配置可以作为文本被解析、验证和复用。