Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add an ASP.NET app that runs in AWS ECS Fargate #532

Merged
merged 3 commits into from
Jan 30, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions aws-cs-fargate/App/.dockerignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
/bin/
/obj/
2 changes: 2 additions & 0 deletions aws-cs-fargate/App/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
/bin/
/obj/
16 changes: 16 additions & 0 deletions aws-cs-fargate/App/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
FROM mcr.microsoft.com/dotnet/core/sdk:3.1 AS build
WORKDIR /app/src

# First restore dependencies so app changes are faster.
COPY *.csproj .
RUN dotnet restore

# Next copy the rest of the app and build it.
COPY * ./
RUN dotnet publish -c release -o /app/bin --no-restore

# Create a new, smaller image stage, that just runs the DLL.
FROM mcr.microsoft.com/dotnet/core/aspnet:3.1
WORKDIR /app
COPY --from=build /app/bin ./
ENTRYPOINT [ "dotnet", "aws-cs-fargate.dll" ]
26 changes: 26 additions & 0 deletions aws-cs-fargate/App/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace dotnet_core_tutorial
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Rename the namespace to something .NET-y

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Will do, all of this is whatever dotnet new spit out, fwiw.

{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}

public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
27 changes: 27 additions & 0 deletions aws-cs-fargate/App/Properties/launchSettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
{
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:39528",
"sslPort": 44392
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"dotnet_core_tutorial": {
"commandName": "Project",
"launchBrowser": true,
"applicationUrl": "https://localhost:5001;http://localhost:5000",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
40 changes: 40 additions & 0 deletions aws-cs-fargate/App/Startup.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace dotnet_core_tutorial
{
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}

app.UseRouting();

app.UseEndpoints(endpoints =>
{
endpoints.MapGet("/", async context =>
{
await context.Response.WriteAsync("Hello Pulumi!");
});
});
}
}
}
9 changes: 9 additions & 0 deletions aws-cs-fargate/App/appsettings.Development.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"Logging": {
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
}
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit, but I would omit this file

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok! Was autogenerated by dotnet new, wasn't sure what it is 😄

10 changes: 10 additions & 0 deletions aws-cs-fargate/App/appsettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*"
}
8 changes: 8 additions & 0 deletions aws-cs-fargate/App/aws-cs-fargate.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>netcoreapp3.0</TargetFramework>
<RootNamespace>dotnet_core_tutorial</RootNamespace>
</PropertyGroup>

</Project>
2 changes: 2 additions & 0 deletions aws-cs-fargate/Infra/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
/bin/
/obj/
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe merge .gitignores in the root folder of the example?

14 changes: 14 additions & 0 deletions aws-cs-fargate/Infra/Infra.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.0</TargetFramework>
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Pulumi.Aws" Version="1.15.0-preview" />
<PackageReference Include="Pulumi.Docker" Version="1.1.0-preview" />
</ItemGroup>

</Project>
148 changes: 148 additions & 0 deletions aws-cs-fargate/Infra/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

using Pulumi;
using Docker = Pulumi.Docker;
using Ec2 = Pulumi.Aws.Ec2;
using Ecs = Pulumi.Aws.Ecs;
using Ecr = Pulumi.Aws.Ecr;
using Elb = Pulumi.Aws.ElasticLoadBalancingV2;
using Iam = Pulumi.Aws.Iam;

