enforce_labels.bash 1.2 KB
Newer Older
1
#!/bin/bash
Jon Azpiazu's avatar
Jon Azpiazu committed
2
3
4
# From a given list of labels, check which of them are already defined in the provided docker image; if any of the labels
# is not defined, a new image with the same name is generated with the label(s) added.
# Labels already defined are not modified.
5

Jon Azpiazu's avatar
Jon Azpiazu committed
6
7
8
9
10
if [ "$#" -ne 1 ]; then
    echo "Usage: $0 IMAGE_NAME"
    exit 1
fi

11
12
image_name="$1"

Jon Azpiazu's avatar
Jon Azpiazu committed
13
# list of labels to be enforced
14
15
declare -A enforced_labels=( ["com.jfrog.artifactory.retention.maxCount"]="10" ["com.jfrog.artifactory.retention.maxDays"]="7")

Jon Azpiazu's avatar
Jon Azpiazu committed
16
if ! docker inspect --type=image "$1" > /dev/null ; then
17
18
19
20
    echo "Error: image does not exist"
    exit 0
fi

Jon Azpiazu's avatar
Jon Azpiazu committed
21
# check if every label is defined
Jon Azpiazu's avatar
Jon Azpiazu committed
22
23
24
for label in "${!enforced_labels[@]}" ; do
    if ! docker inspect -f "{{json .Config.Labels }}" "$image_name" | jq -e '.['\""$label"\"']' > /dev/null ; then
        echo "Key not found"
25
        echo "$label = ${enforced_labels[$label]}"
Jon Azpiazu's avatar
Jon Azpiazu committed
26
        # add missing label to the arguments to be provided to `docker build`
27
        label_args+=" --label $label=\"${enforced_labels[$label]}\""
Jon Azpiazu's avatar
Jon Azpiazu committed
28
    fi
29
30
done

Jon Azpiazu's avatar
Jon Azpiazu committed
31
# generate new image
Jon Azpiazu's avatar
Jon Azpiazu committed
32
if [ -n "${label_args+x}" ]; then
33
    run_command="echo \"FROM $image_name\" | docker build $label_args -t $image_name -"
34
    eval "$run_command"
35
fi