Skip to content

Instantly share code, notes, and snippets.

@CrispyBaguette
Created November 6, 2021 13:38
Show Gist options
  • Save CrispyBaguette/a68a59dcdcca6c0a8bfba41f7f53f231 to your computer and use it in GitHub Desktop.
Save CrispyBaguette/a68a59dcdcca6c0a8bfba41f7f53f231 to your computer and use it in GitHub Desktop.
Docker Swarm: delete unused configs
import docker
client = docker.client.from_env()
def get_configs_for_service(service):
return [
*get_configs_from_current_spec(service),
*get_configs_from_previous_spec(service)
]
def get_configs_from_current_spec(service):
try:
return [client.configs.get(config_id=config["ConfigID"]) for config in service.attrs["Spec"]["TaskTemplate"]["ContainerSpec"]["Configs"]]
except KeyError:
return list()
def get_configs_from_previous_spec(service):
try:
return [client.configs.get(config_id=config["ConfigID"]) for config in service.attrs["PreviousSpec"]["TaskTemplate"]["ContainerSpec"]["Configs"]]
except KeyError:
return list()
def main():
confs_to_remove = client.configs.list()
confs_to_keep = list()
for service in client.services.list():
confs_to_keep.extend(get_configs_for_service(service))
for conf in confs_to_keep:
try:
confs_to_remove.remove(conf)
except ValueError:
pass
print(f"{len(confs_to_remove)} configs to remove")
for conf in confs_to_remove:
print(conf.short_id)
conf.remove()
if __name__ == "__main__":
main()
@CrispyBaguette
Copy link
Author

Deletes unused Docker Swarm configs, while preserving configs that might be necessary for rollbacks.

Requires: python3 and the docker python SDK.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment