Coder Social home page Coder Social logo

ahmetb / kubectl-aliases Goto Github PK

View Code? Open in Web Editor NEW
3.3K 57.0 820.0 174 KB

Programmatically generated handy kubectl aliases.

Home Page: https://ahmet.im/blog/kubectl-aliases/

License: Apache License 2.0

Python 10.08% Shell 89.92%
kubernetes kubectl

kubectl-aliases's Introduction

kubectl-aliases

This repository contains a script to generate hundreds of convenient shell aliases for kubectl, so you no longer need to spell out every single command and --flag over and over again.

An example shell alias created from command/flags permutation looks like:

alias ksysgdepwslowidel='kubectl --namespace=kube-system get deployment --watch --show-labels -o=wide -l'

Confused? Read on.

Examples

Some of the 800 generated aliases are:

alias k='kubectl'
alias kg='kubectl get'
alias kgpo='kubectl get pod'

alias ksysgpo='kubectl --namespace=kube-system get pod'

alias krm='kubectl delete'
alias krmf='kubectl delete -f'
alias krming='kubectl delete ingress'
alias krmingl='kubectl delete ingress -l'
alias krmingall='kubectl delete ingress --all-namespaces'

alias kgsvcoyaml='kubectl get service -o=yaml'
alias kgsvcwn='kubectl get service --watch --namespace'
alias kgsvcslwn='kubectl get service --show-labels --watch --namespace'

alias kgwf='kubectl get --watch -f'
...

See the full list.

Installation

You can directly download the .kubectl_aliases file for bash/zsh or the .kubectl_aliases.fish file for fish and save it to your $HOME directory.

Bash/Zsh

Add the following to your .bashrc/.zshrc file:

[ -f ~/.kubectl_aliases ] && source ~/.kubectl_aliases

Recommendation: If you want to use GNU watch command instead of kubectl [...] --watch, run it like this:

[ -f ~/.kubectl_aliases ] && source \
   <(cat ~/.kubectl_aliases | sed -r 's/(kubectl.*) --watch/watch \1/g')

Print the full command before running it: Add this to your .bashrc or .zshrc file:

function kubectl() { echo "+ kubectl $@">&2; command kubectl $@; }

Fish

Add the following to your ~/.config/fish/config.fish file:

test -f ~/.kubectl_aliases.fish && source ~/.kubectl_aliases.fish

This actually adds the more powerful fish abbreviations instead of aliases, so that pressing space shows the full command before execution.

Recommendation: If you want to use GNU watch command instead of kubectl [...] --watch, run it like this:

test -f ~/.kubectl_aliases.fish && source \
     (cat ~/.kubectl_aliases.fish | sed -r 's/(kubectl.*) --watch/watch \1/g' | psub)

Syntax explanation

  • k=kubectl
    • sys=--namespace kube-system
  • commands:
    • g=get
    • d=describe
    • rm=delete
    • a:apply -f
    • ak:apply -k
    • k:kustomize
    • ex: exec -i -t
    • lo: logs -f
  • resources:
    • po=pod, dep=deployment, ing=ingress, svc=service, cm=configmap, sec=secret, ns=namespace, no=node ⚠️ Please do not suggest new resources here, instead fork the project.
  • flags:
    • output format: oyaml, ojson, owide
    • all: --all or --all-namespaces depending on the command
    • sl: --show-labels
    • w=-w/--watch
  • value flags (should be at the end):
    • n=-n/--namespace
    • f=-f/--filename
    • l=-l/--selector

Running the script

The script has only one optional argument, the shell to which the aliases will be generated. If not given, it assumes bash. Ex:

# Generate aliases for bash/zsh
python generate_aliases.py > .kubectl_aliases

# Generate abbr for fish
python generate_aliases.py fish > .kubectl_aliases.fish

