Skip to content

Instantly share code, notes, and snippets.

@hannesl
Last active December 4, 2024 09:03
Show Gist options
  • Save hannesl/a0d8a264c853553f2b8821789422cec1 to your computer and use it in GitHub Desktop.
Save hannesl/a0d8a264c853553f2b8821789422cec1 to your computer and use it in GitHub Desktop.
Bitbucket pipeline example where Bitbucket is used as Identity Provider to connect to AWS ECR – and to pass access to a remote machine through SSH
pipelines:
custom:
build-and-deploy:
- step:
name: Build and Push Docker image
image: amazon/aws-cli # Convenience image with aws-cli.
oidc: true # Required for AWS CLI to use OIDC token.
services:
- docker
script:
# $AWS_REGION and $AWS_REGISTRY are expected to be set as pipeline variables.
- export AWS_ROLE_ARN=arn:aws:iam::<accound-id>:role/<role-name>
- export AWS_WEB_IDENTITY_TOKEN_FILE=$(pwd)/web-identity-token
- echo $BITBUCKET_STEP_OIDC_TOKEN > $(pwd)/web-identity-token
- export AWS_ECR_REPO=$AWS_ECR_REGISTRY/<client>/<repository>
- aws ecr get-login-password | docker login --username AWS --password-stdin $AWS_ECR_REGISTRY
- export DOCKER_BUILDKIT=1
- docker build --cache-from $AWS_ECR_REPO:latest -f docker/app/Dockerfile -t <image-name> .
- docker tag <image-name> $AWS_ECR_REPO:"build-$BITBUCKET_BUILD_NUMBER"
- docker push $AWS_ECR_REPO:"build-$BITBUCKET_BUILD_NUMBER"
- docker tag jernhusen-se $AWS_ECR_REPO:latest
- docker push $AWS_ECR_REPO:latest
- step:
name: Deploy to remote host
image: amazon/aws-cli
oidc: true
trigger: manual
script:
# $AWS_REGION is expected to be set as pipeline variables.
- yum -y install openssh-clients
- export AWS_ROLE_ARN=arn:aws:iam::<accound-id>:role/<role-name>
- export AWS_WEB_IDENTITY_TOKEN_FILE=$(pwd)/web-identity-token
- echo $BITBUCKET_STEP_OIDC_TOKEN > $(pwd)/web-identity-token
# DOCKER_PASSWORD is a short-lived token.
- export DOCKER_PASSWORD=$(aws ecr get-login-password --region $AWS_REGION)
# Space is intentional prevent password from being logged.
- ssh <host> " echo $DOCKER_PASSWORD | docker login $AWS_ECR_REGISTRY --username AWS --password-stdin"
# Basic example, in reality Docker Compose or Kubernetes might be used.
- ssh <host> "docker pull $AWS_ECR_REGISTRY/<client>/<repository>:latest"
- ssh <host> "docker stop <container-name>"
- ssh <host> "docker rm <container-name>"
- ssh <host> "docker run --name=<container-name> -d <image-name>"
- ssh <host> "docker logout $AWS_ECR_REGISTRY"
@hannesl
Copy link
Author

hannesl commented Dec 3, 2024

The trick with the deploy step is that the server doesn't have to run any aws commands since it gets a temporary password through SSH. Hence, it doesn't need to store any AWS credentials.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment