Skip to content

Instantly share code, notes, and snippets.

@caruccio
Created January 3, 2020 15:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save caruccio/8e163e5cb8ff1432ff7091441e32022c to your computer and use it in GitHub Desktop.
Save caruccio/8e163e5cb8ff1432ff7091441e32022c to your computer and use it in GitHub Desktop.
Kubectl Generator - on-the-fly kubectl shortcuts
#!/usr/bin/python
from __future__ import print_function
import sys
def usage(argv):
print('Usage: %s [commands][resources][options][parameters]' % argv[0], file=sys.stderr)
print('\nCommands:', file=sys.stderr)
for s, l in commands:
print(' %s (%s)' % (s, l), file=sys.stderr)
print('\nResources:', file=sys.stderr)
for s, l in resources:
print(' %s (%s)' % (s, l), file=sys.stderr)
print('\nOptions:', file=sys.stderr)
for s, l in options:
print(' %s (%s)' % (s, l), file=sys.stderr)
print('\nParameters:', file=sys.stderr)
for s, l in parameters:
print(' %s (%s<VALUE>)' % (s, l), file=sys.stderr)
print('\nBash function')
print(' echo \'function kg() { eval $(kubectlgen "$@"); }\' >> ~/.bashrc')
commands = (
('a', 'apply'),
('c', 'create'),
('g', 'get'),
('e', 'edit'),
('ex', 'exec -it'),
('exp', 'explain'),
('lo', 'logs -f'),
('la', 'label'),
('an', 'annotate'),
('del', 'delete'),
('de', 'describe'),
('sc', 'scale'),
('set', 'set'),
)
resources = (
('po', 'pod'),
('dep', 'deploy'),
('ns', 'namespace'),
('svc', 'service'),
('sa', 'serviceaccount'),
('psp', 'podsecuritypolice'),
('dc', 'deploymentconfig'),
('bc', 'buildconfig'),
('is', 'imagestream'),
('scc', 'securitycontextconstraints'),
)
options = (
('oy', '-oyaml'),
('oj', '-ojson'),
('ow', '-owide'),
('w', '--watch'),
('all', '--all'),
('an', '--all-namespaces'),
)
parameters = (
('n', '--namespace='),
('ot', '-otemplate='),
('rep', '--replicas='),
)
def get_token(arg, values):
for short_value, long_value in values:
if arg.startswith(short_value):
return len(short_value), long_value
return 0, None
def main(argv):
c, r, o, p = None, None, None, None
need_val = False
for arg in argv:
if need_val:
p += arg
need_val = False
continue
i = 0
if not c and i < len(arg):
n, c = get_token(arg[i:], commands)
i += n
if not r and i < len(arg):
n, r = get_token(arg[i:], resources)
i += n
if not o and i < len(arg):
n, o = get_token(arg[i:], options)
i += n
if not p and i < len(arg):
n, p = get_token(arg[i:], parameters)
i += n
need_val = True
continue
if i < len(arg) and not need_val:
print('Invalid value:', ''.join(arg[i:]), file=sys.stderr)
sys.exit(1)
res = [c, r, o, p]
cmdline = ' '.join(filter(bool, res))
print('echo + kubectl', cmdline, '>&2 && ')
print('kubectl', cmdline)
if len(sys.argv) > 1:
main(sys.argv[1:])
else:
usage(sys.argv)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment