### Install Artifactory Cleanup from Source Source: https://github.com/devopshq/artifactory-cleanup/blob/master/_autodocs/README.md Clones the repository and installs the package locally from source. ```bash # From source git clone https://github.com/devopshq/artifactory-cleanup.git pip install ./artifactory-cleanup ``` -------------------------------- ### Install and Run Artifactory Cleanup via Docker Source: https://github.com/devopshq/artifactory-cleanup/blob/master/README.md Installs the tool using Docker and shows how to run the help command. ```bash docker pull devopshq/artifactory-cleanup docker run --rm devopshq/artifactory-cleanup artifactory-cleanup --help ``` -------------------------------- ### Full BaseUrlSession Usage Example Source: https://github.com/devopshq/artifactory-cleanup/blob/master/_autodocs/session-loader-api.md A comprehensive example demonstrating session creation, authentication, fetching repositories, executing AQL queries, deleting artifacts, and retrieving artifact properties. ```python from artifactory_cleanup.base_url_session import BaseUrlSession from requests.auth import HTTPBasicAuth # Create session session = BaseUrlSession("https://artifactory.example.com/artifactory") session.auth = HTTPBasicAuth("admin", "password") # Get repositories r = session.get("/api/repositories") repos = r.json() # Execute AQL query aql = 'items.find({"repo": "my-repo"}).include("*")' r = session.post("/api/search/aql", data=aql) artifacts = r.json()["results"] # Delete artifact r = session.delete("/my-repo/path/to/artifact.jar") # Get artifact properties r = session.get("/api/storage/my-repo/path/to/artifact.jar") properties = r.json()["properties"] ``` -------------------------------- ### CLI Complete Example with Environment Variables Source: https://github.com/devopshq/artifactory-cleanup/blob/master/_autodocs/configuration.md A comprehensive CLI command example that sets environment variables for authentication and worker count, then executes a specific cleanup policy with output options. ```bash export ARTIFACTORY_USERNAME=myuser export ARTIFACTORY_PASSWORD=mypass export ARTIFACTORY_CLEANUP_WORKER_COUNT=4 artifactory-cleanup \ --config cleanup.yaml \ --policy docker \ --destroy \ --output report.json \ --output-format json ``` -------------------------------- ### Install and Run Artifactory Cleanup via Python CLI Source: https://github.com/devopshq/artifactory-cleanup/blob/master/README.md Installs the tool using pip and shows how to run the help command. ```bash python3 -mpip install artifactory-cleanup artifactory-cleanup --help ``` -------------------------------- ### BaseUrlSession Request Examples Source: https://github.com/devopshq/artifactory-cleanup/blob/master/_autodocs/session-loader-api.md Shows how to make GET, POST, and DELETE requests using BaseUrlSession. Relative URLs are joined with the base URL, while absolute URLs are used directly. ```python # Relative URL (joined with base_url) r = session.get("/api/version") # → GET https://artifactory.example.com/artifactory/api/version # Absolute URL (used as-is) r = session.post("https://other.com/api", ...) # → POST https://other.com/api # AQL query r = session.post("/api/search/aql", data=aql_query) ``` -------------------------------- ### Policy Composition Example Source: https://github.com/devopshq/artifactory-cleanup/blob/master/_autodocs/README.md Illustrates how multiple rules are composed within a policy to filter artifacts sequentially. ```text Policy ├── Rule 1 (select repo) ├── Rule 2 (filter by age) ├── Rule 3 (filter by properties) └── Rule 4 (keep N versions) ``` -------------------------------- ### Example Artifact Dictionary Source: https://github.com/devopshq/artifactory-cleanup/blob/master/_autodocs/types.md Illustrates a sample ArtifactDict object with typical values for its fields. ```python artifact = { "repo": "docker-local", "path": "myapp/v1.0.0", "name": "sha256:abcd1234", "properties": {"docker.manifest": "1.0.0", "docker.image": "myapp"}, "stats": {"downloaded": "2024-01-15"}, "size": 1048576, "actual_sha1": "abc123def456" } ``` -------------------------------- ### Complete Programmatic Usage Example Source: https://github.com/devopshq/artifactory-cleanup/blob/master/_autodocs/public-api-index.md An example demonstrating how to use the ArtifactoryCleanup class to define cleanup policies and execute cleanup operations programmatically. It includes defining policies, creating a session, and running the cleanup process. ```python #!/usr/bin/env python3 from datetime import date from artifactory_cleanup import CleanupPolicy, register from artifactory_cleanup.artifactorycleanup import ArtifactoryCleanup from artifactory_cleanup.base_url_session import BaseUrlSession from artifactory_cleanup.context_managers import get_context_managers from artifactory_cleanup.rules import ( Repo, DeleteOlderThan, ExcludeFilename, KeepLatestNFiles ) from requests.auth import HTTPBasicAuth # Define policies policy1 = CleanupPolicy( "snapshots", Repo("snapshots"), DeleteOlderThan(days=30) ) policy2 = CleanupPolicy( "releases", Repo("releases"), ExcludeFilename(masks=["*:latest", "*:stable"]), DeleteOlderThan(days=365), KeepLatestNFiles(count=10) ) # Create session session = BaseUrlSession("https://artifactory.example.com/artifactory") session.auth = HTTPBasicAuth("admin", "password") # Create cleanup executor cleanup = ArtifactoryCleanup( session=session, policies=[policy1, policy2], destroy=False, # Dry run first today=date.today(), ignore_not_found=False, worker_count=1 ) # Execute block_mgr, test_mgr = get_context_managers() for summary in cleanup.cleanup( block_ctx_mgr=block_mgr, test_ctx_mgr=test_mgr ): if summary: print(f"{summary.policy_name}: {summary.artifacts_removed} artifacts") ``` -------------------------------- ### Install Artifactory Cleanup via Pip Source: https://github.com/devopshq/artifactory-cleanup/blob/master/_autodocs/README.md Installs the artifactory-cleanup package using pip. ```bash # Via pip pip install artifactory-cleanup ``` -------------------------------- ### AQL AND Operator Example Source: https://github.com/devopshq/artifactory-cleanup/blob/master/_autodocs/delete-rules.md Demonstrates the use of the '$and' operator in AQL to combine multiple conditions, requiring all to be true for an artifact to match. ```json {"$and": [cond1, cond2]} ``` -------------------------------- ### Example Configuration for Basic Cleanup Source: https://github.com/devopshq/artifactory-cleanup/blob/master/_autodocs/configuration.md A sample YAML configuration file demonstrating a basic cleanup policy that removes snapshots older than 30 days from a specific repository. ```yaml artifactory-cleanup: server: https://artifactory.example.com/artifactory user: $ARTIFACTORY_USERNAME password: $ARTIFACTORY_PASSWORD policies: - name: old-snapshots rules: - rule: Repo name: snapshots - rule: DeleteOlderThan days: 30 ``` -------------------------------- ### Repository Doesn't Exist Example Source: https://github.com/devopshq/artifactory-cleanup/blob/master/_autodocs/errors.md Illustrates a configuration where a specified repository does not exist, leading to an error during rule checking. This can be bypassed with `--ignore-not-found`. ```yaml rules: - rule: Repo name: nonexistent-repo ``` -------------------------------- ### Artifactory Cleanup Configuration Example Source: https://github.com/devopshq/artifactory-cleanup/blob/master/README.md A sample YAML configuration file for artifactory-cleanup, specifying server details and cleanup policies. ```yaml # artifactory-cleanup.yaml artifactory-cleanup: server: https://repo.example.com/artifactory # $VAR is auto populated from environment variables user: $ARTIFACTORY_USERNAME password: $ARTIFACTORY_PASSWORD policies: - name: Remove all files from repo-name-here older than 7 days rules: - rule: Repo name: "reponame" - rule: DeleteOlderThan days: 7 ``` -------------------------------- ### Python CleanupSummary Example Source: https://github.com/devopshq/artifactory-cleanup/blob/master/_autodocs/cleanup-api.md Demonstrates how to create and print a CleanupSummary object. This is useful for logging or reporting the results of an artifact cleanup process. ```python summary = CleanupSummary( policy_name="remove_old_artifacts", artifacts_removed=42, artifacts_size=1073741824, # 1 GB removed_artifacts=[...] ) print(f"{summary.policy_name}: {summary.artifacts_removed} files, {summary.artifacts_size} bytes") ``` -------------------------------- ### Simple Docker Cleanup Example Source: https://github.com/devopshq/artifactory-cleanup/blob/master/_autodocs/docker-rules.md A basic Docker cleanup pattern using a repository rule and a rule to delete images older than a specified number of days. ```yaml policies: - name: docker-housekeeping rules: - rule: Repo name: docker-local - rule: DeleteDockerImagesOlderThan days: 30 ``` -------------------------------- ### ArtifactoryCleanup Example Usage Source: https://github.com/devopshq/artifactory-cleanup/blob/master/_autodocs/cleanup-api.md Demonstrates setting up an Artifactory session, defining a cleanup policy, initializing ArtifactoryCleanup, and running it in dry-run mode. It also shows how to switch to destroy mode. ```python from datetime import date from artifactory_cleanup.artifactorycleanup import ArtifactoryCleanup from artifactory_cleanup.base_url_session import BaseUrlSession from artifactory_cleanup.rules import Repo, DeleteOlderThan from artifactory_cleanup.rules.base import CleanupPolicy # Create authenticated session session = BaseUrlSession("https://artifactory.example.com/artifactory") session.auth = ("username", "password") # Define cleanup policy policy = CleanupPolicy( "remove_old_artifacts", Repo("my-repo"), DeleteOlderThan(days=30) ) # Create cleanup instance cleanup = ArtifactoryCleanup( session=session, policies=[policy], destroy=False, # Dry-run mode today=date.today(), ignore_not_found=False, worker_count=1 ) # Execute (dry-run) for summary in cleanup.cleanup( block_ctx_mgr=lambda x: __import__('contextlib').nullcontext(), test_ctx_mgr=lambda x: __import__('contextlib').nullcontext() ): if summary: print(f"Would delete: {summary.artifacts_removed} artifacts ({summary.artifacts_size} bytes)") # Switch to destroy mode cleanup.destroy = True for summary in cleanup.cleanup(...): if summary: print(f"Deleted: {summary.artifacts_removed} artifacts") ``` -------------------------------- ### Register Custom Rule Source: https://github.com/devopshq/artifactory-cleanup/blob/master/_autodocs/README.md Example of creating and registering a custom rule by inheriting from the base Rule class. ```python from artifactory_cleanup import register from artifactory_cleanup.rules import Rule class MyRule(Rule): """Clear description of what this does.""" def __init__(self, param: str): self.param = param def filter(self, artifacts): # Implementation return artifacts register(MyRule) ``` -------------------------------- ### AQL Date-Based Filters Source: https://github.com/devopshq/artifactory-cleanup/blob/master/_autodocs/rule-base-api.md Provides examples of AQL filters for selecting artifacts based on their creation or modification dates. ```python {"created": {"$lt": "2024-01-01"}} # Created before ``` ```python {"modified": {"$gt": "2024-01-01"}} # Modified after ``` -------------------------------- ### Custom Rule Definition Example Source: https://github.com/devopshq/artifactory-cleanup/blob/master/_autodocs/configuration.md Example of a custom rule file (`custom_rules.py`) that defines a new rule class `MyCustomRule` and registers it. This rule can then be used in the configuration file. ```python from artifactory_cleanup import register from artifactory_cleanup.rules import Rule class MyCustomRule(Rule): def __init__(self, param: str): self.param = param register(MyCustomRule) ``` -------------------------------- ### Load Config and Create Cleanup Instance Source: https://github.com/devopshq/artifactory-cleanup/blob/master/_autodocs/session-loader-api.md This snippet demonstrates loading configuration from a YAML file, importing custom Python rules, establishing an authenticated session with Artifactory (using API key or basic auth), and initializing the ArtifactoryCleanup instance for a dry run. Use this for a complete setup of the cleanup process. ```python from datetime import date from artifactory_cleanup.loaders import YamlConfigLoader, PythonLoader from artifactory_cleanup.base_url_session import BaseUrlSession from artifactory_cleanup.artifactorycleanup import ArtifactoryCleanup from requests.auth import HTTPBasicAuth # Load custom rules if needed PythonLoader.import_module("my_rules.py") # Load configuration loader = YamlConfigLoader("artifactory-cleanup.yaml") policies = loader.get_policies() server, user, password, apikey = loader.get_connection() # Create authenticated session session = BaseUrlSession(server) if apikey: session.headers = {"X-JFrog-Art-Api": apikey} else: session.auth = HTTPBasicAuth(user, password) # Create cleanup instance cleanup = ArtifactoryCleanup( session=session, policies=policies, destroy=False, # Dry run today=date.today(), ignore_not_found=False, worker_count=1 ) # Execute for summary in cleanup.cleanup(...): if summary: print(f"Deleted {summary.artifacts_removed} artifacts") ``` -------------------------------- ### Invalid YAML Syntax Example Source: https://github.com/devopshq/artifactory-cleanup/blob/master/_autodocs/errors.md Illustrates an invalid YAML configuration due to a missing colon, which will trigger an InvalidConfigError. ```yaml artifactory-cleanup: server: https://example.com user: admin password: pass policies: # Missing colon - name cleanup ``` -------------------------------- ### Missing Required Fields Example Source: https://github.com/devopshq/artifactory-cleanup/blob/master/_autodocs/errors.md Demonstrates a configuration error where required fields like 'user' or 'password' are missing, leading to an InvalidConfigError. ```yaml artifactory-cleanup: server: https://example.com # Missing user/password or apikey policies: [] ``` -------------------------------- ### Invalid Rule Name Example Source: https://github.com/devopshq/artifactory-cleanup/blob/master/_autodocs/errors.md Shows an example of an invalid rule name in the configuration, which will cause an InvalidConfigError during policy loading. ```yaml policies: - name: cleanup rules: - rule: DeleteNonexistent # Wrong rule name days: 30 ``` -------------------------------- ### AQL OR Operator Example Source: https://github.com/devopshq/artifactory-cleanup/blob/master/_autodocs/delete-rules.md Demonstrates the use of the '$or' operator in AQL to combine multiple conditions, requiring at least one to be true for an artifact to match. ```json {"$or": [cond1, cond2]} ``` -------------------------------- ### Usage Pattern: Keep Latest Releases Source: https://github.com/devopshq/artifactory-cleanup/blob/master/_autodocs/keep-rules.md Example policy configuration for retaining the 5 most recent files in the 'releases' repository. ```yaml policies: - name: production-releases rules: - rule: Repo name: releases - rule: KeepLatestNFiles count: 5 ``` -------------------------------- ### Artifactory Session Operations Source: https://github.com/devopshq/artifactory-cleanup/blob/master/_autodocs/types.md Demonstrates common operations like getting repositories, executing AQL queries, and deleting artifacts using an authenticated session. ```python session = BaseUrlSession("https://artifactory.example.com/artifactory") session.auth = ("username", "password") # Get repositories r = session.get("/api/repositories") # Execute AQL r = session.post("/api/search/aql", data="items.find()") # Delete artifact r = session.delete("/my-repo/path/to/artifact.jar") ``` -------------------------------- ### AQL Less Than Operator Example Source: https://github.com/devopshq/artifactory-cleanup/blob/master/_autodocs/delete-rules.md Demonstrates the use of the '$lt' (less than) operator in AQL for filtering artifacts based on their creation date. ```json {"created": {"$lt": "2024-01-01"}} ``` -------------------------------- ### Example JSON Output with Artifacts Source: https://github.com/devopshq/artifactory-cleanup/blob/master/_autodocs/configuration.md Illustrates the structure of the JSON output when the `--output-artifacts` flag is used, including details of removed items. ```json { "policies": [ { "name": "cleanup-policy", "file_count": 10, "size": 1024, "removed_artifacts": [ { "repo": "my-repo", "path": "app", "name": "old.jar", "size": 512 } ] } ], "total_size": 1024 } ``` -------------------------------- ### Example Usage of CleanupPolicy API Source: https://github.com/devopshq/artifactory-cleanup/blob/master/_autodocs/policy-api.md Demonstrates the complete workflow of creating, initializing, validating, querying, filtering, and deleting artifacts using the CleanupPolicy API. ```python from datetime import date from artifactory_cleanup.rules.base import CleanupPolicy from artifactory_cleanup.rules import Repo, DeleteOlderThan from artifactory_cleanup.base_url_session import BaseUrlSession from requests.auth import HTTPBasicAuth # Create session session = BaseUrlSession("https://artifactory.example.com/artifactory") session.auth = HTTPBasicAuth("user", "password") # Create policy with rules policy = CleanupPolicy( "old-artifacts", Repo("my-repo"), DeleteOlderThan(days=90) ) # Initialize policy.init(session, date.today()) # Validate configuration policy.check() # Generate query policy.build_aql_query() print(f"Query: {policy.aql_text}") # Get matching artifacts artifacts = policy.get_artifacts() print(f"Found {len(artifacts)} artifacts") # Filter to get deletable artifacts to_delete = policy.filter(artifacts) print(f"Will delete {len(to_delete)} artifacts") # Delete each (in dry-run mode) for artifact in to_delete: policy.delete(artifact, destroy=False) ``` -------------------------------- ### AQL Equals Operator Example Source: https://github.com/devopshq/artifactory-cleanup/blob/master/_autodocs/delete-rules.md Demonstrates the use of the '$eq' (equals) operator in AQL for filtering artifacts where a specific field (e.g., downloads) is null. ```json {"stat.downloads": {"$eq": null}} ``` -------------------------------- ### Missing Required Rule Parameter Example Source: https://github.com/devopshq/artifactory-cleanup/blob/master/_autodocs/errors.md Illustrates a configuration where a required parameter, such as 'days' for the DeleteOlderThan rule, is missing, resulting in an InvalidConfigError. ```yaml rules: - rule: DeleteOlderThan # Missing 'days' parameter ``` -------------------------------- ### Connection Error Example Source: https://github.com/devopshq/artifactory-cleanup/blob/master/_autodocs/errors.md Shows a connection error, indicating that the tool cannot reach the Artifactory server. Solutions include verifying the server URL and network connectivity. ```text requests.exceptions.ConnectionError: Failed to establish connection ``` -------------------------------- ### Artifactory Cleanup Command-Line Usage Examples Source: https://github.com/devopshq/artifactory-cleanup/blob/master/_autodocs/README.md Demonstrates common command-line invocations for the artifactory-cleanup tool, including dry runs, destructive operations, policy testing, custom rule loading, and output reporting. ```bash # Dry run (default) artifactory-cleanup # Actually delete artifactory-cleanup --destroy # Test-specific policy artifactory-cleanup --policy docker --destroy # With custom rules artifactory-cleanup --load-rules custom.py # Save output artifactory-cleanup --output report.json --output-format json ``` -------------------------------- ### Using Custom Rule in Configuration Source: https://github.com/devopshq/artifactory-cleanup/blob/master/_autodocs/configuration.md Example of how to specify a custom rule and its parameters within the YAML configuration file. This links the defined custom rule to specific cleanup policies. ```yaml rules: - rule: MyCustomRule param: "value" ``` -------------------------------- ### AQL Less Than or Equal Operator Example Source: https://github.com/devopshq/artifactory-cleanup/blob/master/_autodocs/delete-rules.md Demonstrates the use of the '$lte' (less than or equal) operator in AQL for filtering artifacts based on their modification date. ```json {"modified": {"$lte": "2024-01-01"}} ``` -------------------------------- ### Combining Include and Exclude Filters Source: https://github.com/devopshq/artifactory-cleanup/blob/master/_autodocs/repo-filter-rules.md This example demonstrates combining 'IncludePath' and 'ExcludeFilename' rules. It specifies that only artifacts within 'prod' or 'release' paths should be considered, but excludes files matching certain filename patterns. ```yaml rules: - rule: IncludePath # Match ANY path masks: ['**/prod/**', '**/release/**'] - rule: ExcludeFilename # But NOT these files masks: ['*.md', '*.txt'] - rule: ExcludeFilename # And NOT these either masks: ['*:latest', '*:stable'] ``` -------------------------------- ### Invalid Repository Name Example Source: https://github.com/devopshq/artifactory-cleanup/blob/master/_autodocs/errors.md Shows an invalid repository name containing forbidden characters like '/', which will be rejected with an InvalidConfigError. ```yaml rules: - rule: Repo name: "repo/with/slashes" # Invalid: contains / ``` -------------------------------- ### Usage Pattern: Keep Versions Per Branch Source: https://github.com/devopshq/artifactory-cleanup/blob/master/_autodocs/keep-rules.md Example policy configuration for keeping the 10 newest files within each folder of the 'builds' repository. ```yaml policies: - name: multi-branch-builds rules: - rule: Repo name: builds - rule: KeepLatestNFilesInFolder count: 10 ``` -------------------------------- ### CLI Dry Run Example Source: https://github.com/devopshq/artifactory-cleanup/blob/master/_autodocs/configuration.md Executes the Artifactory cleanup process in dry-run mode using a specified configuration file. This logs actions without performing deletions. ```bash artifactory-cleanup --config config.yaml # Output: "DEBUG - we would delete '...'" ``` -------------------------------- ### Usage Pattern: Semantic Versioning Cleanup Source: https://github.com/devopshq/artifactory-cleanup/blob/master/_autodocs/keep-rules.md Example policy configuration for cleaning up artifacts based on semantic versioning, keeping the 5 latest versions and deleting older ones. ```yaml policies: - name: semantic-cleanup rules: - rule: Repo name: dist-repo - rule: DeleteOlderThan days: 180 - rule: KeepLatestVersionNFilesInFolder count: 5 custom_regexp: 'v?([\d]+\.[\d]+\.[\d]+)' ``` -------------------------------- ### HTTPError 404 Not Found Example Source: https://github.com/devopshq/artifactory-cleanup/blob/master/_autodocs/errors.md Indicates an HTTP 404 error, usually because a specified repository does not exist. Solutions include checking spelling or using `--ignore-not-found`. ```text The repository does not exist! ``` -------------------------------- ### Keep Latest Docker Versions Example Source: https://github.com/devopshq/artifactory-cleanup/blob/master/_autodocs/docker-rules.md A Docker cleanup pattern that keeps the latest N Docker images in a repository. This is a common strategy for managing image versions. ```yaml policies: - name: docker-versions rules: - rule: Repo name: docker-local - rule: KeepLatestNDockerImages count: 5 ``` -------------------------------- ### Create Custom Rule - MySimpleRule Source: https://github.com/devopshq/artifactory-cleanup/blob/master/README.md Example of creating a custom rule in Python. The rule class inherits from 'Rule' and can be registered using the 'register' function. ```python # myrule.py from typing import List from artifactory_cleanup import register from artifactory_cleanup.rules import Rule, ArtifactsList class MySimpleRule(Rule): """ This doc string is used as rule title For more methods look at Rule source code """ def __init__(self, my_param: str, value: int): self.my_param = my_param self.value = value def aql_add_filter(self, filters: List) -> List: print(f"Today is {self.today}") print(self.my_param) print(self.value) return filters def filter(self, artifacts: ArtifactsList) -> ArtifactsList: """I'm here just to print the list""" print(self.my_param) print(self.value) # You can make requests to artifactory by using self.session: # url = f"/api/storage/{self.repo}" # r = self.session.get(url) # r.raise_for_status() return artifacts # Register your rule in the system register(MySimpleRule) ``` -------------------------------- ### Convert Artifactory Response to ArtifactsList Source: https://github.com/devopshq/artifactory-cleanup/blob/master/_autodocs/types.md Example of using the `from_response` class method to convert raw Artifactory AQL search results into a structured ArtifactsList, normalizing data. ```python response = session.post("/api/search/aql", data=aql) artifacts = ArtifactsList.from_response(response.json()["results"]) ``` -------------------------------- ### Programmatic Artifactory Cleanup Execution Source: https://github.com/devopshq/artifactory-cleanup/blob/master/_autodocs/README.md Shows how to programmatically configure and execute artifact cleanup using the ArtifactoryCleanup class, including session setup, policy definition, and execution parameters. ```python from datetime import date from artifactory_cleanup.rules import Repo, DeleteOlderThan from artifactory_cleanup.rules.base import CleanupPolicy from artifactory_cleanup.base_url_session import BaseUrlSession from artifactory_cleanup.artifactorycleanup import ArtifactoryCleanup from requests.auth import HTTPBasicAuth # Create authenticated session session = BaseUrlSession("https://artifactory.example.com/artifactory") session.auth = HTTPBasicAuth("user", "password") # Define policy policy = CleanupPolicy( "old-artifacts", Repo("my-repo"), DeleteOlderThan(days=30) ) # Create cleanup executor cleanup = ArtifactoryCleanup( session=session, policies=[policy], destroy=False, today=date.today(), ignore_not_found=False, worker_count=1 ) ``` -------------------------------- ### Initialize YamlConfigLoader Source: https://github.com/devopshq/artifactory-cleanup/blob/master/_autodocs/session-loader-api.md Create an instance of YamlConfigLoader, specifying the path to the YAML configuration file. ```python from artifactory_cleanup.loaders import YamlConfigLoader loader = YamlConfigLoader("artifactory-cleanup.yaml") ``` -------------------------------- ### AQL Repository and Path Filters Source: https://github.com/devopshq/artifactory-cleanup/blob/master/_autodocs/rule-base-api.md Demonstrates AQL filters for selecting artifacts based on their repository, path, or filename patterns. ```python {"repo": {"$eq": "my-repo"}} # Specific repo ``` ```python {"path": {"$match": "**/cache/**"}} # Path matches pattern ``` ```python {"name": {"$match": "*.jar"}} # Filename matches ``` -------------------------------- ### Configuring Cleanup Policies with Rules Source: https://github.com/devopshq/artifactory-cleanup/blob/master/_autodocs/rule-base-api.md Demonstrates how to define a cleanup policy in YAML, specifying repository rules and custom rules like KeepMinimumArtifacts with parameters. ```yaml policies: - name: docker cleanup rules: - rule: Repo name: docker-local - rule: KeepMinimumArtifacts minimum: 5 ``` -------------------------------- ### Get Rule Name Source: https://github.com/devopshq/artifactory-cleanup/blob/master/_autodocs/rule-base-api.md Demonstrates how to retrieve the name of a custom rule. By default, it uses the class name. ```python class MyRule(Rule): pass print(MyRule.name()) # Output: "MyRule" ``` -------------------------------- ### Basic CLI Usage Source: https://github.com/devopshq/artifactory-cleanup/blob/master/README.md Load custom rules from a Python file using the --load-rules argument. ```bash artifactory-cleanup --load-rules=myrule.py ``` -------------------------------- ### Get Package Version Source: https://github.com/devopshq/artifactory-cleanup/blob/master/_autodocs/public-api-index.md Access the current version string of the artifactory-cleanup package. This is useful for logging or dependency checks. ```python from artifactory_cleanup import __version__ print(__version__) # "1.0.18" ``` -------------------------------- ### Load Custom Rules and Use in Configuration Source: https://github.com/devopshq/artifactory-cleanup/blob/master/_autodocs/session-loader-api.md Demonstrates how to load custom rules using PythonLoader and then reference them in a YAML configuration file. ```python from artifactory_cleanup.loaders import PythonLoader # Load custom rules PythonLoader.import_module("custom_rules.py") # Now use in config.yaml # rules: # - rule: KeepMinimum # minimum: 5 ``` -------------------------------- ### Initialize Rule with Session and Date Source: https://github.com/devopshq/artifactory-cleanup/blob/master/_autodocs/rule-base-api.md Illustrates the initialization of a rule instance with an Artifactory session and a reference date. This is typically called by the CleanupPolicy. ```python rule = MyRule() rule.init(session, date.today()) ``` -------------------------------- ### Get a Rule Class from the Registry Source: https://github.com/devopshq/artifactory-cleanup/blob/master/_autodocs/session-loader-api.md Retrieves a specific rule class from the internal registry by its name. The retrieved class can then be instantiated. ```python from artifactory_cleanup.loaders import registry rule_cls = registry.get("DeleteOlderThan") rule = rule_cls(days=30) ``` -------------------------------- ### AQL Greater Than Operator Example Source: https://github.com/devopshq/artifactory-cleanup/blob/master/_autodocs/delete-rules.md Demonstrates the use of the '$gt' (greater than) operator in AQL for filtering artifacts based on their creation date. ```json {"created": {"$gt": "2024-01-01"}} ``` -------------------------------- ### CLI Dry Run and Destroy Execution Source: https://github.com/devopshq/artifactory-cleanup/blob/master/_autodocs/errors.md Demonstrates the recommended workflow for using the CLI: first perform a dry run to review changes, then execute the cleanup with the --destroy flag. ```bash artifactory-cleanup # Dry run (default) # Review output artifactory-cleanup --destroy # Then delete ``` -------------------------------- ### AQL Statistics-Based Filters Source: https://github.com/devopshq/artifactory-cleanup/blob/master/_autodocs/rule-base-api.md Illustrates AQL filters for selecting artifacts based on download statistics, such as never downloaded or last downloaded before a specific date. ```python {"stat.downloads": {"$eq": None}} # Never downloaded ``` ```python {"stat.downloaded": {"$lt": "2024-01-01"}} # Last download before date ``` -------------------------------- ### Environment Variable Expansion in Configuration Source: https://github.com/devopshq/artifactory-cleanup/blob/master/_autodocs/configuration.md Demonstrates how environment variables can be used within the YAML configuration file for sensitive information like server URLs and credentials. ```yaml server: $ARTIFACTORY_SERVER user: $ARTIFACTORY_USERNAME password: $ARTIFACTORY_PASSWORD apikey: $ARTIFACTORY_API_KEY ``` -------------------------------- ### Create BaseUrlSession with Authentication Source: https://github.com/devopshq/artifactory-cleanup/blob/master/_autodocs/session-loader-api.md Instantiate BaseUrlSession and set authentication credentials. Supports basic auth or API key headers. ```python from artifactory_cleanup.base_url_session import BaseUrlSession from requests.auth import HTTPBasicAuth session = BaseUrlSession("https://artifactory.example.com/artifactory") session.auth = HTTPBasicAuth("username", "password") ``` -------------------------------- ### Normalize Single Artifact with ArtifactsList.prepare Source: https://github.com/devopshq/artifactory-cleanup/blob/master/_autodocs/types.md Demonstrates the `prepare` class method for normalizing a single raw artifact dictionary, converting properties and stats into the expected dictionary format. ```python raw_artifact = { "repo": "my-repo", "properties": [{"key": "build", "value": "123"}], "stats": [{"downloaded": "2024-01-01"}] } normalized = ArtifactsList.prepare(raw_artifact) # properties becomes dict: {"build": "123"} # stats becomes dict: {"downloaded": "2024-01-01"} ``` -------------------------------- ### DeleteOlderThanNDaysWithoutDownloads Rule Example Source: https://github.com/devopshq/artifactory-cleanup/blob/master/_autodocs/delete-rules.md Deletes artifacts that are both older than a specified number of days and have never been downloaded. This rule is more conservative and suitable for production environments. ```yaml policies: - name: safe-cleanup rules: - rule: Repo name: production-repo - rule: DeleteOlderThanNDaysWithoutDownloads days: 90 ``` -------------------------------- ### init(session: Session, today: date) Source: https://github.com/devopshq/artifactory-cleanup/blob/master/_autodocs/policy-api.md Initializes all rules within the policy using the provided Artifactory session and a reference date. This method is automatically called by the ArtifactoryCleanup process. ```APIDOC ## init(session: Session, today: date) ### Description Initializes all rules within the policy using the provided Artifactory session and a reference date. This method is automatically called by the ArtifactoryCleanup process. ### Method - `session`: Authenticated HTTP session (BaseUrlSession) - `today`: Reference date for date-based rules ### Example ```python policy.init(session, date.today()) ``` ``` -------------------------------- ### Use Custom Rule in Configuration Source: https://github.com/devopshq/artifactory-cleanup/blob/master/README.md Example of how to use a custom rule in the Artifactory cleanup configuration file. Specify the rule name and its parameters. ```yaml # artifactory-cleanup.yaml - rule: MySimpleRule my_param: "Hello, world!" value: 42 ``` -------------------------------- ### Create ArtifactoryCleanup Instance Source: https://github.com/devopshq/artifactory-cleanup/blob/master/_autodocs/public-api-index.md Initialize the ArtifactoryCleanup class with a session, policies, and execution parameters. Ensure the session is properly authenticated and configured. ```python # Pattern 3: Create cleanup instance from artifactory_cleanup.base_url_session import BaseUrlSession from artifactory_cleanup.artifactorycleanup import ArtifactoryCleanup from requests.auth import HTTPBasicAuth session = BaseUrlSession("https://artifactory.example.com/artifactory") session.auth = HTTPBasicAuth("user", "pass") cleanup = ArtifactoryCleanup( session=session, policies=policies, destroy=False, today=date.today(), ignore_not_found=False, worker_count=1 ) ``` -------------------------------- ### Extract Rule Title from Docstring Source: https://github.com/devopshq/artifactory-cleanup/blob/master/_autodocs/rule-base-api.md Shows how to get a one-line title from a rule's docstring. Useful for generating human-readable rule descriptions. ```python class MyRule(Rule): """ This is a custom rule for specific use cases. It has multiple lines in the docstring. """ print(MyRule.title()) # Output: "This is a custom rule for specific use cases." ``` -------------------------------- ### Setting Environment Variables and Running Cleanup Source: https://github.com/devopshq/artifactory-cleanup/blob/master/_autodocs/configuration.md Shows how to export environment variables for Artifactory connection details and then run the `artifactory-cleanup` command without explicit CLI arguments. ```bash export ARTIFACTORY_SERVER=https://artifactory.example.com/artifactory export ARTIFACTORY_USERNAME=myuser export ARTIFACTORY_PASSWORD=mypass artifactory-cleanup ``` -------------------------------- ### Wrong Parameter Type Example Source: https://github.com/devopshq/artifactory-cleanup/blob/master/_autodocs/errors.md Demonstrates a type error in the configuration, where a parameter like 'days' is provided as a string instead of an integer, triggering an InvalidConfigError. ```yaml rules: - rule: DeleteOlderThan days: "30" # String instead of integer ``` -------------------------------- ### Execute Cleanup Script Source: https://github.com/devopshq/artifactory-cleanup/blob/master/_autodocs/README.md This snippet shows how to execute the cleanup process using context managers for blocking and testing. ```python from artifactory_cleanup.context_managers import get_context_managers block_mgr, test_mgr = get_context_managers() for summary in cleanup.cleanup(block_ctx_mgr=block_mgr, test_ctx_mgr=test_mgr): if summary: print(f"Deleted {summary.artifacts_removed} artifacts") ``` -------------------------------- ### Specify Artifactory Cleanup Version via Python CLI Source: https://github.com/devopshq/artifactory-cleanup/blob/master/README.md Installs and runs a specific version of the artifactory-cleanup tool using pip. Useful for production environments. ```bash # python (later we call it 'cli') python3 -mpip install artifactory-cleanup==1.0.0 artifactory-cleanup --help ``` -------------------------------- ### YamlConfigLoader.get_policies Source: https://github.com/devopshq/artifactory-cleanup/blob/master/_autodocs/session-loader-api.md Loads and parses cleanup policies from the YAML configuration file. ```APIDOC ## YamlConfigLoader.get_policies() → List[CleanupPolicy] Load and parse policies from the config file. ### Returns List of CleanupPolicy objects ### Raises: - `InvalidConfigError`: If YAML is invalid or schema validation fails - `FileNotFoundError`: If config file doesn't exist - `OSError`: If file can't be read ### Example ```python loader = YamlConfigLoader("config.yaml") policies = loader.get_policies() for policy in policies: print(f"Policy: {policy.name}") print(f" Rules: {len(policy.rules)}") ``` ``` -------------------------------- ### Excluding Critical Artifacts with Filename Masks Source: https://github.com/devopshq/artifactory-cleanup/blob/master/_autodocs/errors.md Example of using the ExcludeFilename rule to prevent deletion of specific artifacts based on their names, such as versioned or documentation files. ```yaml - rule: ExcludeFilename masks: ['*:latest', '*:stable', '*.md'] ``` -------------------------------- ### BaseUrlSession Authentication Methods Source: https://github.com/devopshq/artifactory-cleanup/blob/master/_autodocs/session-loader-api.md Illustrates setting authentication for BaseUrlSession using either basic authentication with username/password or an API key via headers. ```python from requests.auth import HTTPBasicAuth session = BaseUrlSession("https://artifactory.com/artifactory") # Basic auth with credentials session.auth = HTTPBasicAuth("username", "password") # Or with API key via headers session.headers = {"X-JFrog-Art-Api": "your-api-key"} ``` -------------------------------- ### Modify Complete AQL Query Text Source: https://github.com/devopshq/artifactory-cleanup/blob/master/_autodocs/rule-base-api.md Shows how to modify the entire AQL query string, for example, to add sorting by creation date in descending order. ```python def aql_add_text(self, aql): # Add sorting return aql + ".sort({\"$desc\": [\"created\"]})" ``` -------------------------------- ### Custom Rule Validation Source: https://github.com/devopshq/artifactory-cleanup/blob/master/_autodocs/rule-base-api.md Provides an example of overriding the `check` method to add custom validation logic for a rule's configuration, such as verifying repository existence. ```python def check(self, *args, **kwargs): # Verify repository exists url = f"/api/storage/{self.repo}" r = self.session.get(url) r.raise_for_status() ``` -------------------------------- ### DeleteWithoutDownloads Rule Example Source: https://github.com/devopshq/artifactory-cleanup/blob/master/_autodocs/delete-rules.md Deletes artifacts that have never been downloaded. This rule checks both 'stat.downloads' and 'stat.remote_downloads'. It is often used in conjunction with age-based rules for added safety. ```yaml policies: - name: unused-artifacts rules: - rule: Repo name: artifacts-repo - rule: DeleteOlderThan days: 30 - rule: DeleteWithoutDownloads ``` -------------------------------- ### request Method Source: https://github.com/devopshq/artifactory-cleanup/blob/master/_autodocs/types.md Performs an HTTP request, prepending the base URL to relative URLs. Supports standard requests.Session methods like get, post, delete. ```APIDOC ## request ### Description Perform HTTP request, prepending base_url to relative URLs. ### Behavior - Relative URLs (starting with `/`) are joined with base_url - Absolute URLs (starting with `http://` or `https://`) are used as-is - All standard requests.Session methods work (get, post, delete, etc.) ### Example ```python session = BaseUrlSession("https://artifactory.example.com/artifactory") session.auth = ("username", "password") # Get repositories r = session.get("/api/repositories") # Execute AQL r = session.post("/api/search/aql", data="items.find()") # Delete artifact r = session.delete("/my-repo/path/to/artifact.jar") ``` ``` -------------------------------- ### BaseUrlSession Constructor Source: https://github.com/devopshq/artifactory-cleanup/blob/master/_autodocs/session-loader-api.md Creates a new BaseUrlSession with automatic base URL prepending. Authentication can be set after session creation. ```APIDOC ## BaseUrlSession Constructor Creates a new session with automatic base URL prepending. ### Parameters - `base_url` (str): The base URL. Trailing slash is added automatically if missing. ### Example ```python from artifactory_cleanup.base_url_session import BaseUrlSession from requests.auth import HTTPBasicAuth session = BaseUrlSession("https://artifactory.example.com/artifactory") session.auth = HTTPBasicAuth("username", "password") ``` ``` -------------------------------- ### View Registered Rule Keys Source: https://github.com/devopshq/artifactory-cleanup/blob/master/_autodocs/public-api-index.md Import the registry and print the keys of all registered rules. This is useful for verifying that built-in rules have been loaded correctly. ```python from artifactory_cleanup.loaders import registry # All built-in rules are already registered print(registry.rules.keys()) # dict_keys(['Repo', 'RepoList', 'RepoByMask', 'PropertyEq', 'PropertyNeq', # 'DeleteOlderThan', 'DeleteWithoutDownloads', ...]) ``` -------------------------------- ### Initialize BaseUrlSession Source: https://github.com/devopshq/artifactory-cleanup/blob/master/_autodocs/types.md Create a session object with the base URL for Artifactory. The trailing slash is automatically added. ```python session = BaseUrlSession("https://artifactory.example.com/artifactory") ``` -------------------------------- ### AQL Property-Based Filters Source: https://github.com/devopshq/artifactory-cleanup/blob/master/_autodocs/rule-base-api.md Shows how to filter artifacts using custom properties, including equality checks and pattern matching. ```python {"@key": {"$eq": "value"}} # Property equals ``` ```python {"@key": {"$nmatch": "*pattern*"}} # Property doesn't match ``` -------------------------------- ### HTTPError 401 Unauthorized Example Source: https://github.com/devopshq/artifactory-cleanup/blob/master/_autodocs/errors.md Represents an HTTP 401 error, typically caused by invalid credentials or API keys. Solutions involve verifying configuration and permissions. ```text requests.exceptions.HTTPError: 401 Client Error: Unauthorized ``` -------------------------------- ### Construct Artifact Full Path Source: https://github.com/devopshq/artifactory-cleanup/blob/master/_autodocs/types.md Combine repository, path, and name components to form the artifact's full path. Handles special cases for root artifacts and folders. ```python # Full path: my-repo/app/v1.0/app-1.0.jar full_path = f"{artifact['repo']}/{artifact['path']}/{artifact['name']}" ``` -------------------------------- ### Specify Configuration File using Environment Variable Source: https://github.com/devopshq/artifactory-cleanup/blob/master/README.md Runs the artifactory-cleanup tool using a custom configuration file specified via the ARTIFACTORY_CLEANUP_CONFIG_FILE environment variable. ```bash # Specify config filename using environment variable export ARTIFACTORY_CLEANUP_CONFIG_FILE=artifactory-cleanup.yaml artifactory-cleanup --config artifactory-cleanup.yaml ``` -------------------------------- ### Create Custom Rule: Keep Minimum Artifacts Source: https://github.com/devopshq/artifactory-cleanup/blob/master/_autodocs/rule-base-api.md An example of a custom rule that ensures a minimum number of the newest artifacts are always kept in a repository, regardless of their age. ```python from datetime import timedelta, date from artifactory_cleanup.rules.base import Rule, ArtifactsList from artifactory_cleanup import register class KeepMinimumArtifacts(Rule): """Keep at least N artifacts in repository regardless of age.""" def __init__(self, minimum: int): self.minimum = minimum def aql_add_filter(self, filters): # Get all items return filters def filter(self, artifacts: ArtifactsList) -> ArtifactsList: # Sort by creation date, newest first artifacts.sort(key=lambda x: x["created"], reverse=True) # Keep the minimum number of newest artifacts if len(artifacts) <= self.minimum: artifacts.remove(artifacts[:]) return artifacts # Mark oldest items for deletion artifacts_to_keep = artifacts[:self.minimum] artifacts.remove(artifacts_to_keep) return artifacts ``` -------------------------------- ### Specify Configuration File Source: https://github.com/devopshq/artifactory-cleanup/blob/master/README.md Runs the artifactory-cleanup tool using a custom configuration file specified via the --config flag. ```bash # Specify config filename artifactory-cleanup --config artifactory-cleanup.yaml ``` -------------------------------- ### Combining AQL Filters with AND Source: https://github.com/devopshq/artifactory-cleanup/blob/master/_autodocs/rule-base-api.md Shows how to combine multiple AQL filters using the $and operator for more complex queries. ```python filters.append({ "$and": [ {"created": {"$lt": "2024-01-01"}}, {"stat.downloads": {"$eq": None}} ] }) ``` -------------------------------- ### Catching HTTP Errors During Artifact Retrieval Source: https://github.com/devopshq/artifactory-cleanup/blob/master/_autodocs/errors.md Handle HTTPError exceptions when fetching artifacts. This example shows how to check for common status codes like 401 (Unauthorized) and 404 (Not Found). ```python from requests import HTTPError try: artifacts = policy.get_artifacts() except HTTPError as e: if e.response.status_code == 401: print("Authentication failed") elif e.response.status_code == 404: print("Repository not found") else: print(f"HTTP {e.response.status_code}: {e}") ``` -------------------------------- ### DeleteEmptyFolders Rule Example Source: https://github.com/devopshq/artifactory-cleanup/blob/master/_autodocs/delete-rules.md Removes empty directory folders within a repository. This rule is useful for cleaning up hierarchies after artifacts have been deleted, especially in specific repository types like Conan. ```yaml policies: - name: remove-empty-folders rules: - rule: Repo name: conan-repo - rule: DeleteEmptyFolders ``` -------------------------------- ### YamlConfigLoader Constructor Source: https://github.com/devopshq/artifactory-cleanup/blob/master/_autodocs/session-loader-api.md Creates a YamlConfigLoader for the specified YAML configuration file. ```APIDOC ## YamlConfigLoader Constructor Create a loader for the specified YAML config file. ### Parameters - `filepath` (str or Path): Path to config file ### Example ```python from artifactory_cleanup.loaders import YamlConfigLoader loader = YamlConfigLoader("artifactory-cleanup.yaml") ``` ``` -------------------------------- ### DeleteNotUsedSince Rule Example Source: https://github.com/devopshq/artifactory-cleanup/blob/master/_autodocs/delete-rules.md Deletes artifacts not accessed (downloaded) for a specified number of days, or artifacts that were never downloaded and are older than the specified days. This rule considers both last-downloaded and creation dates. ```yaml policies: - name: active-usage-cleanup rules: - rule: Repo name: cache-repo - rule: DeleteNotUsedSince days: 60 ``` ```python policy = CleanupPolicy( "active-usage-cleanup", Repo("cache-repo"), DeleteNotUsedSince(days=60) ) ``` -------------------------------- ### Apply Rule to a List of Repositories Source: https://github.com/devopshq/artifactory-cleanup/blob/master/README.md Applies a cleanup rule to a specified list of repositories. ```yaml - rule: RepoList repos: - repo1 - repo2 - repo3 ``` -------------------------------- ### HTTPError 403 Forbidden Example Source: https://github.com/devopshq/artifactory-cleanup/blob/master/_autodocs/errors.md Represents an HTTP 403 error, signifying that the user lacks the necessary permissions to perform an operation. Solutions involve checking user roles and repository access. ```text HTTPError: 403 Forbidden ``` -------------------------------- ### Basic Configuration File Structure Source: https://github.com/devopshq/artifactory-cleanup/blob/master/_autodocs/configuration.md Defines the fundamental structure of the `artifactory-cleanup.yaml` configuration file, including server connection details and policy definitions. ```yaml artifactory-cleanup: server: https://artifactory.example.com/artifactory user: $ARTIFACTORY_USERNAME password: $ARTIFACTORY_PASSWORD policies: - name: Policy Name rules: - rule: RuleName parameter: value ``` -------------------------------- ### DeleteByRegexpName Rule Examples Source: https://github.com/devopshq/artifactory-cleanup/blob/master/_autodocs/delete-rules.md Deletes artifacts whose filenames match a given regular expression pattern. The regex is applied to the artifact's name using `re.match()`, operating in-memory after an AQL query. ```yaml policies: - name: delete-temp-builds rules: - rule: Repo name: builds-repo - rule: DeleteByRegexpName regex_pattern: '.*-temp-.*' ``` ```python policy = CleanupPolicy( "delete-debug-builds", Repo("builds-repo"), DeleteByRegexpName(regex_pattern=r'.*-debug-\d+\.jar$') ) ``` -------------------------------- ### DeleteOlderThan Rule Example Source: https://github.com/devopshq/artifactory-cleanup/blob/master/_autodocs/delete-rules.md Deletes artifacts older than a specified number of days. This rule adds an AQL filter based on the artifact's creation date. It's efficient as it operates at the AQL level. ```yaml policies: - name: old-artifacts rules: - rule: Repo name: my-repo - rule: DeleteOlderThan days: 30 ``` ```python policy = CleanupPolicy( "old-artifacts", Repo("my-repo"), DeleteOlderThan(days=30) ) ``` -------------------------------- ### Dry-run vs. Destroy Mode Logging Source: https://github.com/devopshq/artifactory-cleanup/blob/master/_autodocs/configuration.md Demonstrates the difference in output between dry-run mode (default) and destroy mode. Always test with dry-run first to ensure correct behavior before enabling deletion. ```bash # Dry run (default) artifactory-cleanup # Output: "DEBUG - we would delete '...'" ``` ```bash # Actually delete artifactory-cleanup --destroy # Output: "DESTROY MODE - delete '...'" ``` -------------------------------- ### YamlConfigLoader.get_connection Source: https://github.com/devopshq/artifactory-cleanup/blob/master/_autodocs/session-loader-api.md Loads and parses connection details from the YAML configuration file. ```APIDOC ## YamlConfigLoader.get_connection() → Tuple[str, str, str, str] Load and parse connection details from the config file. ### Returns A tuple containing connection details (e.g., host, port, username, password). ### Raises: - `InvalidConfigError`: If YAML is invalid or schema validation fails - `FileNotFoundError`: If config file doesn't exist - `OSError`: If file can't be read ``` -------------------------------- ### Load Custom Rules from Python File (CLI) Source: https://github.com/devopshq/artifactory-cleanup/blob/master/README.md Connects and uses custom cleanup rules defined in a Python file when running the artifactory-cleanup CLI. ```bash # Not satisfied with built-in rules? Write your own rules in python and connect them! artifactory-cleanup --load-rules=myrule.py ``` -------------------------------- ### Load Cleanup Policies from YAML Source: https://github.com/devopshq/artifactory-cleanup/blob/master/_autodocs/session-loader-api.md Use YamlConfigLoader to load and parse cleanup policies from a configuration file. It validates the YAML and schema, initializing rule objects. ```python from artifactory_cleanup.loaders import YamlConfigLoader loader = YamlConfigLoader("config.yaml") policies = loader.get_policies() for policy in policies: print(f"Policy: {policy.name}") print(f" Rules: {len(policy.rules)}") ``` -------------------------------- ### Apply cleanup to multiple repositories Source: https://github.com/devopshq/artifactory-cleanup/blob/master/_autodocs/README.md Configure rules to apply cleanup policies to a list of repositories, deleting artifacts older than 7 days. ```yaml rules: - rule: RepoList repos: [snapshots-1, snapshots-2, snapshots-3] - rule: DeleteOlderThan days: 7 ``` -------------------------------- ### Specify Configuration File Path Source: https://github.com/devopshq/artifactory-cleanup/blob/master/_autodocs/configuration.md Use the --config flag to specify the path to a YAML configuration file containing cleanup policies. This is optional, with a default file name if not provided. ```bash artifactory-cleanup --config path/to/config.yaml ```