DEV Community

Stephen Bawks
Stephen Bawks

Posted on

Pulumi - Python - Docker

I do love Pulumi and Python. Working on a few things lately and fought with the Docker build options, getting it working the way I wanted.

The Docker module for Pulumi does not have the greatest documentation and I felt the need to write this up real quick hopefully someone can find it useful.


import json

import pulumi
import pulumi_aws as aws
import pulumi_aws_native as aws_native
import pulumi_docker as docker

# ----------------------------------------------------------------
# Pull Stack Variables from Config File
# ----------------------------------------------------------------

CONFIG = pulumi.Config()
account_id = (aws.get_caller_identity()).account_id
region = (aws.get_region()).name



untagged_days = 14

life_cycle_policy = json.dumps({
    "rules": [
        {
            "rulePriority": 1,
            "description": "Expire images older than 30 days",
            "selection": {
                "tagStatus": "untagged",
                "countType": "sinceImagePushed",
                "countUnit": "days",
                "countNumber": untagged_days
            },
            "action": {
                "type": "expire"
            }
        }
    ]
})

# https://www.pulumi.com/registry/packages/aws-native/api-docs/ecr/repository/
ecr_repository = aws_native.ecr.Repository(
    "ecr-repository",
    image_scanning_configuration=aws_native.ecr.RepositoryImageScanningConfigurationArgs(
        scan_on_push=True
    ),
    lifecycle_policy=aws_native.ecr.RepositoryLifecyclePolicyArgs(
        lifecycle_policy_text=life_cycle_policy
    )
)

# https://www.pulumi.com/registry/packages/aws/api-docs/ecr/getauthorizationtoken/
ecr_token = aws.ecr.get_authorization_token()

# https://www.pulumi.com/registry/packages/docker/api-docs/image/
container = docker.Image(
    "build-container",
    image_name=ecr_repository.repository_uri,
    build=docker.DockerBuild(
        context="./src/api"
    ),
    registry = docker.ImageRegistry(
        server = ecr_repository.repository_uri.apply(lambda uri: uri.split("/")[0]),
        username = ecr_token.user_name,
        password = ecr_token.password,
    ),
    opts=pulumi.ResourceOptions(parent=ecr_repository)
)

Enter fullscreen mode Exit fullscreen mode

Top comments (0)