FindContainersByLabels takes a map of label names and values and returns any Docker containers which match all labels. Explanation of the query: * docs: https://docs.docker.com/engine/api/v1.23/ * Stack Overflow: https://stackoverflow.com/questions/28054203/docker-remote-api-filter-exited
(labels map[string]string)
| 218 | // * docs: https://docs.docker.com/engine/api/v1.23/ |
| 219 | // * Stack Overflow: https://stackoverflow.com/questions/28054203/docker-remote-api-filter-exited |
| 220 | func FindContainersByLabels(labels map[string]string) ([]container.Summary, error) { |
| 221 | if len(labels) < 1 { |
| 222 | return nil, fmt.Errorf("the provided list of labels was empty") |
| 223 | } |
| 224 | filterList := client.Filters{} |
| 225 | for k, v := range labels { |
| 226 | label := fmt.Sprintf("%s=%s", k, v) |
| 227 | // If no value is specified, filter any value by the key. |
| 228 | if v == "" { |
| 229 | label = k |
| 230 | } |
| 231 | filterList = filterList.Add("label", label) |
| 232 | } |
| 233 | |
| 234 | ctx, apiClient, err := GetDockerClient() |
| 235 | if err != nil { |
| 236 | return nil, err |
| 237 | } |
| 238 | containers, err := apiClient.ContainerList(ctx, client.ContainerListOptions{ |
| 239 | All: true, |
| 240 | Filters: filterList, |
| 241 | }) |
| 242 | if err != nil { |
| 243 | return nil, err |
| 244 | } |
| 245 | return containers.Items, nil |
| 246 | } |
| 247 | |
| 248 | // FindContainersWithLabel returns all containers with the given label |
| 249 | // It ignores the value of the label, is only interested that the label exists. |
no test coverage detected