Commit bb4f8f4c authored by Noe Nieto's avatar Noe Nieto 💬

Shipyard becoming something more than a crude wrapper

parent 77581f36
......@@ -5,6 +5,7 @@ import argparse
import tempfile
import subprocess
import json
from pathlib import Path
vagrant_template = """
Vagrant.configure("2") do |config|
......@@ -23,59 +24,97 @@ Vagrant.configure("2") do |config|
end
"""
def print_status():
"""
Prints the status of all the virtual machines managed by shipyard
"""
shpyrd_paths = [str(d) for d in Path(os.environ['HOME'], '.shipyard').iterdir() if d.is_dir()]
vgt_db = Path(
os.environ.get('VAGRANT_HOME', str(Path.home())),
'.vagrant.d', 'data', 'machine-index', 'index'
)
count = 0
if vgt_db.exists():
print('hostname \t State')
db = json.loads(vgt_db.open().read())
for k, v in db['machines'].items():
if v['vagrantfile_path'] in shpyrd_paths:
print('{name} \t {state}'.format(name=v['name'], state=v['state']))
count+=1
print('Total {} machine(s)'.format(count))
def create_box(hostname, ram, cpus):
"""
This creates a box using the template
"""
dot_shipyard = Path(os.environ['HOME'], '.shipyard')
vagrant_wd = dot_shipyard.joinpath(hostname)
if vagrant_wd.exists():
print("Shipyard error: There's already a vm with that hostname")
exit(0)
vagrant_wd.mkdir(parents=True)
# Generate Vagrantfile
with vagrant_wd.joinpath('Vagrantfile').open(mode='w') as vfile:
vfile.write(vagrant_template.format(
hostname=hostname,
ram=ram,
cpus=cpus,
))
# Execute vagrant with the generated vagrantfile
subprocess.run(['vagrant','up'], cwd=vagrant_wd)
subprocess.run(['vagrant','provision'], cwd=vagrant_wd)
def destroy_box(name, all=False):
"""
Destroy a box, or all
"""
if all:
print('Destroy all boxes')
else:
print('Destroying box {} ...'.format(name))
def run_playbook(name, playbook):
"""
run a playbook against one of the boxes
"""
print('Running playbook {} for box {}'.format(playbook, name))
if __name__ == '__main__':
parser = argparse.ArgumentParser(
prog='shipyard',
description='This utility will create a new virtual machine using vagrant without writing a Vagrant file.'
description='This utility will create a new virtual machine using vagrant without writing a Vagrant file.',
)
parser.add_argument('--hostname', help='This is the hostname for the new box', required=True)
parser.add_argument('command', choices=['status', 'create', 'destroy', 'ssh', 'playbook'])
parser.add_argument('--hostname', help='This is the hostname for the new box',)
parser.add_argument('--ram', help='Hoy much RAM for this box (default is 512)', default=512)
parser.add_argument('--cpus', help='Hoy many CPUs for this box (default is 1)', default=1)
parser.add_argument('--verbose', '-v', help='Use this if you want to see all the output from vagrant', action='count')
parser.add_argument('--playbook', help='Path to the yml file', action='count')
args = parser.parse_args()
shipyard_dbdir = os.path.join(os.environ['HOME'], '.shipyard')
try:
os.mkdir(shipyard_dbdir)
except FileExistsError:
pass
vagrant_wd = os.path.join(shipyard_dbdir, args.hostname)
try:
os.mkdir(vagrant_wd)
except FileExistsError:
raise Exception("There's already a vm with that hostname")
# TODO: Check if the hostname is already taken
with open(os.path.join(vagrant_wd, 'Vagrantfile'), 'w') as vfile:
vfile.write(vagrant_template.format(
hostname=args.hostname,
ram=args.ram,
cpus=args.cpus,
))
subprocess.run(['vagrant','up'], cwd=vagrant_wd)
# Execute vagrant with the generated vagrantfile
if args.command == 'status':
print_status()
elif args.command == 'create':
if args.hostname:
create_box(args.hostname, args.ram, args.cpus)
else:
print("Shipyard error: the hostname is required to create a vm")
elif args.command == 'destroy':
destroy_box(args)
elif args.command == 'ssh':
invoke_shell()
elif args.command == 'playbook':
run_playbook()
else:
parser.print_help()
exit(100)
#Print report of all the new vms
# hostname
# ram
# cpus
# ip addres
# Other commands
# vagrant_db = os.path.join(
# os.environ.get('VAGRANT_HOME', os.environ['HOME']),
# '.vagrant.d', 'data', 'machine-index', 'index'
# )
# with open(vagrant_db) as vagrant_ix:
# for uuid in vagrant_ix['machines']:
# vm = vagrant_ix['machines']['uuid']
# vmdb.append([uuid, vm['name'], vm['state']])
# headers = ['UUID', 'Hostname', 'State']
# row_format ="{:>15}" * (len(headers) + 1)
# print(row_format.format("", *headers))
# for row in vmdb:
# print(row_format.format("", *row))
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment