Skip to content

Instantly share code, notes, and snippets.

@filipenf
Created September 10, 2016 15:05
Show Gist options
  • Save filipenf/9ce4b94a06b2d6eb99d05f293e69dbe1 to your computer and use it in GitHub Desktop.
Save filipenf/9ce4b94a06b2d6eb99d05f293e69dbe1 to your computer and use it in GitHub Desktop.
Template(jinja) generator using docker container list as input
#!/usr/bin/env python
import argh, os, sys
from docker import Client
from os.path import dirname, basename
def get_containers(cli):
container_ids = [ c['Id'] for c in cli.containers() ]
containers = [ cli.inspect_container(cid) for cid in container_ids ]
for container in containers:
env_list = container['Config']['Env']
env_dict = {}
for e in env_list:
(k,v) = e.split('=')
env_dict[k] = v
container['Config']['Env'] = env_dict
return containers
@argh.arg('-e', '--extra-var', action='append', help='Extra vars for the template rendering (allows multiple)')
@argh.arg('-t', '--template-file', help='Path to the template file')
@argh.arg('-u', '--base-url', default='unix://var/run/docker.sock', help='Base url for docker socket')
@argh.expects_obj
def render_template(args):
from jinja2 import Environment, FileSystemLoader
cli = Client(base_url=args.base_url)
extra = {}
for ev in args.extra_var:
(k,v) = ev.split('=')
extra[k] = v
jenv = Environment(loader=FileSystemLoader(dirname(args.template_file)))
print jenv.get_template(basename(args.template_file)).render(containers=get_containers(cli), **extra)
@argh.arg('-u', '--base-url', default='unix://var/run/docker.sock', help='Base url for docker socket')
@argh.arg('-o', '--output', help='Destination of yaml file')
@argh.expects_obj
def dump_yml(args):
import yaml
cli = Client(base_url=args.base_url)
containers = get_containers(cli)
outfile = open(args.output, 'w') if args.output else sys.stdout
yaml.safe_dump({ 'containers': containers }, outfile, default_flow_style=False)
def main():
parser = argh.ArghParser()
parser.add_commands([render_template, dump_yml])
parser.dispatch()
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment