Search code examples
mavenvagrantvagrantfilevagrant-provision

Through vagrant running mvn command


I am working on writing vagrantfile for automation of local setup. Through vagrant, i am creating docker image for my app and running it inside vm. Everything is under one command i.e. vagrant up But one thing i have to do manual i.e. creating jar file for my app by using mvn clean package.

I am wondering is there any way to run mvn command from vagrantfile, so that when i issue vagrant up, it should build the JAR and do the rest of the work.


Solution

  • as @Patrick mentions, the shell provisioning is a good fit - I personally use for gradle but the same can be done for maven. Here is how I call my script

    config.vm.provision "shell", path: "script/run-test.sh", privileged: false, run: 'always'
    
    • path : is the path for my shell script from the project directory
    • privileged : if not set, root will run the script, if maven is installed for your vagrant user, make sure to set it to false else you will see issue
    • run: 'always' : this is my use-case (up to you to choose if it makes sense for you), the script will always run when I run vagrant up

    the shell script will be something like

    #!/bin/bash
    
    if [ -d "/home/vagrant/test" ];then 
        cd /home/vagrant/test && git pull
        cd /home/vagrant/test && maven compile
        cd /home/vagrant/test && maven deploy 
        .....
    
    else
        git clone <your project> /home/vagrant/test
    fi
    

    This is an example, basically first time I create the instance it will clone a git repo - then it will pull from git latest files and run your maven command.

    Again this is a simple example, use it for your own need