Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vagrantfile ruby syntax explanation

Tags:

ruby

vagrant

I'm confused with the ruby syntax used to configure Vagrant. Especially with this construct. Is this an assignment, a method call, or something else? Is it pure ruby or vagrant specific dialect?

config.vm.network "forwarded_port", guest: 3000, host: 3000

And this one. Is the "ansible" an assignment or an argument, and where |ansible| comes from?

config.vm.provision "ansible" do |ansible|
  ansible.playbook = "provisioners/docker.yml"
end

Where I can find more information about those specific expressions?

like image 843
Tuomas Toivonen Avatar asked Oct 08 '16 07:10

Tuomas Toivonen


People also ask

How is a Vagrantfile created?

Command: vagrant init [name [url]] This initializes the current directory to be a Vagrant environment by creating an initial Vagrantfile if one does not already exist. If a first argument is given, it will prepopulate the config. vm. box setting in the created Vagrantfile.

Is Vagrantfile a ruby?

The syntax of Vagrantfiles is Ruby, but knowledge of the Ruby programming language is not necessary to make modifications to the Vagrantfile, since it is mostly simple variable assignment.


2 Answers

Those are DSLs, Ruby is a very good language for writing DSL, take a look a this other question

Although those are DSLs, you can throw vanilla Ruby code outside those blocks, and probably inside as well as long as it gets evaluated.

like image 55
Tiago Lopo Avatar answered Oct 01 '22 17:10

Tiago Lopo


The Vagrantfile is written in standard Ruby syntax.

Here is an example Vagrantfile

Vagrant.configure("2") do |config|
  # this is an evaluation statement
  # .box is an string attribute
  config.vm.box = "debian/stretch64"

  # this is a method call
  # .synced_folder is a method that takes two positional arguments ('synced_folder', '/vagrant'), 
  # followed by some keyword arguments (disabled: true)
  config.vm.synced_folder 'synced_folder', '/vagrant', disabled: true

  # this is a method call, followed by a "do ... end" block
  # .provider is a method that takes one positional argument (:libvirt)
  config.vm.provider :libvirt do |node|
    # these are two evaluation statements
    node.cpus = 4
    node.memory = 4096
  end
end

From the official documents, you can see the variable "string" in "config.vm.box (string)", but not following the methods config-vm-provider and config-vm-synced_folder.

I was also confused about the Vagrantfile syntax, even after reading the offical documents. I think it's because Ruby looks very different to me compared to other languages I used before.

like image 31
user10316803 Avatar answered Oct 01 '22 17:10

user10316803