【问题标题】:Evaluate expression on host machine and pass results to the provisioning shell script as an argument评估主机上的表达式并将结果作为参数传递给配置 shell 脚本
【发布时间】:2015-12-16 21:15:35
【问题描述】:

我的尝试

流浪文件:

...
config.vm.provision "shell", privileged: false, path: "provisioning/config-git.sh", args: "$(whoami)"
...

配置/config-git.sh:

#!/usr/bin/env bash

username=$1

git config --global user.email "$username@stackoverflow.com"
git config --global user.name $username

在机器配置好后,我通过 ssh 进入它,这是实际的结果:

实际输出

# Host Machine:
$ whoami
axiopisty

# Guest Machine:
$ whoami
vagrant
$ git config --list
user.email=vagrant@stackoverflow.com
user.name=vagrant

除了传递给 config-git.sh 脚本的参数外,一切都按预期工作。参数是"$(whoami)"。我想在主机上评估表达式,以便将执行 vagrant 命令的用户的用户名作为参数插入到作为 vagrant 用户在客户机上执行的脚本的参数中。

假设主机上用户的用户名是“axiopisty”,我想要以下结果:

预期输出

# Host Machine:
$ whoami
axiopisty

# Guest Machine:
$ whoami
vagrant
$ git config --list
user.email=axiopisty@stackoverflow.com
user.name=axiopisty

问题

如何让 vagrant 评估主机上的表达式,并将评估结果作为参数传递给配置 shell 脚本?

【问题讨论】:

    标签: vagrant


    【解决方案1】:

    您快到了,但 vagrant 运行带有所有参数的 SSH 命令,因此您的参数在来宾 VM 中解析。您需要做的是从主机保存您的用户名值,然后再将 shell 配置作为参数传递此值。

    这是一个要添加到您的 Vagrantfile 中的示例

      username = `whoami`.chomp # you need chomp as the result of the command executed this way returns \n at the end
      config.vm.provision "shell", privileged: false, path: "provisioning/config-git.sh", args: "#{username}"
    

    我本地执行的输出

    fhenri@machine:~/project/examples/vagrant/ubuntu$ whoami
    fhenri
    fhenri@machine:~/project/examples/vagrant/ubuntu$ vagrant ssh
    Welcome to Ubuntu 12.04.1 LTS (GNU/Linux 3.2.0-29-virtual x86_64)
    
     * Documentation:  https://help.ubuntu.com/
    Last login: Wed Dec 16 22:59:01 2015 from 172.16.42.1
    vagrant@ubuntu:~$ whoami
    vagrant
    vagrant@ubuntu:~$ git config --list
    user.email=fhenri@stackoverflow.com
    user.name=fhenri
    

    【讨论】:

    • 另外,我刚刚发现,对于这个特定的用例,我可以使用这样的环境变量:config.vm.provision "shell", privileged: false, path: "provisioning/config-git.sh", args: "#{ENV['USER']}"
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-12
    • 2014-03-13
    • 2014-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多