Created
April 18, 2024 21:24
-
-
Save nilsandrey/111e2295a42f12336679295cf1105e66 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$substringInName = "myservice-rc" | |
$exclusions = @("myservice-rc-tests", "myservice-rc-primary") | |
# Start watching for the pod | |
Watch-Pod -substringInName $substringInName -exclusions $exclusions |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Known issues:
When running...
...at first, it won't attach giving this message:
...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.