I observe a scenario when I'm writing a Jenkinsfile to first authenticate a session on AWS and then push a dockerfile to designated ECR. The below code block works fine and pushes the image to ECR:
stage('build and push images') {
steps {
sh """
sh assume_role.sh
source /tmp/${assume_role_session_name}
aws ecr get-login --region ${aws_region} --registry-ids ${ROLEARN} --no-include-email
docker build -t my-docker-image .
docker tag my-docker-image:latest ${ROLEARN}.dkr.ecr.${aws_region}.amazonaws.com/${ECR_name}:${ECS_TAG_VERSION}
docker push ${ROLEARN}.dkr.ecr.${aws_region}.amazonaws.com/${ECR_name}:${ECS_TAG_VERSION}
docker rmi -f my-docker-image:latest
"""
}
}
However, when I divided each step with an individual sh
command (like below), docker push
failed because the Jenkins agent hasn't been authenticated, which means the authentication token isn't passed to docker push
command line.
stage('build and push images') {
steps {
sh "assume_role.sh"
sh "source /tmp/${assume_role_session_name}"
sh "aws ecr get-login --region ${aws_region} --registry-ids ${ROLEARN} --no-include-email"
sh "docker build -t my-docker-image . "
sh "docker tag my-docker-image:latest ${ROLEARN}.dkr.ecr.${aws_region}.amazonaws.com/${ECR_name}:${ECS_TAG_VERSION}"
sh "docker push ${ROLEARN}.dkr.ecr.${aws_region}.amazonaws.com/${ECR_name}:${ECS_TAG_VERSION}"
sh "docker rmi -f my-docker-image:latest"
}
}
Thus, I'm suspecting that the each sh
starts a new session in Jenkins steps, in between which, authentication tokens cannot be passed through. I don't know whether my guess is correct and how to find evidence to support my guess.