@Override public AwsToken load(AwsCredentials awsCredentials) throws Exception { AmazonECR amazonECR = new AmazonECRClient(new AWSCredentialsProvider() { @Override public AWSCredentials getCredentials() { return awsCredentials; } @Override public void refresh() { } }); amazonECR.setRegion(RegionUtils.getRegion(awsCredentials.getRegion())); GetAuthorizationTokenResult authorizationToken = amazonECR.getAuthorizationToken(new GetAuthorizationTokenRequest()); List<AuthorizationData> authorizationData = authorizationToken.getAuthorizationData(); Assert.isTrue(!CollectionUtils.isEmpty(authorizationData), "authorizationData is null or empty for token " + authorizationToken); AuthorizationData data = authorizationData.get(0); byte[] decode = Base64.getDecoder().decode(data.getAuthorizationToken()); String token = new String(decode); String[] split = token.split(":"); log.info("about to connect to AWS endpoint: {}", data.getProxyEndpoint()); return AwsToken.builder().username(split[0]).password(split[1]) .expiresAt(data.getExpiresAt()).proxyEndpoint(data.getProxyEndpoint()).build(); }
@VisibleForTesting String getAwsAuthorizationToken(String accessKeyId, String secretAccessKey) { try { AWSCredentials credentials = new BasicAWSCredentials(accessKeyId, secretAccessKey); AmazonECRClient amazonECRClient = new AmazonECRClient(credentials); GetAuthorizationTokenResult tokenResult = amazonECRClient.getAuthorizationToken(new GetAuthorizationTokenRequest()); List<AuthorizationData> authData = tokenResult.getAuthorizationData(); if (!authData.isEmpty()) { return authData.get(0).getAuthorizationToken(); } LOG.warn("Failed to retrieve AWS ECR token"); } catch (AmazonECRException e) { LOG.warn(e.getLocalizedMessage()); } return null; }
/** * @param credentials {@link AWSCredentials} to use. * @return {@link AmazonECRClient} configured to use the proxy configured on Jenkins. */ public AmazonECRClient getAmazonECRClientWithProxy(AWSCredentials credentials) { ClientConfiguration conf = new ClientConfiguration(); Jenkins j = Jenkins.getInstance(); if (j != null && j.proxy != null) { conf.setProxyHost(j.proxy.name); conf.setProxyPort(j.proxy.port); conf.setProxyUsername(j.proxy.getUserName()); conf.setProxyPassword(j.proxy.getPassword()); } return new AmazonECRClient(credentials, conf); }