Repository: yokawasa/kubectl-plugin-ssh-jump Branch: master Commit: b6472ca90666 Files: 6 Total size: 35.8 KB Directory structure: gitextract_r71_3ox3/ ├── .gitignore ├── LICENSE ├── README.md ├── VERSION ├── kubectl-ssh-jump └── ssh-jump.yaml ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ /t/* /*/t/* ================================================ FILE: LICENSE ================================================ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ FILE: README.md ================================================ # kubectl-plugin-ssh-jump [![kubectl plugin](https://img.shields.io/badge/kubectl-plugin-blue.svg)](https://github.com/topics/kubectl-plugin) A kubectl plugin to access Kubernetes nodes or remote services using a SSH jump Pod A `jump host` Pod is an intermediary Pod or an SSH gateway to Kubernetes node machines, through which a connection can be made to the node machines or remote services. Here is an scenario where you want to connect to Kubernetes nodes or remote services, but you have to go through a jump host Pod, because of firewalling, access privileges. etc. There is a number of valid reasons why the jump hosts are needed... **CASE 1: SSH into Kubernetes nodes via SSH jump Pod** ![](assets/ssh-jump-node-ssh-login.png) **CASE 2: Connect to remote serivces via SSH local port forwarding**. SSH local port forwarding allows to forward the traffic form local machine to SSH jump then SSH jump will forward the traffic to remote services (host:port)s. ![](assets/ssh-jump-ssh-tunnel.png) > [NOTE] > - Kubectl versions >= `1.12.0` (Preferred) > - As of Kubernetes 1.12, kubectl now allows adding external executables as subcommands. For more detail, see [Extend kubectl with plugins](https://kubernetes.io/docs/tasks/extend-kubectl/kubectl-plugins/) > - You can run the plugin with `kubectl ssh-jump ...` > - Kubectl versions < `1.12.0` > - You still can run the plugin directly with `kubectl-ssh-jump ...` **Table of Content** - [kubectl-plugin-ssh-jump](#kubectl-plugin-ssh-jump) - [Pre-requistes](#pre-requistes) - [Installation](#installation) - [Install through krew](#install-through-krew) - [Manual Installation](#manual-installation) - [How to use](#how-to-use) - [Usage](#usage) - [Option parameters Cache](#option-parameters-cache) - [SSH Agent ssh-agent](#ssh-agent-ssh-agent) - [Customize SSH jump pod](#customize-ssh-jump-pod) - [Examples](#examples) - [CASE 1: SSH into Kubernetes nodes via SSH jump Pod](#case-1-ssh-into-kubernetes-nodes-via-ssh-jump-pod) - [-1 - You have private & public SSH key on your side](#-1---you-have-private--public-ssh-key-on-your-side) - [-2 - You have .pem file but you don't have public key on your side](#-2---you-have-pem-file-but-you-dont-have-public-key-on-your-side) - [CASE 2: Access remote serivces via SSH local port forwarding](#case-2-access-remote-serivces-via-ssh-local-port-forwarding) - [-1 - Configuring SSH local port forwarding with --args or -a option](#-1---configuring-ssh-local-port-forwarding-with---args-or--a-option) - [Useful Links](#useful-links) - [Contributing](#contributing) ## Pre-requistes This plugin needs the following programs: * ssh(1) * ssh-agent(1) * ssh-keygen(1) ## Installation ### Install through krew This is a way to install kubectl-ssh-jump through [krew](https://krew.sigs.k8s.io/). After installing krew by following [this](https://krew.sigs.k8s.io/docs/user-guide/setup/install/), you can install kubectl-ssh-jump like this: ```sh $ kubectl krew install ssh-jump ``` Expected output would be like this: ``` Updated the local copy of plugin index. Installing plugin: ssh-jump CAVEATS: \ | This plugin needs the following programs: | * ssh(1) | * ssh-agent(1) | | Please follow the documentation: https://github.com/yokawasa/kubectl-plugin-ssh-jump / Installed plugin: ssh-jump ``` Once it's installed, run: ```sh $ kubectl plugin list The following kubectl-compatible plugins are available: /Users/yoichi.kawasaki/.krew/bin/kubectl-krew /Users/yoichi.kawasaki/.krew/bin/kubectl-ssh_jump $ kubectl ssh-jump ``` ### Manual Installation Install the plugin by copying the script in the $PATH of your shell. ```sh # Get source $ git clone https://github.com/yokawasa/kubectl-plugin-ssh-jump.git $ cd kubectl-plugin-ssh-jump $ chmod +x kubectl-ssh-jump # Add kubeclt-ssh-jump to the install path. $ sudo cp -p kubectl-ssh-jump /usr/local/bin ``` Once in the $PATH, run: ```sh $ kubectl plugin list The following kubectl-compatible plugins are available: /usr/local/bin/kubectl-ssh-jump $ kubectl ssh-jump ``` ## How to use ### Usage ```TXT Usage: kubectl ssh-jump [options] Options: Destination node name or IP address dest_node must start from the following letters: ASCII letters 'a' through 'z' or 'A' through 'Z', the digits '0' through '9', or hyphen ('-'). NOTE: Setting dest_node as 'jumphost' allows to ssh into SSH jump Pod as 'root' user -u, --user SSH User name -i, --identity Identity key file, or PEM(Privacy Enhanced Mail) -p, --pubkey Public key file -P, --port SSH port for target node SSH server Defaults to 22 -a, --args Args to exec in ssh session -n, --namespace Namespace for jump pod --context Kubernetes context --pod-template Path to custom sshjump pod definition -l, --labels =[,...] Find a pre-existing sshjump pod using labels --skip-agent Skip automatically starting SSH agent and adding SSH Identity key into the agent before SSH login (=> You need to manage SSH agent by yourself) --cleanup-agent Clearning up SSH agent at the end The agent is NOT cleaned up in case that --skip-agent option is given --cleanup-jump Clearning up sshjump pod at the end Defaults to skip cleaning up sshjump pod -v, --verbose Run ssh in verbose mode (=ssh -vvv) -h, --help Show this message Example: Scenario1 - You have private & public SSH key on your side $ kubectl ssh-jump -u myuser -i ~/.ssh/id_rsa -p ~/.ssh/id_rsa.pub hostname Scenario2 - You have .pem file but you don't have public key on your side $ kubectl ssh-jump -u ec2-user -i ~/.ssh/mykey.pem hostname ``` #### Option parameters Cache `username`, `identity`, `pubkey`, `port` options are cached, therefore you can omit these options afterward. The options are stored in a file named `$HOME/.kube/kubectlssh/options` ```sh $ cat $HOME/.kube/kubectlssh/options sshuser=myuser identity=/Users/yoichi.kawasaki/.ssh/id_rsa_k8s pubkey=/Users/yoichi.kawasaki/.ssh/id_rsa_k8s.pub port=22 ``` #### SSH Agent (ssh-agent) The plugin automatically check if there are any `ssh-agents` started running by the plugin, and starts `ssh-agent`if it doesn't find any `ssh-agent` running and adds SSH Identity key into the agent before SSH login. If the command find that ssh-agent is already running, it doesn't start a new agent, and re-use the agent. Add `--cleanup-agent` option if you want to kill the created agent at the end of command. In addtion, add `--skip-agent` option if you want to skip automatic starting `ssh-agent`. This is actually a case where you already have ssh-agent managed or you want to manually start the agent. ### Customize SSH jump pod You can customize the sshjump pod created by `kubectl ssh-jump` by setting the `--pod-template` flag to the path to a pod template on disk. However, customized sshjump pods must be named `sshjump` and run in the current namespace or `kubectl ssh-jump` won't be able to find them without the required flags. If you change the pod name, you must give the pod a unique set of labels and provide them on the command line by setting the `--labels` flag. You can also specify the namespace and context used by `kubectl ssh-jump` by setting the `--namespace` and `--context` flags respectively. ### Examples Show all node list. Simply executing `kubectl ssh-jump` gives you the list of destination nodes as well as command usage ```sh $ kubectl ssh-jump Usage: kubectl ssh-jump [options] ...snip... List of destination node... Hostname Internal-IP aks-nodepool1-18558189-0 10.240.0.4 ...snip... ``` #### CASE 1: SSH into Kubernetes nodes via SSH jump Pod ##### 1-1 - You have private & public SSH key on your side Suppose you have private & public SSH key on your side and you want to SSH to a node named `aks-nodepool1-18558189-0`, execute the plugin with options like this: - usernaem: `azureuser` - identity:`~/.ssh/id_rsa_k8s` - pubkey:`~/.ssh/id_rsa_k8s.pub`) ```sh $ kubectl ssh-jump aks-nodepool1-18558189-0 \ -u azureuser -i ~/.ssh/id_rsa_k8s -p ~/.ssh/id_rsa_k8s.pub ``` > [NOTE] you can try SSH into a node using node IP address (`Internal-IP`) instead of `Hostname` As explained in usage secion, `username`, `identity`, `pubkey` options will be cached, therefore you can omit these options afterward. ```sh $ kubectl ssh-jump aks-nodepool1-18558189-0 ``` You can pass the commands to run in the destination node like this (Suppose that `username`, `identity`, `pubkey` options are cached): ```sh echo "uname -a" | kubectl ssh-jump aks-nodepool1-18558189-0 (Output) Linux aks-nodepool1-18558189-0 4.15.0-1035-azure #36~16.04.1-Ubuntu SMP Fri Nov 30 15:25:49 UTC 2018 x86_64 x86_64 x86_64 GNU/Linux ``` You can pass commands with `--args` or `-a` option ``` sh kubectl ssh-jump aks-nodepool1-18558189-0 --args "uname -a" (Output) Linux aks-nodepool1-18558189-0 4.15.0-1035-azure #36~16.04.1-Ubuntu SMP Fri Nov 30 15:25:49 UTC 2018 x86_64 x86_64 x86_64 GNU/Linux ``` You can clean up sshjump pod at the end of the command with `--cleanup-jump` option, otherwise, the sshjump pod stay running by default. ```sh $ kubectl ssh-jump aks-nodepool1-18558189-0 \ -u azureuser -i ~/.ssh/id_rsa_k8s -p ~/.ssh/id_rsa_k8s.pub \ --cleanup-jump ``` You can clean up ssh-agent at the end of the command with `--cleanup-agent` option, otherwise, the ssh-agent process stay running once it's started. ```sh $ kubectl ssh-jump aks-nodepool1-18558189-0 \ -u azureuser -i ~/.ssh/id_rsa_k8s -p ~/.ssh/id_rsa_k8s.pub \ --cleanup-agent ``` You can skip starting `ssh-agent` by giving `--skip-agent`. This is actually a case where you already have ssh-agent managed. Or you can start new ssh-agent and add an identity key to the ssh-agent like this: ```sh # Start ssh-agent manually $ eval `ssh-agent` # Add an arbitrary private key, give the path of the key file as an argument to ssh-add $ ssh-add ~/.ssh/id_rsa_k8s # Then, run the plugin with --skip-agent $ kubectl ssh-jump aks-nodepool1-18558189-0 \ -u azureuser -i ~/.ssh/id_rsa_k8s -p ~/.ssh/id_rsa_k8s.pub \ --skip-agent # At the end, run this if you want to kill the current agent $ ssh-agent -k ``` ##### 1-2 - You have .pem file but you don't have public key on your side From v0.4.0, the plugin supports PEM (Privacy Enhanced Mail) scenario where you create key-pair but you only have .pem / private key (downloaded from AWS, for example) and you don't have the public key on your side. Suppose you've already downloaded a pem file and you want to ssh to your EKS worker node (EC2) named `ip-10-173-62-96.ap-northeast-1.compute.internal` using the pem, execute the plugin with options like this: - usernaem: `ec2-user` - identity: `~/.ssh/mykey.pem` ```sh $ kubectl ssh-jump -u ec2-user -i ~/.ssh/mykey.pem ip-10-173-62-96.ap-northeast-1.compute.internal ``` #### CASE 2: Access remote serivces via SSH local port forwarding SSH local port forwarding allows to forward the traffic form local machine to SSH jump then SSH jump will forward the traffic to remote services (host:port)s. ##### 2-1 - Configuring SSH local port forwarding with --args or -a option Suppose you have private & public SSH key on your side and you want to access a remote server (IP: `10.100.10.8`) using `3389`/TCP port which is not accessible directly but accessible via SSH jump, execute the plugin with options like this, at first: - identity:`~/.ssh/id_rsa_k8s` - pubkey:`~/.ssh/id_rsa_k8s.pub`) The command below allows to forward the traffic form local machine (`localhost:13200`) to SSH jump then SSH jump will forward the traffic to the remote server (`10.100.10.8:3389`). ```sh $ kubectl ssh-jump sshjump \ -i ~/.ssh/id_rsa_k8s -p ~/.ssh/id_rsa_k8s.pub \ -a "-L 13200:10.100.10.8:3389" ``` > - `sshjump` is the hostname for SSH jump Pod > - The value for `--arg` or `-a` should be in this format: "-L local_port:remote_address:remote_port" Now, you're ready to access to the remote server at port 13200 at local machine. ## Useful Links - [Extend kubectl with plugins](https://kubernetes.io/docs/tasks/extend-kubectl/kubectl-plugins/) - [Write your own kubectl subcommands](https://ahmet.im/blog/kubectl-plugins/) - [SSH-AGENT - SINGLE SIGN-ON USING SSH](https://www.ssh.com/ssh/agent) ## Contributing Bug reports and pull requests are welcome on GitHub at https://github.com/yokawasa/kubectl-plugin-ssh-jump ================================================ FILE: VERSION ================================================ 0.7.3 ================================================ FILE: kubectl-ssh-jump ================================================ #!/usr/bin/env bash # vim: sw=2: # # A kubectl plugin to ssh into Kubernetes nodes using a SSH jump host Pod # [[ -n $DEBUG ]] && set -x -e PLUGIN_DIR="${HOME}/.kube/kubectlssh" PLUGIN_SSH_OPTIONS_FILE="${PLUGIN_DIR}/options" MAX_POD_CREATION_TIME=10 # unit: second SSH_AGENT_ENV_FILE="${PLUGIN_DIR}/sshagent-env" SSH_AGENT_PID_FILE="${PLUGIN_DIR}/sshagent-pid" help(){ echo "Usage: " echo " kubectl ssh-jump [options]" echo "" options } options(){ cat <<"EOF" Options: Destination node name or IP address dest_node must start from the following letters: ASCII letters 'a' through 'z' or 'A' through 'Z', the digits '0' through '9', or hyphen ('-'). NOTE: Setting dest_node as 'jumphost' allows to ssh into SSH jump Pod as 'root' user -u, --user SSH User name -i, --identity Identity key file, or PEM(Privacy Enhanced Mail) -p, --pubkey Public key file -P, --port SSH port for target node SSH server Defaults to 22 -a, --args Args to exec in ssh session -n, --namespace Namespace for jump pod --context Kubernetes context --pod-template Path to custom sshjump pod definition -l, --labels =[,...] Find a pre-existing sshjump pod using labels --skip-agent Skip automatically starting SSH agent and adding SSH Identity key into the agent before SSH login (=> You need to manage SSH agent by yourself) --cleanup-agent Clearning up SSH agent at the end The agent is NOT cleaned up in case that --skip-agent option is given --cleanup-jump Clearning up sshjump pod at the end Defaults to skip cleaning up sshjump pod -v, --verbose Run ssh in verbose mode (=ssh -vvv) -h, --help Show this message Example: Scenario1 - You have private & public SSH key on your side $ kubectl ssh-jump -u myuser -i ~/.ssh/id_rsa -p ~/.ssh/id_rsa.pub hostname Scenario2 - You have .pem file but you don't have public key on your side $ kubectl ssh-jump -u ec2-user -i ~/.ssh/mykey.pem hostname EOF } read_options(){ if [[ -f "${PLUGIN_SSH_OPTIONS_FILE}" ]]; then source ${PLUGIN_SSH_OPTIONS_FILE} fi } write_options(){ local sshuser="$1" local identity="$2" local pubkey="$3" local port="$4" cat << EOF > ${PLUGIN_SSH_OPTIONS_FILE} sshuser=${sshuser} identity=${identity} pubkey=${pubkey} port=${port} EOF } get_node_list(){ echo "List of destination node..." kubectl "${k_args[@]}" get no -o custom-columns=Hostname:.metadata.name,Internal-IP:'{.status.addresses[?(@.type=="InternalIP")].address}' echo "" } get_openssh_verion_number() { ssh -V 2>&1 | awk -F'[_,]' '{print $2+0}' } cleanup_sshjump_pod(){ echo "Clearning up SSH Jump host (Pod)..." kubectl "${k_args[@]}" delete pod sshjump } check_and_start_agent(){ local identity="$1" is_alive="no" if [ -f ${SSH_AGENT_PID_FILE} ]; then SSH_AGENT_PID=$(cat ${SSH_AGENT_PID_FILE}) source ${SSH_AGENT_ENV_FILE} if [ ${SSH_AGENT_PID} -gt 0 ] && ps -p ${SSH_AGENT_PID} > /dev/null then echo "ssh-agent is already running" is_alive="yes" fi fi if [ "${is_alive}" = "no" ]; then ssh-agent > ${SSH_AGENT_ENV_FILE} agent_pid=$(cat ${SSH_AGENT_ENV_FILE} | grep 'echo Agent pid' |sed 's/echo Agent pid //; s/;//') echo "Started ssh-agent: pid=${agent_pid}" echo ${agent_pid} > ${SSH_AGENT_PID_FILE} source ${SSH_AGENT_ENV_FILE} ssh-add ${identity} fi } cleanup_agent(){ echo "Killing ssh-agent..." ssh-agent -k if [ -f ${SSH_AGENT_PID_FILE} ]; then rm ${SSH_AGENT_PID_FILE} fi if [ -f ${SSH_AGENT_ENV_FILE} ]; then rm ${SSH_AGENT_ENV_FILE} fi } create_jump_pod(){ local pod_template if [[ -n "${jump_pod_template:-}" && -e "${jump_pod_template}" ]]; then pod_template=$(<"${jump_pod_template}") fi if [[ -z "${pod_template}" ]]; then pod_template=$(cat </dev/null)) if [[ "${#pods[@]}" -eq 0 ]]; then echo "Error: failed to find pods with labels ${pod_labels}" >&2 exit 1 fi pod_name="${pods[0]}" echo "Using SSH jump pod ${pod_name}..." else pod_name=sshjump # Install an SSH Server if not yet installed if ! kubectl "${k_args[@]}" get pod "${pod_name}" &>/dev/null; then create_jump_pod # Wait until sshjump gets ready c=1 while [[ ${c} -le ${MAX_POD_CREATION_TIME} ]]; do pod_status=$(kubectl "${k_args[@]}" get pod "${pod_name}" -o jsonpath='{.status.phase}') if [[ "${pod_status}" == "Running" ]]; then break fi (( c++ )) sleep 1 done fi fi local identity_sshjump=${identity} local pubkey_sshjump=${pubkey} if [ ! -f "${pubkey_sshjump}" ]; then # Generate temp private/public key to ssh to the sshjump if the pubkey isn't given identity_sshjump=${PLUGIN_DIR}/id_rsa_sshjump pubkey_sshjump=${PLUGIN_DIR}/id_rsa_sshjump.pub if [ ! -f "${pubkey_sshjump}" ]; then echo "Generating nopass SSH pri/pub key to ssh to the sshjump ..." ssh-keygen -t rsa -f ${identity_sshjump} -N '' > /dev/null fi fi # Setup portforward kubectl "${k_args[@]}" port-forward "${pod_name}" 2222:22 2>/dev/null & pid_port_forward=$! # Wait a bit for the port forwarding to get ready for connection handling for 2222 sleep 2 # Inject public SSH key to sshjump cat ${pubkey_sshjump} | \ kubectl "${k_args[@]}" exec -i "${pod_name}" -- /bin/bash -c "cat > /root/.ssh/authorized_keys" # Add default ssh option sshargs="${sshargs} -o StrictHostKeyChecking=no" # Add RSA workaround options if the local OpenSSH version >= 8.5 sshversion=$(get_openssh_verion_number) if [ $(echo "${sshversion} >= 8.5" | bc) -eq 1 ]; then sshargs="${sshargs} -o HostkeyAlgorithms=+ssh-rsa -o PubkeyAcceptedAlgorithms=+ssh-rsa" fi if [ "${destnode}" = "sshjump" ]; then ssh ${sshuser}@127.0.0.1 -p 2222 -i ${identity_sshjump} ${sshargs} else # Using the SSH Server as a jumphost (via port-forward proxy), ssh into the desired Node ssh -i ${identity} -p ${port} ${sshuser}@${destnode} \ -o "ProxyCommand ssh root@127.0.0.1 -p 2222 -i ${identity_sshjump} ${sshargs} \"nc %h %p\"" ${sshargs} fi # Stop port-forward kill -3 ${pid_port_forward} 2>/dev/null } plugin_main() { skip_agent=no cleanup_jump=no cleanup_agent=no pod_labels= sshargs="" k_args=() while [ $# -gt 0 ] ; do nSkip=1 case $1 in "-h" | "--help") help exit 0 ;; "-v" | "--verbose" ) sshargs="${sshargs} -vvv" ;; "--cleanup-jump") cleanup_jump=yes ;; "--cleanup-agent") cleanup_agent=yes ;; "--skip-agent") skip_agent=yes ;; "-u" | "--user" ) c_sshuser=$2 nSkip=2 ;; "-i" | "--identity" ) c_identity=$2 nSkip=2 ;; "-p" | "--pubkey" ) c_pubkey=$2 nSkip=2 ;; "-P" | "--port") c_port=$2 nSkip=2 ;; "-a" | "--args" ) sshargs="${sshargs} $2" nSkip=2 ;; "-n" | "--namespace" | "--context") k_args+=("$1" "$2") nSkip=2 ;; "--pod-template") jump_pod_template="$2" nSkip=2 ;; "-l" | "--labels") pod_labels="$2" nSkip=2 ;; [0-9a-zA-Z-]*) destnode=$1 ;; *) help >&2 exit 1 ;; esac shift $nSkip done if [[ "$(type kubectl &>/dev/null; echo $?)" -eq 1 ]]; then echo "Error: missing kubectl command" >&2 echo "Please install kubectl (https://kubernetes.io/docs/tasks/tools/install-kubectl/)" >&2 exit 1 fi if [ ! -n "${destnode}" ]; then help >&2 echo "" get_node_list exit 1 fi if [ "${destnode}" = "sshjump" ]; then echo "Setting destination name as 'jumphost' allows to ssh into SSH jump Pod as 'root' user" c_sshuser=root fi if [ ! -d ${PLUGIN_DIR} ]; then mkdir -p ${PLUGIN_DIR} fi read_options if [ ! -n "${c_sshuser}" ]; then if [ ! -n "${sshuser}" ]; then c_sshuser="${USER}" # default: Current executing user fi echo "using: sshuser=${sshuser}" c_sshuser="${sshuser}" fi if [ ! -f "${c_identity}" ]; then if [ ! -f "${identity}" ]; then echo "Error: identity file is required" >&2 help >&2 exit 1 fi echo "using: identity=${identity}" c_identity="${identity}" fi if [ ! -f "${c_pubkey}" ]; then # From v0.4.0 pubkey file is optional to support PEM scenario # where you don't have public key on your side #if [ ! -n "${pubkey}" ]; then # help >&2 # exit 1 #fi if [ -f "${pubkey}" ]; then echo "using: pubkey=${pubkey}" c_pubkey="${pubkey}" fi fi if [ ! -n "${c_port}" ]; then if [ ! -n "${port}" ]; then port="22" # default: 22 fi echo "using: port=${port}" c_port="${port}" fi if [ "${sshargs}" != "" ]; then echo "using: args=${sshargs}" fi if [ "${jump_pod_template}" != "" ]; then echo "using: pod-template=${jump_pod_template}" fi # Caching current ssh options write_options "${c_sshuser}" "${c_identity}" "${c_pubkey}" "${c_port}" if [ "${skip_agent}" = "no" ]; then check_and_start_agent ${c_identity} fi # SSH Logging into desitnation node via Jump host run_ssh_node "${destnode}" "${c_sshuser}" "${c_identity}" "${c_pubkey}" "${c_port}" "${sshargs}" "${pod_labels}" # Cleaning up resources if needed if [[ "${cleanup_jump}" == "yes" && -z "${pod_labels}" ]]; then cleanup_sshjump_pod fi if [[ "${skip_agent}" = "no" && "${cleanup_agent}" = "yes" ]]; then cleanup_agent fi } plugin_main "$@" ================================================ FILE: ssh-jump.yaml ================================================ apiVersion: krew.googlecontainertools.github.com/v1alpha2 kind: Plugin metadata: name: ssh-jump spec: version: "v0.6.0" homepage: https://github.com/yokawasa/kubectl-plugin-ssh-jump platforms: - selector: matchExpressions: - {key: os, operator: In, values: [darwin, linux]} uri: https://github.com/yokawasa/kubectl-plugin-ssh-jump/archive/0.6.0.zip sha256: "a24149bb1b1ccba91ae87c86d21625adf9e110b9e81a0ab58ec84343e0f99ede" files: - from: "./*/kubectl-ssh-jump" to: . - from: "./*/LICENSE" to: . bin: "./kubectl-ssh-jump" shortDescription: Access nodes or services using SSH jump Pod caveats: | This plugin needs the following programs: * ssh(1) * ssh-agent(1) Please follow the documentation: https://github.com/yokawasa/kubectl-plugin-ssh-jump description: | A kubectl plugin to access Kubernetes nodes or remote services using a SSH jump Pod. A jump Pod is an intermediary Pod or an SSH gateway to Kubernetes node machines or remote services, through which a connection can be made.