-
Notifications
You must be signed in to change notification settings - Fork 12
/
azure-acr-mirror-image-from-external-registry.sh
executable file
·89 lines (72 loc) · 2.51 KB
/
azure-acr-mirror-image-from-external-registry.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#!/usr/bin/env bash
################################################################################
# Script Name : azure-acr-mirror-image-from-external-registry.sh
# Description : Used to mirror images from external registries to an ACR (Azure Container Registry)
# Args : EXTERNAL_CONTAINER_REGISTRY REPOSITORY IMAGE_TAG AZURE_CONTAINER_REGISTRY [IMAGE_ARCHITECTURE]
# Author : Wellington Ozorio <[email protected]>
################################################################################
set -e
function log() {
local MESSAGE="${1}"
echo "${MESSAGE}" 1>&2
}
function usage() {
log "ERROR: Missing or invalid arguments"
log "Usage example: ${0} EXTERNAL_CONTAINER_REGISTRY REPOSITORY IMAGE_TAG AZURE_CONTAINER_REGISTRY [IMAGE_ARCHITECTURE]"
exit 1
}
function check_image_exists() {
local IMAGE_EXISTS
IMAGE_EXISTS=$(
az acr repository show \
--name "${AZURE_CONTAINER_REGISTRY}" \
--image "${REPOSITORY}:${IMAGE_TAG}" \
--query name \
2>/dev/null || true
)
echo "${IMAGE_EXISTS}"
}
function tag_image() {
buildah tag "${ECR_TAG}" "${ACR_TAG}"
}
function pull_image() {
buildah pull --arch "${IMAGE_ARCHITECTURE}" "${ECR_TAG}"
tag_image
}
function logon_to_acr() {
# The `addSpnToEnvironment` property must be set to `true` in the AzureCLI@2 pipeline task
# for the servicePrincipalId and servicePrincipalKey environment variables to be available
# shellcheck disable=SC2154
buildah login \
--username "${servicePrincipalId}" \
--password "${servicePrincipalKey}" \
"${AZURE_CONTAINER_REGISTRY}"
}
function push_image_to_acr() {
local IMAGE_EXISTS
IMAGE_EXISTS=$(check_image_exists)
if [[ -n "${IMAGE_EXISTS}" ]]; then
log "INFO: Image already exists in the ACR! It can be used with the following annotation:"
log "${ACR_TAG}"
exit 0
fi
pull_image
logon_to_acr
buildah push "${ACR_TAG}"
log "INFO: Image successfully mirrored! It can be used with the following annotation:"
log "${ACR_TAG}"
}
function main() {
if [[ "${#}" -lt 4 || "${#}" -gt 5 ]]; then
usage
fi
EXTERNAL_CONTAINER_REGISTRY="${1}"
REPOSITORY="${2}"
IMAGE_TAG="${3}"
AZURE_CONTAINER_REGISTRY="${4}"
IMAGE_ARCHITECTURE="${5:-amd64}"
ECR_TAG="${EXTERNAL_CONTAINER_REGISTRY}/${REPOSITORY}:${IMAGE_TAG}"
ACR_TAG="${AZURE_CONTAINER_REGISTRY}/${REPOSITORY}:${IMAGE_TAG}"
push_image_to_acr
}
main "$@"