Adding /etc/hosts entry to host machine on vagrant up

前端 未结 4 1716
花落未央
花落未央 2021-01-30 17:11

Is it possible for one to modify files on the host machine during the vagrant up process? For example, adding an entry to the host machine\'s /etc/hosts

4条回答
  •  庸人自扰
    2021-01-30 17:18

    I don't want to depend on some plug in to vagrant. It should be standard feature in Vagrant!!!! Untill then I use a shell script to propagate VM's in my cluster of new VMs. The key lines are :

    # Obtain the hostkey based on the IP-address and add it to the known_host list 
    ssh-keyscan -t ecdsa ${START}.${OFFSET} >> /home/vagrant/.ssh/known_hosts
    
    # obtain the hostname, because you might not know it yet, with the IP address:
    EXTERNAL_HOSTNAME=`ssh ${START}'.'${OFFSET} 'hostname'`
    # obtain the key ot the new other VM based on hostname and also add to known_hosts
    ssh-keyscan -t ecdsa ${EXTERNAL_HOSTNAME} >>  /home/vagrant/.ssh/known_hosts
    # so now you have the IP address and the corresponding hostname
    # add to /etc/hosts without being asked for "yes/no"
    echo  ${START}'.'${OFFSET}' '${EXTERNAL_HOSTNAME} >> /etc/hosts
    

    Where IPADRRESS is the IP address of the master VM in the cluster with several slave node VM's with succeedding ip-addresses. (IPADDRESS=IPADDRESS + 1 untill no successfull ping)

    IPADDRESS=`ip addr show eth1 | grep 'inet ' | cut -d ' ' -f 6 | cut -d '/' -f1`
    START=`echo ${IPADDRESS} | cut -d '.' -f1,2,3`
    OFFSET=`echo ${IPADDRESS} | cut -d '.' -f4`
    

    And then I loop trough the next IP addresses until no more succesfull pings. I do not want to hardcode anything (ip-address or hostname), but to find out itself.

    Resulting /etc/hosts file (after sort /etc/hosts | uniq > /tmp/hosts.uniq && sudo sh -c 'mv /tmp/hosts.uniq /etc/hosts' :

    [vagrant@master ~]$ cat /etc/hosts
    127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
    127.0.0.1       master.RHEL70.local     master
    192.168.1.50 master.RHEL70.local
    192.168.1.51 node01.RHEL70.local
    192.168.1.52 node02.RHEL70.local
    ::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
    

提交回复
热议问题