Skip to content

Commit

Permalink
Return JSON in all apps, add comments
Browse files Browse the repository at this point in the history
  • Loading branch information
cnunciato committed Oct 17, 2022
1 parent 64eb8ee commit b234179
Show file tree
Hide file tree
Showing 11 changed files with 140 additions and 75 deletions.
11 changes: 9 additions & 2 deletions container-azure-csharp/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,18 @@

return await Pulumi.Deployment.RunAsync(() =>
{
// Import the program's configuration settings.
var config = new Config();
var appPath = config.Get("appPath") ?? "./app";
var imageName = config.Get("imageName") ?? "my-app";
var containerPort = config.GetInt32("containerPort") ?? 80;
var cpu = Math.Max(config.GetObject<double>("cpu"), 1.0);
var memory = Math.Max(config.GetObject<double>("memory"), 1.5);

// Create a resource group for the container registry.
var resourceGroup = new AzureNative.Resources.ResourceGroup("resource-group");

// Create a container registry.
var registry = new AzureNative.ContainerRegistry.Registry("registry", new()
{
ResourceGroupName = resourceGroup.Name,
Expand All @@ -25,15 +28,16 @@
},
});

// Fetch login credentials for the registry.
var credentials = AzureNative.ContainerRegistry.ListRegistryCredentials.Invoke(new()
{
ResourceGroupName = resourceGroup.Name,
RegistryName = registry.Name,
});

var registryUsername = credentials.Apply(result => result.Username!);
var registryPassword = credentials.Apply(result => result.Passwords[0]!.Value!);

// Create a container image for the service.
var image = new Docker.Image("image", new()
{
ImageName = Pulumi.Output.Format($"{registry.LoginServer}/{imageName}"),
Expand All @@ -47,12 +51,14 @@
},
});

// Use a random string to give the service a unique DNS name.
var dnsName = new Random.RandomString("dns-name", new()
{
Length = 8,
Special = false,
}).Result.Apply(result => $"{imageName}-{result.ToLower()}");

// Create a container group for the service that makes it publicly accessible.
var containerGroup = new AzureNative.ContainerInstance.ContainerGroup("container-group", new()
{
ResourceGroupName = resourceGroup.Name,
Expand Down Expand Up @@ -103,10 +109,11 @@
}
});

// Export the service's IP address, hostname, and fully-qualified URL.
return new Dictionary<string, object?>
{
["ipAddress"] = containerGroup.IpAddress.Apply(addr => addr!.Ip),
["hostname"] = containerGroup.IpAddress.Apply(addr => addr!.Fqdn),
["ip"] = containerGroup.IpAddress.Apply(addr => addr!.Ip),
["url"] = containerGroup.IpAddress.Apply(addr => $"http://{addr!.Fqdn}:{containerPort}"),
};
});
7 changes: 4 additions & 3 deletions container-azure-csharp/app/Dockerfile
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build
WORKDIR /app

WORKDIR /app
COPY *.csproj ./
RUN dotnet restore

COPY . ./
COPY . .
RUN dotnet publish -c Release -o out

FROM mcr.microsoft.com/dotnet/aspnet:6.0 as base

WORKDIR /app
COPY --from=build /app/out .

ENTRYPOINT ["dotnet", "App.dll"]
8 changes: 7 additions & 1 deletion container-azure-csharp/app/Program.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.MapGet("/", () => "Hello, world! 👋");
app.MapGet("/", async (context) =>
{
await context.Response.WriteAsJsonAsync(new
{
message = "Hello, world! 👋"
});
});

app.Run();
3 changes: 1 addition & 2 deletions container-azure-go/app/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,7 @@ WORKDIR /usr/src/app

COPY go.* ./
RUN go mod download

COPY . .
RUN go build -o /app

ENTRYPOINT /app
ENTRYPOINT ["/app"]
17 changes: 16 additions & 1 deletion container-azure-go/app/main.go
Original file line number Diff line number Diff line change
@@ -1,16 +1,31 @@
package main

import (
"encoding/json"
"fmt"
"log"
"net/http"
"os"
)

type AppResponse struct {
Message string `json:"message"`
}

func main() {

http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, world! 👋")
response := AppResponse{
Message: "Hello, world! 👋",
}

s, err := json.Marshal(response)
if err != nil {
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
}

w.Header().Set("Content-Type", "application/json")
fmt.Fprintf(w, string(s))
})

if err := http.ListenAndServe(fmt.Sprintf(":%s", os.Getenv("PORT")), nil); err != nil {
Expand Down
13 changes: 10 additions & 3 deletions container-azure-go/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import (
func main() {
pulumi.Run(func(ctx *pulumi.Context) error {

// Import the program's configuration settings.
cfg := config.New(ctx, "")
imageName := "my-app"
if param := cfg.Get("imageName"); param != "" {
Expand All @@ -33,16 +34,18 @@ func main() {
if param := cfg.GetFloat64("cpu"); param != 0 {
cpu = param
}
memory := 1.0
memory := 1.5
if param := cfg.GetFloat64("memory"); param != 0 {
memory = param
}

// Create a resource group for the container registry.
resourceGroup, err := resources.NewResourceGroup(ctx, "resource-group", nil)
if err != nil {
return err
}

// Create a container registry.
registry, err := containerregistry.NewRegistry(ctx, "registry", &containerregistry.RegistryArgs{
ResourceGroupName: resourceGroup.Name,
AdminUserEnabled: pulumi.Bool(true),
Expand All @@ -54,13 +57,15 @@ func main() {
return err
}

// Fetch login credentials for the registry.
credentials := containerregistry.ListRegistryCredentialsOutput(ctx, containerregistry.ListRegistryCredentialsOutputArgs{
ResourceGroupName: resourceGroup.Name,
RegistryName: registry.Name,
})
registryUsername := credentials.Username().Elem()
registryPassword := credentials.Passwords().Index(pulumi.Int(0)).Value().Elem()

// Create a container image for the service.
image, err := docker.NewImage(ctx, "image", &docker.ImageArgs{
ImageName: pulumi.Sprintf("%s/%s", registry.LoginServer, imageName),
Build: docker.DockerBuildArgs{
Expand All @@ -76,18 +81,19 @@ func main() {
return err
}

// Use a random string to give the service a unique DNS name.
dnsNameSuffix, err := random.NewRandomString(ctx, "dns-name-suffix", &random.RandomStringArgs{
Length: pulumi.Int(8),
Special: pulumi.Bool(false),
})
if err != nil {
return err
}

dnsName := dnsNameSuffix.Result.ApplyT(func(result string) string {
return fmt.Sprintf("%s-%s", imageName, strings.ToLower(result))
}).(pulumi.StringOutput)

// Create a container group for the service that makes it publicly accessible.
containerGroup, err := containerinstance.NewContainerGroup(ctx, "container-group", &containerinstance.ContainerGroupArgs{
ResourceGroupName: resourceGroup.Name,
OsType: pulumi.String("linux"),
Expand Down Expand Up @@ -135,7 +141,8 @@ func main() {
},
})

ctx.Export("ipAddress", containerGroup.IpAddress.Elem().Ip())
// Export the service's IP address, hostname, and fully-qualified URL.
ctx.Export("ip", containerGroup.IpAddress.Elem().Ip())
ctx.Export("hostname", containerGroup.IpAddress.Elem().Fqdn())
ctx.Export("url", pulumi.Sprintf("http://%s:%d", containerGroup.IpAddress.Elem().Fqdn(), containerPort))

Expand Down
135 changes: 79 additions & 56 deletions container-azure-python/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,23 +3,30 @@
import pulumi_random as random
from pulumi_azure_native import resources, containerregistry, containerinstance

# Import the program's configuration settings.
config = pulumi.Config()
image_name = config.get("imageName", "my-app")
app_path = config.get("appPath", "./app")
container_port = config.get_int("containerPort", 80)
cpu = config.get_float("cpu", 1.0)
memory = config.get_float("memory", 1.5)

# Create a resource group for the container registry.
resource_group = resources.ResourceGroup("resource-group")

registry = containerregistry.Registry("registry", containerregistry.RegistryArgs(
resource_group_name=resource_group.name,
admin_user_enabled=True,
sku=containerregistry.SkuArgs(
name=containerregistry.SkuName.BASIC,
# Create a container registry.
registry = containerregistry.Registry(
"registry",
containerregistry.RegistryArgs(
resource_group_name=resource_group.name,
admin_user_enabled=True,
sku=containerregistry.SkuArgs(
name=containerregistry.SkuName.BASIC,
),
),
))
)

# Fetch login credentials for the registry.
credentials = containerregistry.list_registry_credentials_output(
resource_group_name=resource_group.name,
registry_name=registry.name,
Expand All @@ -28,7 +35,9 @@
registry_username = credentials.apply(lambda creds: creds.username)
registry_password = credentials.apply(lambda creds: creds.passwords[0].value)

image = docker.Image("image",
# Create a container image for the service.
image = docker.Image(
"image",
image_name=pulumi.Output.concat(registry.login_server, "/", image_name),
build=docker.DockerBuild(
context=app_path,
Expand All @@ -40,62 +49,76 @@
),
)

dns_name = random.RandomString("dns-name", random.RandomStringArgs(
length=8,
special=False,
)).result.apply(lambda result: f"{image_name}-{result.lower()}")
# Use a random string to give the service a unique DNS name.
dns_name = random.RandomString(
"dns-name",
random.RandomStringArgs(
length=8,
special=False,
),
).result.apply(lambda result: f"{image_name}-{result.lower()}")

container_group = containerinstance.ContainerGroup("container-group", containerinstance.ContainerGroupArgs(
resource_group_name=resource_group.name,
os_type="linux",
restart_policy="always",
image_registry_credentials=[
containerinstance.ImageRegistryCredentialArgs(
server=registry.login_server,
username=registry_username,
password=registry_password,
),
],
containers=[
containerinstance.ContainerArgs(
name=image_name,
image=image.image_name,
# Create a container group for the service that makes it publicly accessible.
container_group = containerinstance.ContainerGroup(
"container-group",
containerinstance.ContainerGroupArgs(
resource_group_name=resource_group.name,
os_type="linux",
restart_policy="always",
image_registry_credentials=[
containerinstance.ImageRegistryCredentialArgs(
server=registry.login_server,
username=registry_username,
password=registry_password,
),
],
containers=[
containerinstance.ContainerArgs(
name=image_name,
image=image.image_name,
ports=[
containerinstance.ContainerPortArgs(
port=container_port,
protocol="tcp",
),
],
environment_variables=[
containerinstance.EnvironmentVariableArgs(
name="FLASK_RUN_PORT",
value=str(container_port),
),
containerinstance.EnvironmentVariableArgs(
name="FLASK_RUN_HOST",
value="0.0.0.0",
),
],
resources=containerinstance.ResourceRequirementsArgs(
requests=containerinstance.ResourceRequestsArgs(
cpu=cpu,
memory_in_gb=memory,
),
),
),
],
ip_address=containerinstance.IpAddressArgs(
type=containerinstance.ContainerGroupIpAddressType.PUBLIC,
dns_name_label=dns_name,
ports=[
containerinstance.ContainerPortArgs(
containerinstance.PortArgs(
port=container_port,
protocol="tcp",
),
],
environment_variables=[
containerinstance.EnvironmentVariableArgs(
name="FLASK_RUN_PORT",
value=str(container_port),
),
containerinstance.EnvironmentVariableArgs(
name="FLASK_RUN_HOST",
value="0.0.0.0",
),
],
resources=containerinstance.ResourceRequirementsArgs(
requests=containerinstance.ResourceRequestsArgs(
cpu=cpu,
memory_in_gb=memory,
),
),
),
],
ip_address=containerinstance.IpAddressArgs(
type=containerinstance.ContainerGroupIpAddressType.PUBLIC,
dns_name_label=dns_name,
ports=[
containerinstance.PortArgs(
port=container_port,
protocol="tcp",
),
],
),
))
)

pulumi.export("ipAddress", container_group.ip_address.apply(lambda addr: addr.ip))
# Export the service's IP address, hostname, and fully-qualified URL.
pulumi.export("hostname", container_group.ip_address.apply(lambda addr: addr.fqdn))
pulumi.export("url", container_group.ip_address.apply(lambda addr: f"http://{addr.fqdn}:{container_port}"))
pulumi.export("ip", container_group.ip_address.apply(lambda addr: addr.ip))
pulumi.export(
"url",
container_group.ip_address.apply(
lambda addr: f"http://{addr.fqdn}:{container_port}"
),
)
1 change: 1 addition & 0 deletions container-azure-python/app/Dockerfile
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
FROM python:3.10-alpine

WORKDIR /usr/src/app

COPY requirements.txt requirements.txt
Expand Down
Loading

0 comments on commit b234179

Please sign in to comment.