class Program
{
static Task<int> Main()
{
return Deployment.RunAsync(async () => {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's common to put { on a new line, also in our .NET code

Copy link
Member Author

@joeduffy joeduffy Jan 29, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Alright, will fix those that are obvious.

Not quite sure what the style is meant to be in all places, e.g.

    LoadBalancers = {
        x
    },

or

    LoadBalancers =
    {
        x
    },

Do we have plans to add style/linter checking?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The latter

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh my, the code is now twice as long! 🤦‍♂ But I shall resist the temptation to comment on style guidelines ... (oh wait, too late)

// Read back the default VPC and public subnets, which we will use.
var vpc = await Ec2.Invokes.GetVpc(new Ec2.GetVpcArgs { Default = true });
var subnet = await Ec2.Invokes.GetSubnetIds(new Ec2.GetSubnetIdsArgs { VpcId = vpc.Id });

// Create a SecurityGroup that permits HTTP ingress and unrestricted egress.
var webSg = new Ec2.SecurityGroup("web-sg", new Ec2.SecurityGroupArgs {
VpcId = vpc.Id,
Egress = new[] {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

new[] is not required here and down below

new Ec2.Inputs.SecurityGroupEgressArgs {
Protocol = "-1",
FromPort = 0,
ToPort = 0,
CidrBlocks = new[] { "0.0.0.0/0" },
},
},
Ingress = new[] {
new Ec2.Inputs.SecurityGroupIngressArgs {
Protocol = "tcp",
FromPort = 80,
ToPort = 80,
CidrBlocks = new[] { "0.0.0.0/0" },
},
},
});

// Create an ECS cluster to run a container-based service.
var cluster = new Ecs.Cluster("app-cluster");

// Create an IAM role that can be used by our service's task.
var taskExecRole = new Iam.Role("task-exec-role", new Iam.RoleArgs {
AssumeRolePolicy = @"{
""Version"": ""2008-10-17"",
""Statement"": [{
""Sid"": """",
""Effect"": ""Allow"",
""Principal"": {
""Service"": ""ecs-tasks.amazonaws.com""
},
""Action"": ""sts:AssumeRole""
}]
}",
});
var taskExecAttach = new Iam.RolePolicyAttachment("task-exec-policy", new Iam.RolePolicyAttachmentArgs {
Role = taskExecRole.Name,
PolicyArn = "arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy",
});

// Create a load balancer to listen for HTTP traffic on port 80.
var webLb = new Elb.LoadBalancer("web-lb", new Elb.LoadBalancerArgs {
Subnets = subnet.Ids,
SecurityGroups = new[] { webSg.Id },
});
var webTg = new Elb.TargetGroup("web-tg", new Elb.TargetGroupArgs {
Port = 80,
Protocol = "HTTP",
TargetType = "ip",
VpcId = vpc.Id,
});
var webListener = new Elb.Listener("web-listener", new Elb.ListenerArgs {
LoadBalancerArn = webLb.Arn,
Port = 80,
DefaultActions = new[] {
new Elb.Inputs.ListenerDefaultActionsArgs {
Type = "forward",
TargetGroupArn = webTg.Arn,
},
},
});

// Create a private ECR registry and build and publish our app's container image to it.
var appRepo = new Ecr.Repository("app-repo");
var appRepoCreds = appRepo.RegistryId.Apply(async rid => {
var creds = await Ecr.Invokes.GetCredentials(new Ecr.GetCredentialsArgs { RegistryId = rid });
var credsData = Convert.FromBase64String(creds.AuthorizationToken);
return Encoding.UTF8.GetString(credsData).Split(":");
});
var image = new Docker.Image("app-img", new Docker.ImageArgs {
Build = "../App",
ImageName = appRepo.RepositoryUrl,
Registry = new Docker.ImageRegistry {
Server = appRepo.RepositoryUrl,
Username = appRepoCreds.Apply(creds => creds[0]),
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think you should be able to do appRepoCreds.Get(0)

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm: error CS1061: 'Output<string[]>' does not contain a definition for 'Get' and no accessible extension method 'Get' accepting a first argument of type 'Output<string[]>' could be found (are you missing a using directive or an assembly reference?)

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Password = appRepoCreds.Apply(creds => creds[1]),
},
});

// Spin up a load balanced service running our container image.
var appTask = new Ecs.TaskDefinition("app-task", new Ecs.TaskDefinitionArgs {
Family = "fargate-task-definition",
Cpu = "256",
Memory = "512",
NetworkMode = "awsvpc",
RequiresCompatibilities = new[] { "FARGATE" },
ExecutionRoleArn = taskExecRole.Arn,
ContainerDefinitions = image.ImageName.Apply(imgName => @"[{
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

imgName -> imageName in .NET

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done.

""name"": ""my-app"",
""image"": """ + imgName + @""",
""portMappings"": [{
""containerPort"": 80,
""hostPort"": 80,
""protocol"": ""tcp""
}]
}]"),
});
var appSvc = new Ecs.Service("app-svc", new Ecs.ServiceArgs {
Cluster = cluster.Arn,
DesiredCount = 3,
LaunchType = "FARGATE",
TaskDefinition = appTask.Arn,
NetworkConfiguration = new Ecs.Inputs.ServiceNetworkConfigurationArgs {
AssignPublicIp = true,
Subnets = subnet.Ids,
SecurityGroups = new[] { webSg.Id },
},
LoadBalancers = new[] {
new Ecs.Inputs.ServiceLoadBalancersArgs {
TargetGroupArn = webTg.Arn,
ContainerName = "my-app",
ContainerPort = 80,
},
},
}, new CustomResourceOptions { DependsOn = { webListener } });

// Export the resulting web address.
return new Dictionary<string, object?>{
{ "url", webLb.DnsName.Apply(url => $"http://{url}") },
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Try changing to Output.Format

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done.

};
});
}
}
4 changes: 4 additions & 0 deletions aws-cs-fargate/Pulumi.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
name: aws-cs-fargate
runtime: dotnet
main: Infra
description: An ASP.NET application running in AWS ECS Fargate, using C# infrastructure as code
Loading