Ruby 中的字符串连接(Vagrant 中 Junos vSRX 虚拟实验室的脚本配置)

Strings concatenation in Ruby (script provisioning of a Junos vSRX virtual lab in Vagrant)

我有以下正在运行的命令:

my_host_shell.inline = 'vagrant ssh router3 -c "/usr/sbin/cli -f /tmp/provision01_router3.sh"'

("vagrant ssh" 在主机中启动,连接到虚拟机,在那里它将 "provision01_router3.sh" 脚本(已经位于 VM 中)提供给 cli 解释器)。

现在我希望将 "router3" 和 "provision01_router3.sh" 字符串替换为变量,因为它们对于每个虚拟机都是不同的。 我尝试了很多方法,包括跟随,但 none 正在工作...

my_host_shell.inline = '"vagrant ssh " + node.vm.hostname +  " -c /usr/sbin/cli -f /tmp/" + script[:script_name]'

你能帮忙调试这条线吗?

这里是完整的 Vagrantfile(见最后几行): https://github.com/XiaoJu/junos_vagrant_virtual_lab/

VAGRANTFILE_API_VERSION = "2"
require "vagrant-host-shell"
require "vagrant-junos"
mynodes=[
    {
    :hostname => "router3",
    :box => "juniper/ffp-12.1X47-D15.4-packetmode",
    :ram => 512,
    :cpus => 2,
    :myscripts => [
        {
            :script_name => "provision01_router3.sh"
        },
        {
            :script_name => "provision02_all.sh"
        }
    ],
    :interfaces => [
        {
            :subnet_name => "3-to-6",
            :subnet_ip => "172.23.10.13"
        },
        {
            :subnet_name => "3-to-4",
            :subnet_ip => "172.23.3.13"
        },
        {
            :subnet_name => "exit3",
            :subnet_ip => "10.10.2.13"
        }
    ]
    } ]

Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
    config.vm.box_check_update = false
    mynodes.each do |machine|
        config.vm.define machine[:hostname] do |node|
            node.vm.box = machine[:box]
            node.vm.hostname = machine[:hostname]

            node.vm.provider "virtualbox" do |vb|
                vb.check_guest_additions = false
                vb.customize ["modifyvm", :id, "--memory", machine[:ram], "--cpus", machine[:cpus]]
            end

            # assign ip addresses to interfaces
            machine[:interfaces].each do |subnet|
                node.vm.network "private_network",
                            autoconfig: false,
                            ip: subnet[:subnet_ip],
                            virtualbox__intnet: subnet[:subnet_name]
            end

            # provision each node
            machine[:myscripts].each do |script|
                node.vm.provision "file",
                              source: script[:script_name], 
                              destination: '/tmp/' + script[:script_name]
                node.vm.provision :host_shell do |my_host_shell|
                              # my_host_shell.inline = 'vagrant ssh router3 -c "/usr/sbin/cli -f /tmp/provision01_router3.sh"'
                              my_host_shell.inline = '"vagrant ssh " + node.vm.hostname +  " -c /usr/sbin/cli -f /tmp/" + script[:script_name]'
                end
            end
        end
    end 
end

使用字符串插值;它将使您的代码更具可读性:

my_host_shell.inline = "vagrant ssh #{node.vm.hostname} -c \"/usr/sbin/cli -f /tmp/#{script[:script_name]}\""