FAQ

  • Doesn't this slow down my shell start up? Sourcing the file that contains ~500 aliases takes about 30-45 milliseconds in my shell (zsh). I don't think it's a big deal for me. Measure it with echo $(($(date +%s%N)/1000000)) command yourself in your .bashrc/.zshrc.

  • Can I add more Kubernetes resource types to this? Please consider forking this repo and adding the resource types you want. Not all resource types are used by everyone, and adding more resource types slows down shell initialization see above).

  • Where can I find PowerShell aliases for kubectl? There’s a fork of this here.

Authors


This is not an official Google project.

kubectl-aliases's People

Contributors

achton avatar ahmetb avatar freele avatar henricook avatar kamina-zzz avatar lfrobeen avatar masgustavos avatar ustun avatar xunzhuo avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

kubectl-aliases's Issues

Printing the command line breaks ps-1

Not an issue per se but perhaps theres' an easy fix
Instead of

(⎈ |eu-1:default)➜  ~

You'll see

(⎈ |+ kubectl config current-context
eu-1:+ kubectl config view --minify --output jsonpath={..namespace})➜  ~

Support for custom resources

This is great. Thank you for sharing! Any ideas about adding support for custom resources?

Something along the lines of:

kubectl get crd -o json | jq '[.items[].spec.names] | map([.kind,.singular,.plural, ["g","d","rm"], null])'

would get pretty close to the shape already being used:

res=[
('po','pods', ['g','d','rm'], None),
('dep','deployment', ['g','d','rm'], None),
('svc','service', ['g','d','rm'], None),
('ing','ingress', ['g','d','rm'], None),
('cm','configmap', ['g','d','rm'], None),
('sec','secret', ['g','d','rm'], None),
('no','nodes',['g','d'], ['sys']),
('ns','namespaces',['g','d','rm'], ['sys']),
]

However, seems this would be tricky without an abbreviation field defined in the spec.names.. I'm happy regenerating locally after manually adding my own abbreviations, but maybe you have some ideas about how to support this more generally?

Support Openshift OC client?

Would it be possible to update this project to support oc as well?
Or have you heard of a dedicated project for this?

Thanks.

Add --show-labels for nodes, configmaps and other resources.

Show labels as i see is for pods and deployment only.

('sl', '--show-labels', ['g'], ['oyaml', 'ojson']
         + diff(res_types, ['po', 'dep'])),

I'm able to write: kgsl nodes but not kgnosl or kgslno same for configmaps and other k8s objects.

If there any reason for us to not add them other resources, can we add them up too

Add aliases for resource 'job'

Our team works with k8s jobs a lot. It would be nice to have a set of aliases for the resource 'job' similar to 'pod'.
For example,
alias kgjb='kubectl get jobs'
or
alias kgj='kubectl get jobs'

If you don't mind, I can add them and open a PR.

Why this script try to connect to server when startup?

I using this script and I recognize this just using alias command but why I got message look like this script try to connect to the server?

I using zsh and here my ~/.zshrc

[ -f ~/.kubectl_aliases ] && source ~/.kubectl_aliases
function kubectl() { echo "+ kubectl $@"; command kubectl $@; }
if [ /usr/local/bin/kubectl ]; then source <(kubectl completion zsh); fi

When I try to start new windows of shell I got these message.

Last login: Tue Jul 30 21:56:30 on ttys000
Unable to connect to the server: dial tcp {serverIP}:6443: connect: network is unreachable
/dev/fd/12:1: command not found: +

and It's so slow to start new windows (I doubt it's because try to connect the server and got timeout).

function kubectl() {...} doesn't provide any autocomplete of the kubectl command

Usually, using the kubectl command, there are autocompletes in a terminal (well, in my zsh terminal there is autocomplete).

I've noticed that when I added this line to my .zshrc:

function kubectl() { echo "+ kubectl $@">&2; command kubectl $@; }

I could not use any autocomplete feature of the kubectl command anymore in my terminal.

Add commands to switch cluster/namespace context

Handy commands I would like to have in the aliases are:

  • Switch current namespace kcns

kubectl config set-context --current --namespace=NAMESPACE

  • Switch current cluster context kcc

