Last active
August 10, 2016 19:25
-
-
Save corpix/5498b5f00a9f520cba9d8441d291b033 to your computer and use it in GitHub Desktop.
Tiny script to brew your dockerfile with ease
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import argparse | |
import json | |
import os | |
from os import path | |
def get_file_content(path): | |
with open(path, "r") as file: | |
return file.read() | |
def set_file_content(path, content): | |
with open(path, "w") as file: | |
return file.write(content) | |
def get_config(config_path): | |
return json.loads( | |
get_file_content(config_path) | |
) | |
# because python std lib sucks a whole bunch! | |
def resolve_path(target, base): | |
if path.isabs(target): | |
return target | |
return path.join( | |
base, | |
target | |
) | |
def apply_definition(directory, name, template, definition): | |
target_directory = path.join( | |
directory, | |
path.normpath(name) | |
) | |
os.makedirs( | |
target_directory, | |
exist_ok=True | |
) | |
set_file_content( | |
path.join(target_directory, "Dockerfile"), | |
template.format(**definition) | |
) | |
def brew(args): | |
directory = path.abspath(args["directory"]) | |
configuration = get_config( | |
resolve_path( | |
args["configuration"], | |
directory | |
) | |
) | |
template = get_file_content( | |
resolve_path( | |
args["template"], | |
directory | |
) | |
) | |
for name, definition in configuration.items(): | |
apply_definition(directory, name, template, definition) | |
if __name__ == "__main__": | |
p = argparse.ArgumentParser( | |
description="Prepare dockerfile's from templates" | |
) | |
p.add_argument( | |
"directory", | |
help="Root directory for container dockerfile's to be brewed", | |
type=str | |
) | |
p.add_argument( | |
"--template", | |
help="Template file path to use for substitution when brewing the container Dockerfile. " + | |
"If relative path is given then it will be resolved relatively to root directory(see directory parameter).", | |
type=str, | |
default="Dockerfile.template" | |
) | |
p.add_argument( | |
"--configuration", | |
help="Brew configuration which contains a dictionary " + | |
"{name: {...variables...}} for substitution in the template. " + | |
"If relative path is given then it will be resolved relatively to root directory, " + | |
"just like template argument.", | |
type=str, | |
default="dockerfile-brew.json" | |
) | |
brew(p.parse_args().__dict__) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment