import os
from dotenv import load_dotenv
import pulumi
from pulumi import automation as auto
from pulumi_gcp import compute
# Load environment variables from .env
load_dotenv(r"C:\Users\USER\OneDrive\Desktop\scaling_considerations\prod\deployment_manager\.env")
# 1. Define the Pulumi program
def pulumi_program():
# Create a VPC network
compute_network = compute.Network("network", auto_create_subnetworks=True)
# Allow HTTP and SSH access
compute_firewall = compute.Firewall(
"firewall",
network=compute_network.self_link,
allows=[compute.FirewallAllowArgs(protocol="tcp", ports=["22", "80"])],
source_ranges=["0.0.0.0/0"],
)
# Reserve a static external IP
instance_addr = compute.Address("address", region=os.environ["GCP_REGION"])
# Define instance metadata to run a Docker container
container_metadata = {
"gce-container-declaration": """
spec:
containers:
- name: hello
image: nginxdemos/hello
ports:
- containerPort: 80
restartPolicy: Always
""",
"google-logging-enabled": "true",
}
# Launch the VM with Container-Optimized OS and the container
compute_instance = compute.Instance(
"instance",
machine_type="e2-medium",
metadata=container_metadata,
boot_disk=compute.InstanceBootDiskArgs(
initialize_params=compute.InstanceBootDiskInitializeParamsArgs(
image="cos-cloud/cos-stable"
)
),
network_interfaces=[
compute.InstanceNetworkInterfaceArgs(
network=compute_network.id,
access_configs=[
compute.InstanceNetworkInterfaceAccessConfigArgs(
nat_ip=instance_addr.address
)
],
)
],
zone=os.environ["GCP_ZONE"],
service_account=compute.InstanceServiceAccountArgs(
scopes=["
https://www.googleapis.com/auth/cloud-platform"]
),
opts=pulumi.ResourceOptions(depends_on=[compute_firewall]),
)
# Export outputs
pulumi.export("instanceName", compute_instance.name)
pulumi.export("instanceIP", instance_addr.address)
# 2. Use the Automation API with env values
def main():
stack_name = "dev"
project_name = "gcp-vm-docker"
# Load environment variables
gcp_project = os.environ["GCP_PROJECT"]
gcp_region = os.environ["GCP_REGION"]
gcp_zone = os.environ["GCP_ZONE"]
# Create or select a stack
stack = auto.create_or_select_stack(stack_name=stack_name,
project_name=project_name,
program=pulumi_program,)
print("Installing plugins...")
stack.workspace.install_plugin("gcp", "v6.0.0") # Adjust version as needed
print("Setting config from environment variables...")
stack.set_config("gcp:project", auto.ConfigValue(value=gcp_project))
stack.set_config("gcp:region", auto.ConfigValue(value=gcp_region))
stack.set_config("gcp:zone", auto.ConfigValue(value=gcp_zone))
print("Refreshing stack...")
stack.refresh(on_output=print)
print("Updating stack...")
up_result = stack.up(on_output=print)
print(f"Instance name: {up_result.outputs['instanceName'].value}")
print(f"Instance IP: {up_result.outputs['instanceIP'].value}")
if
name == "__main__":
main()