k config use-context CONTEXT

Consider adding "kgpv" and "kgpvc"

Would be nice to addkgpv and kgpvc for kubectl get pv and kubectl get pvcrespectively.

and maybe associated aliases for describe commands for pv and pvc.

Happy to send in a patch to include these

kubectl exec [POD] [COMMAND] is DEPRECATED

When running a command like kexn test varnish-529679cb57-mjn62 bash it translates to kubectl exec -i -t --namespace test varnish-529679cb57-mjn62 bash and kubectl returns a deprecation warning:

kubectl exec [POD] [COMMAND] is DEPRECATED and will be removed in a future version. Use kubectl kubectl exec [POD] -- [COMMAND] instead.

The problem is that --namespace is a positional argument, but to fix this issue it will need to not be last, but come before the --. See https://kubernetes.io/docs/reference/generated/kubectl/kubectl-commands#exec

Watch examples in Readme.md are wrong

The README has the following examples:

alias kgsvcwn='watch kubectl get service --namespace'
alias kgsvcslwn='watch kubectl get service --show-labels --namespace'
alias kgwf='watch kubectl get -f'

However, in actuality the watch commands is:

$ type kgwf
kgwf is aliased to `kubectl get --watch --recursive -f'

Support configuration to handle more use-cases while not sacrificing the performance

Since the concern with adding more and more options here is the amount of aliases generated and time required for loading them, I think it would be great if such aliases are still in the code, but enabled by default, so user can simply disable things, which he doesn't need.

The configuration would be great, since then user don't have to figure out which parameters are not compatible with what options etc, but simply enables and disables certain features.

As an example, I almost never use JSON output, so I stripped it out from the code, that reduced generation time from 30 seconds to just 5. Also if there are resources, which you never use, user could simple disable them as well.

proposal: add alias of kubectl extension

Can we add some alias of kubectl extension like:
kr - kubectl krew
kri - kubectl krew install
krup - kubectl krew update
krug - kubectl krew upgrade
krrm - kubectl krew uninstall
kns - kubectl ns
kcx - kubectl ctx

Supporting Fish Shell

Hi there @ahmetb! Thanks for this project. I've been using kubectx and kubens for a while now and when I looked up for k8s aliases, found you once again =)

I'm opening this issue to make reference to a contribution, where I propose supporting fish shell on the python script, as well as the addition of a .kubectl_aliases.fish file to those who want it.

Single quotes from labels removed

I was able to reproduce this on Mac only. When I provide a label expression in a single quote, they are truncated and hence cause the error in command:

$ kgdep -l 'svc in (nats-streaming)'
+ kubectl get deployment -l svc in (nats-streaming)
error: name cannot be provided when a selector is specified

$ kgdepl 'svc in (nats-streaming)'
+ kubectl get deployment -l svc in (nats-streaming)
error: name cannot be provided when a selector is specified

Fish abbreviations

Would be good to have better fish integration.
However this script can do it:

#!/usr/bin/env ruby

lines = File.read('.kubectl_aliases').split("\n")

script = "#!/usr/local/bin/fish\n\n"

lines.each do |line|
  abbr = line.match(/alias (\w+)/)[1]
  cmd = line.match(/\='(.+)'/)[1]
  script << "abbr -a #{abbr} #{cmd};\n"
end

File.write('/tmp/fish-k8s-abbrs', script)

`chmod +x /tmp/fish-k8s-abbrs`
`fish -c /tmp/fish-k8s-abbrs`
`rm /tmp/fish-k8s-abbrs`

Minor issue while running the python script

Hi Ahmed,

When a user tries running the script (minus cloning the repo) it apparently seeks license_header. Would be good to add a small note that the user can just create a base license_header file as the script looks for that in the respective path.

Traceback (most recent call last):
File "/Users/amit/generate_aliases.py", line 194, in
main()
File "/Users/amit/generate_aliases.py", line 108, in main
with open(header_path, 'r') as f:
FileNotFoundError: [Errno 2] No such file or directory: '/Users/amit/license_header'

bash-3.2$ touch license_header

helps mitigate this minor issue.

Thanks!
-Amit

Problem using the aliases with the `watch` command

Hi I recently started using your awesome aliases and I really like using them. 🥂
I am facing problem using it with the watch command.

I run Ubuntu18.04

$ watch --version
watch from procps-ng 3.3.12

This works as expected.

$ watch kubectl get pods
# works as expected

This doesn't.

$ watch kgpo
sh: 1: kgpo: not found

I am not sure if you and others also face this issue.
If you have a work-around please share below. 🙇‍♂️

`function kubectl()` in README doesn't handle quoted arguments correctly

I posted on Stack Overflow about a difficult-to-diagnose error when working with kubectl here: https://stackoverflow.com/questions/54948471/jsonpath-range-not-working-when-using-kubectl

I traced the error down to having followed this repo's suggestion to overwrite kubectl with a function. It seems the function strips quotes from arguments when in some cases they are necessary.

Instead of

function kubectl() { echo "+ kubectl $@"; command kubectl $@; }

how about this?

function kubectl() { echo "+ kubectl $@"; command kubectl "$@"; }

Add Service Accounts

Please add ServiceAccounts to the resource types, my suggestion would be to have 'sa' be the shortcut.

Readme is wrong

[ -f ~/.kubectl_aliases ] && source \
   <(cat ~/.kubectl_aliases | sed -r 's/(kubectl.*) --watch/watch\1/g')

watch section should contain whitespace:

[ -f ~/.kubectl_aliases ] && source \
   <(cat ~/.kubectl_aliases | sed -r 's/(kubectl.*) --watch/watch \1/g')

rename dep to d ?

Hi, thanks for sharing super useful aliases!

I have a question.
Is there any concern about keeping long name dep ? To me it's a bit too long for an alias.
Doesn't kgd makes sense to you?

Support for --dry-run=client

Just did my CKAD exam and one of the useful tips we employed in this context was to dry run the commands before executing them.
This is currently not supported by this project right.
Would it be a good idea for me to add support for it?

--dry-run=client

This is a flag (not a value flag) so adding the the word "dry" would do it I think.

function kubectl() does not work with jsonpath

(Firstly, credit to the people on the Kubernetes slack who helped me with this!)

So I have been trying to craft a query with jsonpath to find all pods with a certain annotation.

kubectl get pod --all-namespaces -o jsonpath='{range .items[?(@.metadata.annotations.prometheus\.io/scrape=="true")]}{.metadata.name}{"\n"}{end}'

the following line prevents exectution of the above as it appears to strips out the quotes in my command
function kubectl() { echo "+ kubectl $@">&2; command kubectl $@; }

changing the function to the following does work - adding quotes around the shell variables (although what it echoes still removes the quotes).
function kubectl() { echo "+ kubectl $@">&2; command kubectl "$@"; }

Completion not working with Bash

With zsh, programmable completion works with the aliases as it would with the full commands.

For example:

# Displays all sub-commands of kubectl
k [tab]
# Displays all resource objects
kg [tab]
# Displays all pods
kgpo [tab]

However, this doesn't work with Bash. If you do the same in Bash, there is no programmable completion invoked at all for the aliases.

I use Bash 5.0 on macOS with bash-completion 2.8 installed.

Do you have any ideas on this? Is this the normal behaviour of Bash, or can it be fixed somehow?

Autocompletion does not work

The kubectl auto completion does not work with aliases

On tab it shows the files in current directory instead of kubectl completion

$ kgpon 
.git/           .gitattributes  .gitignore      ATP/            Jenkins/        Jenkins_CI/     docs/           nukeConfig/     scripts/        

No aliases for `kubectl logs -p <podName>`

I often use this command to get logs of the previous container in a pod (e.g. in the event of pod crash) - but it's not in the aliases list, could something be added?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.