Richard Felkl | e90ef1c | 2017-12-08 00:13:56 +0100 | [diff] [blame] | 1 | /** |
| 2 | * |
| 3 | * Mirror Docker images |
| 4 | * |
| 5 | * Expected parameters: |
| 6 | * TARGET_REGISTRY_CREDENTIALS_ID Credentials for target Docker Registry |
| 7 | * TARGET_REGISTRY Target Docker Registry name |
| 8 | * REGISTRY_URL Target Docker Registry URL |
| 9 | * IMAGE_TAG Tag to use when pushing images |
| 10 | * IMAGE_LIST List of images to mirror |
| 11 | * |
| 12 | */ |
| 13 | import java.util.regex.Pattern; |
| 14 | |
| 15 | def common = new com.mirantis.mk.Common() |
| 16 | |
| 17 | @NonCPS |
| 18 | def getImageName(String image) { |
| 19 | def regex = Pattern.compile('(?:.+/)?([^:]+)(?::.+)?') |
| 20 | def matcher = regex.matcher(image) |
| 21 | if(matcher.find()){ |
| 22 | def imageName = matcher.group(1) |
| 23 | return imageName |
| 24 | }else{ |
| 25 | throw new IllegalFormatException("Wrong format of image name.") |
| 26 | } |
| 27 | } |
| 28 | |
| 29 | node("docker") { |
| 30 | try { |
| 31 | stage("Mirror Docker Images"){ |
| 32 | def creds = common.getPasswordCredentials(TARGET_REGISTRY_CREDENTIALS_ID) |
| 33 | sh "docker login --username=${creds.username} --password=${creds.password.toString()} ${REGISTRY_URL}" |
| 34 | def images = IMAGE_LIST.tokenize('\n') |
| 35 | def imageName |
| 36 | for (image in images){ |
| 37 | sh "echo ${image}" |
| 38 | imageName = getImageName(image) |
| 39 | sh "docker pull ${image}" |
| 40 | sh "docker tag ${image} ${TARGET_REGISTRY}/${imageName}:${IMAGE_TAG}" |
| 41 | sh "docker push ${TARGET_REGISTRY}/${imageName}:${IMAGE_TAG}" |
| 42 | } |
| 43 | } |
| 44 | } catch (Throwable e) { |
| 45 | // If there was an error or exception thrown, the build failed |
| 46 | currentBuild.result = "FAILURE" |
| 47 | throw e |
| 48 | } |
| 49 | } |