Search code examples
dockerdocker-machine

Docker Machine: remove machines where STATE = Error or ERRORS is not None or DOCKER = Unknown


To list active docker-machines on a local computer we can use $docker-machine ls.

Which gives the following:

NAME ACTIVE DRIVER STATE URL SWARM DOCKER ERRORS

With each one populated by something, such as:

NAME                                       ACTIVE   DRIVER         STATE   URL   SWARM   DOCKER    ERRORS
api.horseshoe.v0.0.1.1570109766987.26    -        digitalocean   Error                 Unknown   GET https://api.digitalocean.com/v2/droplets/9999: 404 The resource you were accessing could not be found.

As just an example.

Now, to remove this manually I would do this:

$ docker-machine rm -f api.horseshoe.v0.0.1.1570109766987.26

However, I was wondering if there were a way to run a command which removes all of those machines where the following is true:

STATE = Error || DOCKER = Unknown || ERRORS is not None


Solution

  • Use filter:

    test=`docker-machine ls --filter STATE=Error --filter label=DOCKER=Unknown -q`
    

    Use it:

    docker-machine rm -f $test

    All together:

    `docker-machine rm -f $(docker-machine ls --filter STATE=Error --filter label=DOCKER=Unknown -q)`
    

    you can also use the two commands in one step, I just wrote them so just as an example

    see this