MohanKanth
MohanKanth

Reputation: 175

Remove docker containers with image names through jenkins pipeline

I am redeploying docker containers whenever there is trigger from gitlab through jenkins pipeline. So I am not able to remove docker containers with image name. I have followed below commands:

sh 'docker ps -f name=imagename -q | xargs --no-run-if-empty docker container stop

and

sh 'docker container ls -a -fname=imagename -q | xargs -r docker container rm'

The above command is not able to delete containers with image name.

I have tried with below command also.

sh 'docker ps -a | awk '{ print $1,$2 }' | grep imagename | awk '{print $1 }' | xargs -I {} docker rm -f {}'

But above command is able to delete container only through command mode. But it is not working through Jenkins pipeline

I need to delete the all containers with image names. For example if there are 5 containers with one image name. Then through that image name i need to delete 5 containers. Is it possible through jenkins pipeline ?

Can anyone help me please ?

Upvotes: 2

Views: 3661

Answers (1)

BMitch
BMitch

Reputation: 263896

In a Jenkins pipeline, you'd need to escape your $. You are also using single quotes for both Jenkins and in the command you're running. Instead of escaping those in your command, you can use a different shell syntax from Jenkins:

sh """
  docker ps -a \
    | awk '{ print \$1,\$2 }' \
    | grep imagename \
    | awk '{print \$1 }' \
    | xargs -I {} docker rm -f {}
  """

Upvotes: 2

Related Questions