Skip to content

Instantly share code, notes, and snippets.

@nilsandrey
Created April 18, 2024 21:24
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 nilsandrey/111e2295a42f12336679295cf1105e66 to your computer and use it in GitHub Desktop.
Save nilsandrey/111e2295a42f12336679295cf1105e66 to your computer and use it in GitHub Desktop.
$substringInName = "myservice-rc"
$exclusions = @("myservice-rc-tests", "myservice-rc-primary")
# Start watching for the pod
Watch-Pod -substringInName $substringInName -exclusions $exclusions
# Function to watch for a pod with a specific substring in its name
# and ensure it does not contain any substrings from a list of exclusions
function Watch-Pod {
param (
[string]$substringInName,
[string[]]$exclusions
)
while ($true) {
# Retrieve all pods and filter based on inclusion and exclusion criteria
$pods = kubectl get pods -n business-solutions | Where-Object { $_ -match $substringInName }
foreach ($exclusion in $exclusions) {
$pods = $pods | Where-Object { $_ -notmatch $exclusion }
}
# If suitable pod is found
if ($pods) {
$pod = $pods[0] # Take the first matching pod
Write-Host "Pod found: $($pod)"
$namespace = "<fixed-namespace>"
$podName = $pod.Split()[0]
# Start watching logs
Start-LogWatch $namespace $podName
# Break out of the loop once the pod is terminated
break
}
# Wait for a few seconds before checking again
Start-Sleep -Seconds 5
}
}
# Function to start watching the logs of a specific pod
function Start-LogWatch {
param (
[string]$namespace,
[string]$podName
)
Write-Host "Watching logs for pod $podName in namespace $namespace..."
# Stream logs continuously using kubectl logs command
kubectl logs -n $namespace --since=1h --timestamps --follow $podName
}
@nilsandrey
Copy link
Author

nilsandrey commented Apr 18, 2024

Known issues:

When running...

kubectl logs -n $namespace --since=1h --timestamps --follow $podName

...at first, it won't attach giving this message:

Pod found: myservice-rc-74f69cd7c-8whq7                     0/1     ContainerCreating   0               5s
Watching logs for pod myservice-rc-74f69cd7c-8whq7 in namespace nnnnnnn...
Error from server (BadRequest): container "main" in pod "myservice-rc-74f69cd7c-8whq7" is waiting to start: ContainerCreating

...in which case you just repeat execting the command until the pod is no more in the "ContainerCreating" state. The script needs to be fixed to detect that situation and retry to attach.

Also, the namespace needs to be parametrized.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment