Merge "Pass common maven options to deploy file builder"
[releng/global-jjb.git] / shell / docker-login.sh
1 #!/bin/bash
2 # SPDX-License-Identifier: EPL-1.0
3 ##############################################################################
4 # Copyright (c) 2017 The Linux Foundation and others.
5 #
6 # All rights reserved. This program and the accompanying materials
7 # are made available under the terms of the Eclipse Public License v1.0
8 # which accompanies this distribution, and is available at
9 # http://www.eclipse.org/legal/epl-v10.html
10 ##############################################################################
11
12 # Log into a custom hosted docker registry and / or docker.io
13
14 # $DOCKER_REGISTRY : Optional
15 #                    Jenkins global variable should be defined
16 #                    If set, then this is the base IP or FQDN that will be used
17 #                    for logging into the custom docker registry
18 #                    ex: nexus3.example.com
19 #
20 # $REGISTRY_PORTS  : Required if DOCKER_REGISTRY is set
21 #                    Jenkins global variable should be defined (space separated)
22 #                    Listing of all the registry ports to login to
23 #                    ex: 10001 10002 10003 10004
24 #
25 # $SETTINGS_FILE   : Job level variable with maven settings file location
26 #
27 # $DOCKERHUB_EMAIL : Optional
28 #                    Jenkins global variable that defines the email address that
29 #                    should be used for logging into DockerHub
30 #                    If defined than an attempt to login to docker hub will
31 #                    happen
32
33 # Ensure we fail the job if any steps fail
34 set -eu -o pipefail
35
36 # Execute the credential lookup and login to the registry
37 do_login() {
38     echo "$1"
39     CREDENTIAL=$(xmlstarlet sel -N "x=http://maven.apache.org/SETTINGS/1.0.0" \
40         -t -m "/x:settings/x:servers/x:server[starts-with(x:id, '${1}')]" \
41         -v x:username -o ":" -v x:password \
42         "$SETTINGS_FILE")
43
44     USER=$(echo "$CREDENTIAL" | cut -f1 -d:)
45     PASS=$(echo "$CREDENTIAL" | cut -f2 -d:)
46
47     if [ -z "$USER" ]
48     then
49         echo "ERROR: No user provided"
50         return 1
51     fi
52
53     if [ -z "$PASS" ]
54     then
55         echo "ERROR: No password provided"
56         return 1
57     fi
58
59     docker login -u "$USER" -p "$PASS" -e "$2" "$1"
60 }
61
62 if [ "${DOCKER_REGISTRY:-none}" != 'none' ]
63 then
64     for PORT in $REGISTRY_PORTS
65     do
66         REGISTRY="${DOCKER_REGISTRY}:${PORT}"
67
68         # docker login requests an email address if nothing is passed to it
69         # Nexus, however, does not need this and ignores the value
70         do_login "$REGISTRY" none
71     done
72 fi
73
74 # Attempt to login to docker.io only if $DOCKERHUB_EMAIL is configured
75 if [ "${DOCKERHUB_EMAIL:-none}" != 'none' ]
76 then
77     do_login docker.io "$DOCKERHUB_EMAIL"
78 fi