天天看點

Vagrant 檔案配置器的使用

Vagrant 檔案配置器的使用

摘要: 本文翻譯自 Vagrant 官方文檔 File Provisioner 部分,主要介紹了檔案配置器的使用,如何使用檔案配置器将本地檔案上拷貝到 Vagrant 所管理的虛拟機上面。

Provisioner name: “file”

Vagrant 檔案配置器可以将本地主機的檔案或者目錄上傳到虛拟機。

檔案配置器可以輕松地将本地

~/.gitconfig

複制到虛拟機的

vagrant

使用者家目錄,這樣的話就不需要在每次配置一個新的虛拟機時運作

git config --global

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

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

如果你想給虛拟機上傳一個目錄,可以使用下面的檔案配置器來完成。複制時,本地檔案夾會被複制到虛拟機的

newfolder

檔案夾。注意,如果想在虛拟機保持和本機同樣的檔案夾名稱,請確定目的路徑名稱和本地路徑名稱一緻。

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

     directory,  files
           

然後将

~/path/to/host/folder

拷貝到虛拟機的

$HOME/remote/newfolder

:

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

     directory,  files
           

注意,檔案上傳不像檔案目錄同步,上傳的檔案或者檔案夾不是保持同步的。還是以上面的例子來說,如果你更改了本地的

~/.gitconfig

,那麼虛拟機上的同樣的檔案并不會更改。

檔案配置器的檔案上傳是通過

SSH 或 PowerShell

使用者來上傳。通常情況下使用者的權限是有限的,如果你想将檔案上傳到需要更高權限的位置,我們推薦将它們上傳到臨時位置,然後使用 shell 配置器将它們移動到目标的位置。

選項

檔案配置器隻有兩個選項,并且是必須的:

  • source(string) - 要上傳的本地檔案或者檔案夾。
  • destination(string) - 遠端虛拟機路徑。檔案或者檔案夾通過

    SCP

    來上傳,是以該目的路徑需要對

    SSH

    使用者可寫。

    SSH

    使用者可以通過

    ssh-config

    來檢視,預設是

    vagrant

注意事項

盡管檔案配置器支援尾部斜杠或 “globing”,但這會導緻在本地和虛拟機之間複制檔案時産生一些令人困惑的結果。例如,如下源路徑沒有尾部斜杠,而目的路徑有尾部斜杠:

這意味着

vagrant

會将

~/pathfolder

上傳到遠端目錄

/remote/newlocation

底下,結果看起來會像下面這樣:

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

     directory,  files
           

同樣的行為也可以通過如下配置來實作:

另一個例子是使用

.

号,拷貝本地機器目錄裡面的檔案,不包括上一層目錄:

以上配置将

~/otherfolder

目錄下的所有檔案拷貝到新的路徑

/remote/otherlocation

。這個也可以通過指定一個和源檔案夾不同的遠端檔案夾來實作: