kubectl copy a folder to all pods available in a namespace

6/21/2021

Im trying to copy folder to all kubernete pods. Below is the snippet of the PS1 I have to automate the process where I'm able to copy to one K8 pod.

$MasterPod = $(kubectl -n $namespace get pods --selector=jmeter_mode=master --no-headers=true --output=name).Replace("pod/", "")

Write-Output "Copy over Fragments Folder to master"
kubectl cp $FragFolder $namespace/${MasterPod}:"/TestFiles"

I would like to do the same for all my slave pods (which i can list using below)

$SlavePodAll = $(kubectl -n jmeter get pods --selector=jmeter_mode=slave --no-headers=true --output=name).Replace("pod/", "")

kubectl cp $FragFolder $namespace/${SlavePodAll}:"/TestFiles"

Obviously the last line is not working as it has list of all pods.

Is there any way I can achieve this-where I can replace $namespace/${SlavePodAll} with a proper line?

-- shey
azure
kubectl
kubernetes
powershell

1 Answer

6/21/2021

Since you are using --output name you can do an xargs bash script.

kubectl -n jmeter get pods --selector=jmeter_mode=slave --no-headers=true --output=name
| xargs -n1 -I{ins} kubectl cp $FragFolder $namespace/{ins}:"/TestFiles"
  • -n1 execute the command per line
  • -I{ins} uses the input from xargs as the variable {ins} which you can use inside your command.
-- Leroy
Source: StackOverflow