Vagrant 手册之 Provisioning - file 配置程序

原文地址

Provisioner 命令:“file”

通过 file 配置程序可以上传宿主机的文件或目录到虚拟机中。

使用场景:将宿主机的 ~/.gitconfig 复制到虚拟机中的用户家目录,这样就不用每次都要为新的虚拟机执行 git config --global

Vagrant.configure("2") do |config|
  # ... other configuration

  config.vm.provision "file", source: "~/.gitconfig", destination: ".gitconfig"
end

可以上传目录到虚拟机。复制时,宿主机上的文件夹将替换文件夹作为新文件夹并将其放在虚拟机上。注意,如果希望在虚拟机上使用相同的文件夹名称,请确保目标路径(destination )与主机上的文件夹名称相同。

Vagrant.configure("2") do |config|
  # ... other configuration

  config.vm.provision "file", source: "~/path/to/host/folder", destination: "$HOME/remote/newfolder"
end

在将 ~/path/to/host/folder 复制到虚拟机之前:

    folder
    ├── script.sh
    ├── otherfolder
    │   └── hello.sh
    ├── goodbye.sh
    ├── hello.sh
    └── woot.sh

    1 directory, 5 files

~/path/to/host/folder 复制到虚拟机中的 $HOME/remote/newfolder 之后:

    newfolder
    ├── script.sh
    ├── otherfolder
    │   └── hello.sh
    ├── goodbye.sh
    ├── hello.sh
    └── woot.sh

    1 directory, 5 files

注意,与同步文件夹不同,上传的文件或目录不会保持同步。对于上面的例子,如果对本地 ~/.gitconfig 进行更改,它们将不会立即反映在上传到虚拟机的副本中。

由 file provisioner 上传的文件以 SSH 或 PowerShell 用户身份完成。这很重要,因为这些用户通常无法提升权限。如果想将文件上传到需要特权的位置,我们建议将它们上传到临时位置,然后使用 shell provisioner 将它们移动到位。

选项

file provisioner 只有两个选项,都是必须的:

  • source (string) - 要上传的文件或目录的本地路径。
  • destination (string) - 虚拟机中用于接收上传文件的远端路径。文件或目录通过 SCP 之上的 SSH 上传,因此路径必须对用户可写。SSH 用户可以通过运行 vagrant ssh-config 来决定,默认是“vagrant”。

警告

虽然 file provisioner 确实支持尾部斜杠或“全局”,但由于用于在主机和虚拟机之间复制文件和文件夹的底层工具的差异,这可能会导致一些令人困惑的结果。例如,如果源和目标的尾部斜线定义如下:

  config.vm.provision "file", source: "~/pathfolder", destination: "/remote/newlocation/"

你这是在告诉 vagrant 上传 ~/pathfolder/remote/newlocation 下面:

    newlocation
    ├── pathfolder
    │   └── file.sh

    1 directory, 2 files

此行为也可以通过下面的定义你的 file provisioner 来实现:

  config.vm.provision "file", source: "~/pathfolder", destination: "/remote/newlocation/pathfolder"

另一个例子是在主机上使用 globing 来抓取文件夹内的所有文件,但不是顶层文件夹本身:

  config.vm.provision "file", source: "~/otherfolder/.", destination: "/remote/otherlocation"

file provisioner 被定义为将 ~/otherfolder 下的所有文件包含到新位置 /remote/otherlocation。这个想法可以通过简单地让目标文件夹与源文件夹不同来实现:

  config.vm.provision "file", source: "/otherfolder", destination: "/remote/otherlocation"

posted on 2018-05-19 17:28  kikajack  阅读(177)  评论(0编辑  收藏  举报