'Can I define the hostname (or other variable) on the vagrant command line?

I want to do something like this:

vagrant up --hostname="hello.world"

However there's no --hostname.

The reason I want this is so that the provisioner (Ansible) can use it to modify the provisioning depending on the hostname.

I could also use vagrant up hello.world (in which case Ansible could use it as inventory_hostname), but in that case I'd need to create an entry for hello.world in the Vagrantfile, which I don't want, since all possible hosts use the same Vagrantfile configuration. (An alternative could be to somehow specify in the Vagrantfile "use this configuration regardless of vm-name", but I don't know how to do that either.)

If none of this works, I could use an environment variable, but I don't know how to process that in Vagrantfile either.



Solution 1:[1]

You can call vagrant like:

HOSTNAME=myhostname vagrant up

In your Vagrantfile, store the environment variable:

$hostname = #{ENV['HOSTNAME']}"

And then call your ansible playbook passing extra_vars:

ansible.extra_vars = {
  hostname: "#{$hostname}"
}

Alternatively, if these hostnames are predefined in groups in your playbook you can use limit:

ansible.limit = "#{$hostname}"

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 HiroCereal