82 lines
3.1 KiB
Python
82 lines
3.1 KiB
Python
import pulumi
|
|
import pulumi_docker as docker
|
|
import json
|
|
import os
|
|
|
|
# Load the JSON configuration file
|
|
try:
|
|
with open("config.json", "r") as f:
|
|
containers_data = json.load(f)
|
|
except FileNotFoundError:
|
|
raise Exception("Error: 'config.json' file not found.")
|
|
|
|
# Create the network
|
|
try:
|
|
network = docker.Network("testNetwork")
|
|
|
|
except Exception as e:
|
|
pulumi.log.error(f"Failed to create network: {e}")
|
|
network = None
|
|
|
|
# Create containers
|
|
for container in containers_data.get("containers", []):
|
|
instances = container.get("instances", 1)
|
|
for i in range(instances):
|
|
container_name = f"{container['name']}-{i}" if instances > 1 else container["name"]
|
|
|
|
# Configure volumes
|
|
volumes = {}
|
|
for volume in container.get("volumes", []):
|
|
try:
|
|
if "volume_name" in volume and volume["volume_name"] not in volumes:
|
|
volumes[volume["volume_name"]] = docker.Volume(volume["volume_name"])
|
|
except Exception as e:
|
|
pulumi.log.error(f"Failed to create volume {volume.get('volume_name')}: {e}")
|
|
volumes_config = []
|
|
try:
|
|
if "volumes" in container:
|
|
volumes_config = [
|
|
docker.ContainerVolumeArgs(
|
|
container_path=volume["container_path"],
|
|
volume_name=volumes[volume["volume_name"]].name
|
|
) if "volume_name" in volume else
|
|
docker.ContainerVolumeArgs(
|
|
container_path=volume["container_path"],
|
|
host_path=os.path.abspath(volume["host_path"])
|
|
)
|
|
for volume in container["volumes"]
|
|
]
|
|
except KeyError as e:
|
|
pulumi.log.warn(f"Missing key in volume configuration: {e}")
|
|
except Exception as e:
|
|
pulumi.log.error(f"Error configuring volumes for container {container_name}: {e}")
|
|
|
|
# Create the container
|
|
try:
|
|
container_resource = docker.Container(
|
|
container_name,
|
|
image=container["image"],
|
|
hostname=container_name,
|
|
envs=[
|
|
f"{key}={value}" for key, value in container.get("envs", {}).items()
|
|
] if "envs" in container else [],
|
|
ports=[
|
|
docker.ContainerPortArgs(
|
|
internal=port["internal"],
|
|
external=port["external"] + i
|
|
) for port in container.get("ports", [])
|
|
] if "ports" in container else [],
|
|
volumes=volumes_config,
|
|
network_mode=network.name if network else None,
|
|
)
|
|
ports = container.get("ports", [])
|
|
if ports:
|
|
for port in ports:
|
|
external_port = port["external"] + i
|
|
pulumi.export(
|
|
f"{container_name}_url",
|
|
f"http://localhost:{external_port}"
|
|
)
|
|
except Exception as e:
|
|
pulumi.log.error(f"Failed to create container {container_name}: {e}")
|