Skip to content

Instantly share code, notes, and snippets.

@sherbang
Last active August 29, 2015 14:21
Show Gist options
  • Save sherbang/7ab35be2fca640346765 to your computer and use it in GitHub Desktop.
Save sherbang/7ab35be2fca640346765 to your computer and use it in GitHub Desktop.
Use incrontab to auto-update vagrant boxes
#!/usr/bin/env python3
# Run by incron whenever a file in the vagrant_boxes dir changes.
# Updates the corresponding box in vagrant (vagrant box add -f)
#
# For me, boxes in vagrant_boxes are created on another machine
# and synced over with BTSync. This detects the change for me and
# makes sure my local box is fresh.
#
# Add this to your incrontab:
# /path/to/vagrant_boxes IN_CREATE,IN_CLOSE_WRITE,IN_MOVE,IN_NO_LOOP /path/to/refresh_vagrant_box.py $@/$# $%
import sys
import os
import sh
import logging
logfile = os.path.expanduser('~/incron.log')
boxes_to_monitor = [
'windows_81_virtualbox.box',
'windows_2012_r2_virtualbox.box',
]
logger = logging.getLogger('refresh_vagrant_box')
logger.setLevel(logging.DEBUG)
fh = logging.FileHandler(logfile)
fh.setLevel(logging.DEBUG)
logger.addHandler(fh)
file_path = sys.argv[1]
event_flags = sys.argv[2]
# somehow BTSync avoids triggering any write/move on the final filename.
# So, we'll just wait for the end of writing and then process the output file.
if file_path.endswith('.!sync') and event_flags == 'IN_CLOSE_WRITE':
file_path = os.path.splitext(file_path)[0]
file_base = os.path.basename(file_path)
if file_base in boxes_to_monitor:
# windows_2012_r2_virtualbox.box -> windows_2012_r2
box_name = file_base.rsplit('_', 1)[0]
if os.path.exists(file_path):
logger.debug('Updating {} {}'.format(box_name, event_flags))
sh.vagrant('box', 'add', '-f', box_name, file_path)
else:
logger.debug('File not found - skipping')
else:
logger.debug('Skipping {} {}'.format(file_path, event_flags))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment