Nexus 3 使用 Groovy 脚本创建清理策略

Nexus 3 create clean up policy with Groovy script

我想使用 Groovy 为 Nexus 3 上的 Maven 和 docker 存储库创建清理策略。 到目前为止我找到的所有解决方案和示例都是清理脚本和清理任务。 我想用 Groovy 创建一个清理策略,将它附加到存储库(maven 或 docker)并使用该策略定期创建一个任务到 运行。

更新:这是新的解决方案。第一个 groovy 脚本创建策略并将其附加到 Docker 存储库,第二个 groovy 脚本正在创建 Docker 存储库

import org.sonatype.nexus.cleanup.storage.CleanupPolicyStorage

def createPolicy (policyName) {
    try {
        def policyStorage = container.lookup(CleanupPolicyStorage.class.getName())
        def cleanupPolicy = policyStorage.newCleanupPolicy()
        cleanupPolicy.setName(policyName)
        cleanupPolicy.setNotes('')
        cleanupPolicy.setMode('deletion')
        cleanupPolicy.setFormat('docker')
        cleanupPolicy.setCriteria(['regex': '.*SNAPSHOT'])
        policyStorage.add(cleanupPolicy)
    } catch (e) {
        log.info("Cleanup policy already exists, skipping...")
    }

}

def attachPolicy (policyName, repositoryName) {
    try {
        def repo = repository.repositoryManager.get(repositoryName)
        def cleanupPolicyAttribute = [policyName: [policyName].toSet()]
        def conf = repo.getConfiguration()
        conf.getAttributes().put("cleanup", cleanupPolicyAttribute)
        repo.stop()
        repo.update(conf)
        repo.start()
    } catch (e) {
        log.info("Attaching policy fail")
    }
}

createPolicy('dockerCleanupPolicy')
attachPolicy('dockerCleanupPolicy', 'docker-NameOfTheRepo')

我们使用此脚本创建存储库。请记住,在较旧的 nexus 版本中,您应该导入 import org.sonatype.nexus.repository.storage.WritePolicy 而不是 import org.sonatype.nexus.repository.config.WritePolicy

import org.sonatype.nexus.blobstore.api.BlobStoreManager
import org.sonatype.nexus.repository.config.WritePolicy

def createDockerHosted(repoName, repoHttpPort){
    try {
        repository.createDockerHosted(repoName, repoHttpPort, null, BlobStoreManager.DEFAULT_BLOBSTORE_NAME, true, false, WritePolicy.ALLOW)
    } catch (e) {
        log.info("Repo already exists, skipping...")
    }
}
createDockerHosted('docker-NameOfTheRepo', 5001)

旧的解决方案 找到了,这是你如何做的例子

import org.sonatype.nexus.cleanup.storage.CleanupPolicyStorage;
def policyStorage = container.lookup(CleanupPolicyStorage.class.getName());
def cleanupPolicy = policyStorage.newCleanupPolicy();
cleanupPolicy.setName('name');
cleanupPolicy.setNotes('');
cleanupPolicy.setMode('deletion');
cleanupPolicy.setFormat('raw');
cleanupPolicy.setCriteria(['lastBlobUpdated':'432000']);
policyStorage.add(cleanupPolicy);