Skip to content

Instantly share code, notes, and snippets.

@mdaniel
Created January 29, 2016 22:26
Show Gist options
  • Save mdaniel/8cccc520620c51d8d204 to your computer and use it in GitHub Desktop.
Save mdaniel/8cccc520620c51d8d204 to your computer and use it in GitHub Desktop.
Mostly convert the output of "docker inspect" into a Kubernetes ReplicationController
#! /usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals
import json
import re
import sys
import yaml
def main(argv):
docker_fn = argv[1]
replica_count = 1
with open(docker_fn) as fh:
#: :type: list[dict[unicode,object]]
d_list = json.load(fh)
if len(d_list) != 1:
print('WARNING: I do not yet do anything intelligent with multiple Docker inspect entries',
file=sys.stderr)
d = d_list[0]
#: :type: unicode
container_name = d['Name']
name = re.sub(r'/?(.*)-\d+$', r'\1', container_name)
#: :type: dict[unicode, object|unicode|dict]
d_config = d['Config']
docker_image = d_config['Image']
version = re.sub(r'.*?:([0-9\.]+)$', r'\1', docker_image)
def env_to_dict(e_str):
#: :type: list[unicode]
parts = e_str.split('=')
assert len(parts) == 2, 'Unexpected ENV value: <<{0}>>'.format(e_str)
return {
"name": re.sub(r'-', '_', parts[0]),
"value": parts[1],
}
def ports_to_port(exposed_ports_dict):
""":type exposed_ports_dict: dict[unicode, dict]"""
#: :type: list[dict[unicode, object]]
results = []
#: :type: list[int]
the_ports = []
for k in exposed_ports_dict.keys():
parts = k.split('/')
assert len(parts) == 2, 'Unexpected "ExposedPorts" value <<{0}>>'.format(k)
the_ports.append(int(parts[0]))
the_ports.sort()
# we're counting on the "business" port being the lower of the two
for idx, p in enumerate(the_ports):
results.append({
"name": "http" if idx == 0 else "management",
"containerPort": p,
})
return results
container_ports = ports_to_port(d_config['ExposedPorts'])
rc = {
"apiVersion": "v1",
"kind": "ReplicationController",
"metadata": {
"name": name,
"labels": {
"app": name,
"version": version,
}
},
"spec": {
"replicas": replica_count,
"template": {
"metadata": {
"labels": {
"app": name,
"version": version,
},
},
"spec": {
"containers": [
{
"name": name,
"image": docker_image,
"env": [env_to_dict(it) for it in d_config['Env']],
"ports": container_ports,
"readinessProbe": {
"httpGet": {
"scheme": "HTTP",
"port": [it['containerPort'] for it in container_ports
if it['name'] == 'management'][0],
"path": "/health",
}
},
"resources": {
"limits": {
"memory": '1536Mi',
}
},
},
]
}
}
}
}
yaml.safe_dump(rc, sys.stdout)
if __name__ == '__main__':
main(sys.argv)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment