Run redis-cli in a container from kubectl command


Scenario

You have a Kubernetes cluster running a Redis pod or replication controller. You need to run a redis-cli command in the container utilizing the kubectl command. The grep/awk commands below may not be needed depending on how you have Redis configured. In this scenario, the Redis container binds to the container IP only (not localhost), so we must grep for the host. There are plenty of other ways to accomplish the same thing but wanted to pass this along in case anyone else ran into a similar situation.


Command

# kubectl --namespace=default exec -it `kubectl --namespace=default get pod | grep mypodname | awk '{print $1}'` -- /usr/bin/redis-cli -h `kubectl --namespace=default get pod | grep mypodname | awk '{print $1}'` -p 6379 -a mysecretpassword info server

Output

# Server
redis_version:3.0.7
redis_git_sha1:00000000
redis_git_dirty:0
redis_build_id:33b0defdcca850ac
redis_mode:standalone
os:Linux 3.10.0-327.el7.x86_64 x86_64
arch_bits:64
multiplexing_api:epoll
gcc_version:4.8.5
process_id:9
run_id:f58cb95b25f32519266d78f30fb92f800cf3e22d
tcp_port:6379
uptime_in_seconds:99775
uptime_in_days:1
hz:10
lru_clock:2077829
config_file:/etc/redis.conf

Advanced Command

If you need an administrative task to purge keys in the Redis cache or something similar, use this command with a pipe to a xargs command:

kubectl --namespace=default exec -i `kubectl --namespace=default get pod | grep my-redis-pod | awk '{print $1}'` -- /usr/bin/redis-cli -h `kubectl --namespace=default get pod | grep my-redis-pod | awk '{print $1}'` -p 6379 -a mysecretpassword KEYS "mykey:*" | xargs kubectl --namespace=default exec -i `kubectl --namespace=default get pod | grep my-redis-pod | awk '{print $1}'` -- /usr/bin/redis-cli -h `kubectl --namespace=default get pod | grep my-redis-pod | awk '{print $1}'` -p 6379 -a mysecretpassword DEL

This command can come in handy to allow developers to purge the Redis cache from a Jenkins Continuous Integration workflow.