0

I would like to have a command that gets the name of a pod and then uses it to log in to the pod. The command to list the pods to get the pod name:

kubectl get pods | Select-String -Pattern "mypodname"

The output is:

mypodname 1/1 Running    0  4d3h

I need to only get the value mypodname here. I have tried with Select-Object NAME with no luck. The podname changes over time. For example it can be mypodname-3467gogsfg one day and mypodname-043086dndn the next day because of new deployment.

This value I will use in this command:

kubectl --server=https://myservername.com --insecure-skip-tls-verify exec -it <name of pod goes here> /bin/sh

The second question is how these two can be combined in a windows powershell script so I can run something like this to log in to the pod:

podlogin mypodname

2 Answers 2

3

A function is probably what you're after since you're looking to combine the results into an execution by passing just the name:

Function PodLogin ($PodName) {
    $name = kubectl get pods | ? { $_ -match "(?<=($PodName-.*))\s" } | % { $Matches[1] }
    kubectl --server=https://myservername.com --insecure-skip-tls-verify exec -it $name /bin/sh
}

The use of Where-Object (?) just allows for a more condensed code without having to dig through the properties for the value matched since -Match will populate the $Matches automatic variable. Then, piping to Foreach-Object (%) to access the value matched via $Matches[1]; although not necessarily needed, saving it to a $name is more appealing overall. Finally, pass the $name to your command for execution.

Now you can call it using PodLogin podname.

Here's a RegEx demo that explains the pattern.

  • Assuming the pattern is always podname-.... , which is followed by a space.
Sign up to request clarification or add additional context in comments.

Comments

2

If I understand you correctly, you can split the output and then assign the first word to a variable. The output of kubectl is text, not an object.

$podname = -split (kubectl get pods | select-string mypodname) | select -first 1
$podname

mypodname


podlogin $podname

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.