Can we add text to a file inside a vagrant vm during vagrant up?

26 views
Skip to first unread message

Soham Chakraborty

unread,
Jul 27, 2016, 2:19:48 AM7/27/16
to Vagrant
Hi, 

I have a four node vagrant setup that I am using to test puppet. What I intend to do is to add the FQDN of the puppetmaster node to the 2nd line of the /etc/hosts of the other 3 nodes. The Vagrantfile is thus: 

# -*- mode: ruby -*-
# vi: set ft=ruby :
#
#
Vagrant.configure(2) do |config|
  config.vm.box = "ubuntu/trusty64"
  config.vm.provision "shell", path: "script.sh"

  config.vm.define "puppetmaster" do |puppetmaster|
    puppetmaster.vm.network :private_network, ip: "192.168.33.33"
    puppetmaster.vm.network :forwarded_port, guest: 80, host: 8080
    puppetmaster.vm.network :forwarded_port, guest: 8140, host: 8141
    puppetmaster.vm.hostname = "puppetmaster.example.com"
  end

  config.vm.define "web" do |web|
    web.vm.network :private_network, ip: "192.168.33.34"
    web.vm.network :forwarded_port, guest: 8140, host: 8142
    web.vm.hostname = "web.example.com"
  end

  config.vm.define "mail" do |mail|
    mail.vm.network :private_network, ip: "192.168.33.35"
    mail.vm.network :forwarded_port, guest: 8140, host: 8143
    mail.vm.hostname = "mail.example.com"
  end

  config.vm.define "db" do |db|
    db.vm.network :private_network, ip: "192.168.33.36"
    db.vm.network :forwarded_port, guest: 8140, host: 8144
    db.vm.hostname = "db.example.com"
  end

end

script.sh is used for updating the vm, otherwise puppet-common won't be installed. 

$ cat script.sh 
sudo apt-get update -y
sudo apt-get install puppet -y

With this setup, after the four machines boot up, I go to web, db and mail vms and do a sed -i "2i 192.168.33.33 puppetmaster.example.com puppet" /etc/hosts to include the FQDN of the puppetmaster host. 

1) Can this be accomplished by any method inside the Vagrantfile or in script.sh? 

2) Also, any critique to write the Vagrantfile better will be appreciated. I feel like maintaining the file like I do now can be a bit cumbersome when I add more machines or want to do specific things to specific nodes. I don't have a specific example right now, this is just a thought. 

Thanks guys!

Alvaro Miranda Aguilera

unread,
Jul 27, 2016, 6:33:18 AM7/27/16
to vagra...@googlegroups.com

On Wed, Jul 27, 2016 at 6:19 PM, Soham Chakraborty <dec....@gmail.com> wrote:
sed -i "2i 192.168.33.33 puppetmaster.example.com puppet"

Hello,

Looks good, you could something like this

grep -i puppetmaster /etc/hosts || {
   echo "192.168.33.33 puppetmaster.example.com puppet" | tee -a /etc/hosts
}

Alvaro.

pixel fairy

unread,
Aug 15, 2016, 6:17:50 AM8/15/16
to Vagrant
also, the vagrant-hostmanager plugin does this for you. https://github.com/devopsgroup-io/vagrant-hostmanager
Reply all
Reply to author
Forward
0 new messages