Created
November 6, 2021 13:38
-
-
Save CrispyBaguette/a68a59dcdcca6c0a8bfba41f7f53f231 to your computer and use it in GitHub Desktop.
Docker Swarm: delete unused configs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Deletes unused Docker Swarm configs, while preserving configs that might be necessary for rollbacks.
Requires:
python3
and the docker python SDK.