Skip to Content
Cloud Engineering Academy
3. .NET Application Development on AWS

Elastic Beanstalk for .NET

Deploy an ASP.NET Core API to Elastic Beanstalk on the .NET 10 Amazon Linux 2023 platform, understand every resource Beanstalk creates for you, harden the environment, and know when the Windows/IIS platform is the right choice.

intermediate⏱ 1 h 40 min🟡 Low costDVA-C03SAA-C03

Assumes: .NET 10 LTS · Beanstalk platform '.NET 10 on AL2023 version 3.12.3' · AWS SDK for .NET v4 (AWSSDK.ElasticBeanstalk 4.1.0.2, AWSSDK.S3 4.1.1) · AWS CLI v2 · Region us-east-1. Verified against official sources on 2026-11-18.

Learning objectives

By the end of this lesson you can:

  • Explain Elastic Beanstalk's model — application, application version, environment, platform — and list the real AWS resources an environment creates.
  • Package and deploy an ASP.NET Core API to the .NET 10 on Amazon Linux 2023 platform with a Procfile, .ebextensions and environment properties.
  • Choose a deployment policy (all at once, rolling, rolling with additional batch, immutable, traffic splitting) and explain blue/green with a CNAME swap.
  • Harden an environment: instance profile, IMDSv2, private instances, log streaming with retention, managed platform updates and secrets that are not plain-text properties.
  • Decide when the Windows Server / IIS platform is justified and deploy to it with a deployment manifest.
  • Automate a deployment from C# with the Elastic Beanstalk API.

Prerequisites

Why this matters in banking

Harbourline Bank has a dozen internal ASP.NET applications — a branch appointment booker, a complaints tracker, an internal FX-rate admin page — each with a handful of users. Containerising and building ECS pipelines for every one of them is more work than the applications themselves. Elastic Beanstalk is the AWS service that most resembles Azure App Service: upload a zip, get a running, load-balanced, monitored application.

That convenience has a cost if you do not understand it. Teams discover months later that their "simple" Beanstalk app created a public load balancer, instances with public IPs, a log bucket nobody configured, and an EC2 fleet still running an outdated platform version because managed updates were never turned on. A penetration tester finds IMDSv1 enabled. An auditor finds the database password in plain text in the environment properties, visible to anyone with read access to the console.

This lesson shows you what Beanstalk builds, how to make it safe, and when to choose it over Fargate or Lambda.

The idea in plain language

AWS Elastic Beanstalk is an orchestration service. You give it your application code and a few settings; it creates and manages the EC2 instances, Auto Scaling group, load balancer, security groups, alarms and logging needed to run it, and it deploys new versions for you. Underneath, Beanstalk uses CloudFormation, so every environment is a real stack you can see.

Four concepts:

TermPlain meaningAzure App Service analogy
ApplicationA named container for versions and environments.The App Service "app" name grouping
Application versionA specific, labelled source bundle (a zip in S3). Immutable.A deployment package
EnvironmentA running copy of one version on a chosen platform, with its own resources and URL. accounts-dev, accounts-prod.An App Service (or a deployment slot)
PlatformThe OS, language runtime, web/proxy server and Beanstalk agent, versioned together. e.g. .NET 10 on AL2023 version 3.12.3.The runtime stack setting

An environment is either a web server tier (HTTP traffic, optionally through a load balancer) or a worker tier (pulls messages from an SQS queue, posted to your app by a daemon).

Analogy: Beanstalk is a serviced office. You bring your team (the code) and choose a package (platform + instance size). The building manager supplies desks, reception, security badges, cleaning and fire alarms. It is quick and convenient, but the desks, reception and alarms are real and you pay rent on all of them, even when nobody is in. If you want to rearrange walls, you need to know where the building manager keeps the floor plans (.ebextensions and CloudFormation).

What problem Elastic Beanstalk solves

It removes the glue work of turning "a .NET app" into "a monitored, scalable, deployable fleet": launch templates, Auto Scaling groups, load balancer listeners, health reporting, log collection, rolling deployments and platform patching.

What Beanstalk is good at:

  • Fast path from dotnet publish to a URL, with no containers required.
  • Lift-and-shift of IIS-hosted apps, including .NET Framework 4.x, on the Windows Server platforms.
  • Built-in deployment policies, enhanced health monitoring and managed platform updates.
  • No charge for Beanstalk itself; you pay only for the resources it creates.

Limitations and sharp edges (checked 2026-11-18):

  • You still run EC2 instances. They are patched by managed platform updates only if you turn them on. Instances scale in whole-VM steps and cost money while idle.
  • Environment start and deployment are slow compared with Lambda or Fargate: creating an environment takes several minutes; immutable deployments launch a whole new Auto Scaling group.
  • Configuration sprawl. Settings can come from the console, saved configurations, .ebextensions, the EB CLI and the API, with a precedence order (console/API settings override .ebextensions). Drift is easy.
  • Environment properties are plain text. Anyone with elasticbeanstalk:DescribeConfigurationSettings can read them. Use Secrets Manager or Parameter Store references instead (see below).
  • Windows platform restriction: the .NET on Windows Server platforms do not support worker environments.
  • Single-instance environments have no load balancer, so no zero-downtime rolling deployments (the instance is updated in place).

Platforms available today (from the Beanstalk platform list, checked 2026-11-18):

Platform branchSolution stack nameRuntime
.NET 10 on AL2023 version 3.12.364bit Amazon Linux 2023 v3.12.3 running .NET 10.NET 10.0.15, nginx 1.30.6
.NET 9 / .NET 8 on AL2023 version 3.12.3… running .NET 9 / … running .NET 8.NET 9.0.23 / 8.0.34
Windows Server 2025 / 2022 / 2019 (full and Core) with IIS 10.0 version 2.23.10e.g. 64bit Windows Server 2025 v2.23.10 running IIS 10.0.NET 10.0.15, 9, 8 and .NET Framework 4.8.1 (4.8 on 2019)

Platform versions are released frequently; always look up the current solution stack name rather than hard-coding the one above:

aws elasticbeanstalk list-available-solution-stacks --query "SolutionStacks[?contains(@, '.NET 10')]" --profile learn-sandbox

Microsoft / Azure comparison

You know (Microsoft/Azure)AWS equivalentWhat's different
Azure App Service (Linux)Beanstalk .NET on AL2023Real EC2 instances, ALB and Auto Scaling group are created in your account and VPC, and you can see and are billed for each
Azure App Service (Windows) / IIS on a VMBeanstalk .NET on Windows Server with IISSupports .NET Framework 4.x; deploy with Web Deploy archive or a deployment manifest
App Service plan (instance count/size)Auto Scaling group + instance type settingsScaling triggers are CloudWatch alarms (default: network out) — change them to CPU or request count
Deployment slots + swapSecond environment + Swap environment URLs (CNAME swap)The swap changes DNS, so clients with cached DNS take time to move
App settingsEnvironment properties (aws:elasticbeanstalk:application:environment)Plain text — use aws:elasticbeanstalk:application:environmentsecrets for secrets
Key Vault referencesEnvironment secrets (Secrets Manager / Parameter Store ARNs)Values fetched at instance bootstrap only, not on rotation
Managed identityEC2 instance profileOne role for the whole instance; every process on it gets the permissions
Application Insights / Log streamEnhanced health + CloudWatch Logs streamingHealth is a colour (Green/Yellow/Red/Grey) with causes; logs need StreamLogs turned on
Kudu / web.config transforms.ebextensions/*.config, .platform/ hooks and nginx configYAML/JSON option settings plus shell hooks during deployment

Architecture

What a load-balanced web server environment creates:

Inside each Linux instance, nginx listens on port 80 and proxies to your app. By default nginx forwards to port 5000, and Beanstalk passes the port in the PORT environment variable. Your ASP.NET Core app must listen on that port. The lab code does this in UsePlatformPort():

labs/m03-accounts-api/src/Harbourline.Accounts.Api/Hosting/HostingExtensions.cs (excerpt)
var port = Environment.GetEnvironmentVariable("PORT");
var explicitUrls = builder.Configuration["ASPNETCORE_URLS"] ?? builder.Configuration["urls"];
if (int.TryParse(port, out var p) && p is > 0 and < 65536 && string.IsNullOrEmpty(explicitUrls))
{
    builder.WebHost.UseUrls($"http://0.0.0.0:{p}");
}

Security-boundary view:

BoundaryControlDefaultWhat a bank sets
Internet → ALBListener, security group, WAFHTTP 80 publicHTTPS 443 with ACM certificate; internal scheme for staff-only apps; WAF
ALB → instanceInstance security groupAllows 80 from ALB security groupSame; instances in private subnets
Instance → AWS APIsInstance profileaws-elasticbeanstalk-ec2-role with broad Beanstalk tier policiesCustom role: tier policy + only the app's data permissions
Instance metadataIMDSIMDSv1 and v2 may both be allowedDisableIMDSv1: true
LogsCloudWatch LogsOff; bundles go to S3StreamLogs: true, retention, KMS-encrypted log groups
PatchingManaged platform updatesOff unless enabledOn, weekly window, minor + patch

Deployment policies

PolicyHow it worksDowntimeExtra cost during deployRollback
All at onceDeploy to every instance simultaneouslyYes, brieflyNoneRedeploy previous version
RollingBatches of instances taken out of service and updatedNo, but reduced capacityNoneRedeploy previous version
Rolling with additional batchLaunch an extra batch first, then rollNo, full capacityOne extra batchRedeploy previous version
ImmutableLaunch a full new set of instances in a temporary Auto Scaling group; swap in when healthyNoDouble the fleet brieflyTerminate the new group — fastest safe rollback
Traffic splittingCanary: send a percentage of traffic to new instances for an evaluation periodNoNew fleetAutomatic if health degrades
Blue/green (not a policy setting)Clone to a new environment, deploy there, swap environment URLsNoSecond environmentSwap back

For a bank, immutable or traffic splitting in production, and all at once for single-instance dev environments, is a sensible default. Blue/green is the right choice when the platform version itself changes or when the database schema change needs a controlled cut-over.

Step-by-step implementation

Create the IAM roles once per account

Beanstalk needs a service role (Beanstalk calls other services on your behalf; used for enhanced health and managed updates) and an instance profile (the role your instances and your app use). The console can create defaults; the CLI section shows how to create them explicitly so you control the permissions.

Publish the application

dotnet publish -c Release -o publish produces a framework-dependent build. The .NET 10 platform already has the runtime installed, so you do not need a self-contained build. Framework-dependent output is portable across x86_64 and arm64 instances.

Add a Procfile and configuration files

Add a Procfile at the root of the bundle so you control exactly what runs. Add .ebextensions/*.config files for settings that must travel with the code (health check path, log streaming, IMDSv2).

Zip the bundle correctly

Zip the contents of the publish folder, not the folder itself. Procfile and .ebextensions must be at the root of the zip.

Create the application, version and environment

Start with a single-instance environment for the lab (no load balancer, much cheaper). Use a load-balanced environment for anything shared.

Check health and logs

Watch the environment go from Launching → Ready and health Grey → Green. Request logs with eb logs or the console, and confirm streaming into CloudWatch Logs.

Deploy version 2 and terminate

Deploy a second version with the C# deployer, then terminate the environment and delete the application versions and bucket objects.

AWS Console instructions

  1. Console → Elastic Beanstalk → Create application. Environment tier Web server environment. Application name hl-m03-accounts, environment name hl-m03-accounts-dev.
  2. Platform: Managed platform → .NET Core on Linux → platform branch .NET 10 running on 64bit Amazon Linux 2023 → recommended version.
  3. Application code: Upload your code → choose the zip, version label v1.
  4. Presets: Single instance (free tier eligible) for the lab; High availability for production.
  5. Configure service access: choose Use an existing service role if you created one, plus the EC2 instance profile you created. (Newer accounts no longer get a default instance profile automatically ⚠ VERIFY; create aws-elasticbeanstalk-ec2-role first.)
  6. Set up networking, database, and tags: choose your VPC; for load-balanced environments put instances in private subnets and the load balancer in public subnets (or private for an internal app). Add the four mandatory tags.
  7. Configure instance traffic and scaling: instance type t4g.small (Graviton) or t3.small; IMDSv1: Deactivated.
  8. Configure updates, monitoring, and logging: health reporting Enhanced; Managed updates: activated, weekly window, update level Minor and patch; Instance log streaming to CloudWatch Logs: activated, retention 7 days, Delete logs upon termination on; Environment properties: ASPNETCORE_ENVIRONMENT=Production, Repository__Provider=InMemory.
  9. Submit. Watch Events; when health turns Green, open the environment URL and request /health/ready.
  10. To deploy a new version: Environments → hl-m03-accounts-dev → Upload and deploy.

AWS CLI

export AWS_PROFILE=learn-sandbox AWS_REGION=us-east-1
ACCOUNT=$(aws sts get-caller-identity --query Account --output text)

# ---- One-off: instance profile (the role your code runs as) ----------------------------------
cat > ec2-trust.json <<'EOF'
{ "Version": "2012-10-17",
  "Statement": [{ "Effect": "Allow", "Principal": { "Service": "ec2.amazonaws.com" }, "Action": "sts:AssumeRole" }] }
EOF
aws iam create-role --role-name hl-m03-eb-ec2 --assume-role-policy-document file://ec2-trust.json
# Beanstalk agent needs: upload logs to the EB bucket, CloudWatch, X-Ray etc.
aws iam attach-role-policy --role-name hl-m03-eb-ec2 \
  --policy-arn arn:aws:iam::aws:policy/AWSElasticBeanstalkWebTier
aws iam create-instance-profile --instance-profile-name hl-m03-eb-ec2
aws iam add-role-to-instance-profile --instance-profile-name hl-m03-eb-ec2 --role-name hl-m03-eb-ec2

# ---- One-off: service role (Beanstalk itself, for enhanced health + managed updates) ----------
cat > eb-trust.json <<EOF
{ "Version": "2012-10-17",
  "Statement": [{ "Effect": "Allow", "Principal": { "Service": "elasticbeanstalk.amazonaws.com" },
    "Action": "sts:AssumeRole",
    "Condition": { "StringEquals": { "sts:ExternalId": "elasticbeanstalk" } } }] }
EOF
aws iam create-role --role-name hl-m03-eb-service --assume-role-policy-document file://eb-trust.json
aws iam attach-role-policy --role-name hl-m03-eb-service \
  --policy-arn arn:aws:iam::aws:policy/service-role/AWSElasticBeanstalkEnhancedHealth
aws iam attach-role-policy --role-name hl-m03-eb-service \
  --policy-arn arn:aws:iam::aws:policy/AWSElasticBeanstalkManagedUpdatesCustomerRolePolicy

# ---- Build the bundle (see "Complete code" for Procfile and .ebextensions) --------------------
dotnet publish src/Harbourline.Accounts.Api -c Release -o publish
cp Procfile publish/ && cp -r .ebextensions publish/
(cd publish && zip -r ../accounts-v1.zip .)

# ---- Upload to the Beanstalk-managed bucket (creates it if missing) ---------------------------
BUCKET=$(aws elasticbeanstalk create-storage-location --query S3Bucket --output text)
aws s3 cp accounts-v1.zip "s3://$BUCKET/hl-m03-accounts/accounts-v1.zip"

# ---- Application and version ----------------------------------------------------------------
aws elasticbeanstalk create-application --application-name hl-m03-accounts \
  --tags Key=Project,Value=cea-lab Key=Lab,Value=m03-beanstalk Key=Environment,Value=learn Key=Owner,Value=you
aws elasticbeanstalk create-application-version --application-name hl-m03-accounts \
  --version-label v1 --source-bundle S3Bucket="$BUCKET",S3Key=hl-m03-accounts/accounts-v1.zip --process

# ---- Environment: single instance, IMDSv2 only, enhanced health, managed updates, log streaming
STACK=$(aws elasticbeanstalk list-available-solution-stacks \
  --query "SolutionStacks[?contains(@, 'running .NET 10')] | [0]" --output text)
aws elasticbeanstalk create-environment --application-name hl-m03-accounts \
  --environment-name hl-m03-accounts-dev --version-label v1 --solution-stack-name "$STACK" \
  --tags Key=Project,Value=cea-lab Key=Lab,Value=m03-beanstalk Key=Environment,Value=learn Key=Owner,Value=you \
  --option-settings \
    Namespace=aws:elasticbeanstalk:environment,OptionName=EnvironmentType,Value=SingleInstance \
    Namespace=aws:elasticbeanstalk:environment,OptionName=ServiceRole,Value=hl-m03-eb-service \
    Namespace=aws:autoscaling:launchconfiguration,OptionName=IamInstanceProfile,Value=hl-m03-eb-ec2 \
    Namespace=aws:autoscaling:launchconfiguration,OptionName=DisableIMDSv1,Value=true \
    Namespace=aws:ec2:instances,OptionName=InstanceTypes,Value=t4g.small \
    Namespace=aws:elasticbeanstalk:healthreporting:system,OptionName=SystemType,Value=enhanced \
    Namespace=aws:elasticbeanstalk:managedactions,OptionName=ManagedActionsEnabled,Value=true \
    Namespace=aws:elasticbeanstalk:managedactions,OptionName=PreferredStartTime,Value="Sun:02:00" \
    Namespace=aws:elasticbeanstalk:managedactions:platformupdate,OptionName=UpdateLevel,Value=minor \
    Namespace=aws:elasticbeanstalk:cloudwatch:logs,OptionName=StreamLogs,Value=true \
    Namespace=aws:elasticbeanstalk:cloudwatch:logs,OptionName=RetentionInDays,Value=7 \
    Namespace=aws:elasticbeanstalk:cloudwatch:logs,OptionName=DeleteOnTerminate,Value=true \
    Namespace=aws:elasticbeanstalk:application:environment,OptionName=ASPNETCORE_ENVIRONMENT,Value=Production \
    Namespace=aws:elasticbeanstalk:application:environment,OptionName=Repository__Provider,Value=InMemory

# ---- Wait and inspect --------------------------------------------------------------------------
aws elasticbeanstalk wait environment-updated --environment-names hl-m03-accounts-dev
aws elasticbeanstalk describe-environment-health --environment-name hl-m03-accounts-dev \
  --attribute-names All --query '{status:Status,health:Color,causes:Causes}'
URL=$(aws elasticbeanstalk describe-environments --environment-names hl-m03-accounts-dev \
  --query 'Environments[0].CNAME' --output text)
curl -s "http://$URL/health/ready"

# Last 20 events (deployment progress and errors)
aws elasticbeanstalk describe-events --environment-name hl-m03-accounts-dev --max-items 20 \
  --query 'Events[].[EventDate,Severity,Message]' --output table

# ---- Blue/green: clone, deploy v2 to the clone, then swap URLs ----------------------------------
# aws elasticbeanstalk swap-environment-cnames \
#   --source-environment-name hl-m03-accounts-blue --destination-environment-name hl-m03-accounts-green

With the EB CLI the same flow is shorter (eb init, eb create hl-m03-accounts-dev --single, eb deploy, eb health, eb logs, eb terminate). The EB CLI is convenient for experiments; use the API, CDK or Terraform for anything repeatable.

Infrastructure as Code

CDK has only L1 (Cfn*) constructs for Beanstalk, which map one-to-one to CloudFormation. Terraform's aws_elastic_beanstalk_environment takes the same namespaced settings as the CLI.

BeanstalkStack.cs
using Amazon.CDK;
using Amazon.CDK.AWS.ElasticBeanstalk;
using Amazon.CDK.AWS.IAM;
using Amazon.CDK.AWS.S3.Assets;
using Constructs;

public sealed class BeanstalkStack : Stack
{
    public BeanstalkStack(Construct scope, string id, IStackProps props) : base(scope, id, props)
    {
        // The zip built by `dotnet publish` + Procfile + .ebextensions, uploaded by CDK as an asset.
        var bundle = new Asset(this, "Bundle", new AssetProps { Path = "../../artifacts/accounts-v1.zip" });

        var instanceRole = new Role(this, "InstanceRole", new RoleProps
        {
            AssumedBy = new ServicePrincipal("ec2.amazonaws.com"),
            ManagedPolicies = [ManagedPolicy.FromAwsManagedPolicyName("AWSElasticBeanstalkWebTier")],
        });
        var instanceProfile = new CfnInstanceProfile(this, "InstanceProfile", new CfnInstanceProfileProps
        {
            Roles = [instanceRole.RoleName],
        });

        var app = new CfnApplication(this, "App", new CfnApplicationProps { ApplicationName = "hl-m03-accounts" });

        var version = new CfnApplicationVersion(this, "V1", new CfnApplicationVersionProps
        {
            ApplicationName = "hl-m03-accounts",
            SourceBundle = new CfnApplicationVersion.SourceBundleProperty
            {
                S3Bucket = bundle.S3BucketName,
                S3Key = bundle.S3ObjectKey,
            },
        });
        version.Node.AddDependency(app);

        CfnEnvironment.OptionSettingProperty Opt(string ns, string name, string value) =>
            new() { Namespace = ns, OptionName = name, Value = value };

        var env = new CfnEnvironment(this, "Dev", new CfnEnvironmentProps
        {
            ApplicationName = "hl-m03-accounts",
            EnvironmentName = "hl-m03-accounts-dev",
            // Look up the current name with list-available-solution-stacks; it changes with each platform release.
            SolutionStackName = "64bit Amazon Linux 2023 v3.12.3 running .NET 10",
            VersionLabel = version.Ref,
            OptionSettings = new[]
            {
                Opt("aws:elasticbeanstalk:environment", "EnvironmentType", "SingleInstance"),
                Opt("aws:autoscaling:launchconfiguration", "IamInstanceProfile", instanceProfile.Ref),
                Opt("aws:autoscaling:launchconfiguration", "DisableIMDSv1", "true"),
                Opt("aws:ec2:instances", "InstanceTypes", "t4g.small"),
                Opt("aws:elasticbeanstalk:healthreporting:system", "SystemType", "enhanced"),
                Opt("aws:elasticbeanstalk:cloudwatch:logs", "StreamLogs", "true"),
                Opt("aws:elasticbeanstalk:cloudwatch:logs", "RetentionInDays", "7"),
                Opt("aws:elasticbeanstalk:application:environment", "ASPNETCORE_ENVIRONMENT", "Production"),
            },
        });
        env.Node.AddDependency(version);

        _ = new CfnOutput(this, "Url", new CfnOutputProps { Value = env.AttrEndpointUrl });
    }
}

Complete code

Bundle files

Procfile
web: dotnet ./Harbourline.Accounts.Api.dll
.ebextensions/01-harbourline.config
option_settings:
  # Load-balanced environments only: the ALB health check path (ignored for SingleInstance).
  aws:elasticbeanstalk:environment:process:default:
    HealthCheckPath: /health/ready
    MatcherHTTPCode: "200"
    DeregistrationDelay: "30"
  # Rolling deployments that never reduce capacity, for load-balanced environments.
  aws:elasticbeanstalk:command:
    DeploymentPolicy: Immutable
  # Never allow IMDSv1 (SSRF protection), even if someone forgets it in the console.
  aws:autoscaling:launchconfiguration:
    DisableIMDSv1: true
  # Stream instance and app logs to CloudWatch with retention.
  aws:elasticbeanstalk:cloudwatch:logs:
    StreamLogs: true
    RetentionInDays: 7
    DeleteOnTerminate: true
  # Non-secret settings only. Secrets use the environmentsecrets namespace below.
  aws:elasticbeanstalk:application:environment:
    ASPNETCORE_ENVIRONMENT: Production
    Hosting__TrustedProxyNetworks__0: 10.0.0.0/16
.ebextensions/02-secrets.config
# Platform versions released on or after 2025-03-26 can map Secrets Manager secrets and
# Parameter Store parameters to environment variables at instance bootstrap.
# The instance profile needs secretsmanager:GetSecretValue / ssm:GetParameter (+ kms:Decrypt for CMKs).
option_settings:
  aws:elasticbeanstalk:application:environmentsecrets:
    Pseudonymisation__Key: arn:aws:ssm:us-east-1:111122223333:parameter/hl-m03/accounts-api/Pseudonymisation/Key

A C# deployer

This console app uploads a bundle, creates an application version and deploys it, then waits until the environment is Ready and Green, printing Beanstalk events along the way. It is the Beanstalk equivalent of the ECS rollout watcher.

Harbourline.Deploy.Beanstalk.csproj
<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net10.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
    <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="AWSSDK.ElasticBeanstalk" Version="4.1.0.2" />
    <PackageReference Include="AWSSDK.S3" Version="4.1.1" />
    <PackageReference Include="AWSSDK.SSO" Version="4.1.0.2" />
    <PackageReference Include="AWSSDK.SSOOIDC" Version="4.1.0.2" />
  </ItemGroup>
</Project>
Program.cs
using Amazon.ElasticBeanstalk;
using Amazon.ElasticBeanstalk.Model;
using Amazon.S3;
using Amazon.S3.Model;

// Usage: dotnet run -- <application> <environment> <zipPath> <versionLabel>
if (args.Length != 4)
{
    Console.Error.WriteLine("Usage: <application> <environment> <zipPath> <versionLabel>");
    return 2;
}
var (application, environment, zipPath, label) = (args[0], args[1], args[2], args[3]);

using var eb = new AmazonElasticBeanstalkClient();
using var s3 = new AmazonS3Client();
using var cts = new CancellationTokenSource(TimeSpan.FromMinutes(30));

// 1. The account's Beanstalk bucket (created on first call, encrypted by default).
var bucket = (await eb.CreateStorageLocationAsync(new CreateStorageLocationRequest(), cts.Token)).S3Bucket;
var key = $"{application}/{label}.zip";
await s3.PutObjectAsync(new PutObjectRequest { BucketName = bucket, Key = key, FilePath = zipPath }, cts.Token);
Console.WriteLine($"Uploaded s3://{bucket}/{key}");

// 2. Immutable, labelled version. Process = true validates the bundle before it can be deployed.
await eb.CreateApplicationVersionAsync(new CreateApplicationVersionRequest
{
    ApplicationName = application,
    VersionLabel = label,
    SourceBundle = new Amazon.ElasticBeanstalk.Model.S3Location { S3Bucket = bucket, S3Key = key },
    Process = true,
    Description = $"Deployed by {Environment.UserName} at {DateTime.UtcNow:O}",
}, cts.Token);

// Wait until the version has been processed.
while (true)
{
    var versions = await eb.DescribeApplicationVersionsAsync(new DescribeApplicationVersionsRequest
    {
        ApplicationName = application,
        VersionLabels = [label],
    }, cts.Token);
    var status = versions.ApplicationVersions?.FirstOrDefault()?.Status;
    if (status == ApplicationVersionStatus.Processed) break;
    if (status == ApplicationVersionStatus.Failed)
    {
        Console.Error.WriteLine("Bundle validation failed (check Procfile and .ebextensions syntax).");
        return 1;
    }
    await Task.Delay(TimeSpan.FromSeconds(5), cts.Token);
}

// 3. Deploy.
var started = DateTime.UtcNow;
await eb.UpdateEnvironmentAsync(new UpdateEnvironmentRequest
{
    EnvironmentName = environment,
    VersionLabel = label,
}, cts.Token);

// 4. Poll status, health and events until Ready + Green (or failure).
var printed = new HashSet<string>();
while (true)
{
    var events = await eb.DescribeEventsAsync(new DescribeEventsRequest
    {
        EnvironmentName = environment,
        StartTime = started,
    }, cts.Token);
    foreach (var e in (events.Events ?? []).AsEnumerable().Reverse())
    {
        var id = $"{e.EventDate:O}|{e.Message}";
        if (printed.Add(id)) Console.WriteLine($"{e.EventDate:HH:mm:ss} {e.Severity,-5} {e.Message}");
    }

    var env = (await eb.DescribeEnvironmentsAsync(new DescribeEnvironmentsRequest
    {
        EnvironmentNames = [environment],
    }, cts.Token)).Environments?.FirstOrDefault()
        ?? throw new InvalidOperationException($"Environment {environment} not found.");

    if (env.Status == EnvironmentStatus.Ready)
    {
        if (env.VersionLabel != label)
        {
            Console.Error.WriteLine($"Environment is Ready but runs {env.VersionLabel}: the deployment was rolled back or failed.");
            return 1;
        }
        if (env.Health == EnvironmentHealth.Green)
        {
            Console.WriteLine($"Deployed {label} to {environment}: Ready / Green at http://{env.CNAME}");
            return 0;
        }
        if (env.Health == EnvironmentHealth.Red)
        {
            Console.Error.WriteLine($"Deployed but health is Red ({env.HealthStatus}). Investigate before proceeding.");
            return 1;
        }
    }

    await Task.Delay(TimeSpan.FromSeconds(10), cts.Token);
}

Code explained line by line

Bundle files

  1. Procfile → web: dotnet ./Harbourline.Accounts.Api.dll — the web process is the one nginx proxies to. Without a Procfile, the platform guesses the entry point from the *.runtimeconfig.json file it finds; with several projects in the bundle, that guess fails, so always include one.
  2. aws:elasticbeanstalk:environment:process:default — settings for the default process behind the load balancer: health check path, success code and deregistration delay. Ignored by single-instance environments, which have no ALB.
  3. DeploymentPolicy: Immutable — every deployment launches a fresh set of instances, so a bad version never touches the running fleet.
  4. DisableIMDSv1: true — the instance metadata service only accepts session-token (v2) requests, which blocks the classic SSRF credential theft.
  5. aws:elasticbeanstalk:cloudwatch:logs — streams /var/log/web.stdout.log, nginx logs and Beanstalk agent logs to CloudWatch with 7-day retention.
  6. aws:elasticbeanstalk:application:environment — plain-text environment variables. Hosting__TrustedProxyNetworks__0 binds to the first element of the Hosting:TrustedProxyNetworks array used by the forwarded-headers setup.
  7. aws:elasticbeanstalk:application:environmentsecrets — maps a Parameter Store or Secrets Manager ARN to an environment variable at instance bootstrap. The value never appears in the Beanstalk configuration. Rotation is not picked up until the instance is replaced or the environment is updated.

Deployer

  1. CreateStorageLocationAsync — returns (and creates if necessary) the per-Region elasticbeanstalk-<region>-<account> bucket.
  2. PutObjectAsync with FilePath — uploads the zip. Credentials come from the default chain.
  3. CreateApplicationVersionAsync with Process = true — Beanstalk validates the bundle (for example, malformed .ebextensions YAML) before allowing deployment.
  4. DescribeApplicationVersionsAsync loop — waits for Processed or Failed. Note the v4 SDK pattern: ApplicationVersions?.FirstOrDefault().
  5. UpdateEnvironmentAsync — starts the deployment using the environment's configured policy.
  6. DescribeEventsAsync with StartTime — only events from this deployment. Beanstalk returns newest first, so the list is reversed.
  7. env.Status == Ready and env.VersionLabel != label — after a failed immutable deployment Beanstalk returns to Ready on the old version. Checking the label catches this silent failure.
  8. env.Health — Green, Yellow, Red or Grey. HealthStatus gives the enhanced-health detail (Ok, Warning, Degraded, Severe …).

Windows Server and IIS

Use the Windows platform when the application cannot run on Linux yet: .NET Framework 4.x, WCF services, Windows authentication, COM components or Windows-only libraries. For modern ASP.NET Core, Linux is cheaper (no Windows licence in the instance price) and starts faster.

For an ASP.NET Core app on IIS, include an aws-windows-deployment-manifest.json at the root of the bundle and put the published site in a subfolder:

aws-windows-deployment-manifest.json
{
  "manifestVersion": 1,
  "deployments": {
    "aspNetCoreWeb": [
      {
        "name": "harbourline-branch-booker",
        "parameters": {
          "appBundle": "site",
          "iisPath": "/",
          "iisWebSite": "Default Web Site"
        }
      }
    ]
  }
}

The bundle layout is aws-windows-deployment-manifest.json plus a site/ folder containing the dotnet publish output (with its web.config). For classic .NET Framework apps, the manifest's msDeploy section or a Web Deploy package is used instead ⚠ VERIFY the manifest schema against the current Beanstalk Windows documentation before relying on it. The Windows platforms do not support worker environments, so background jobs move to a Windows Service on EC2, a scheduled task, or (better) a separate Linux worker.

Security considerations

⚠ Learning shortcut — not for production

The lab uses a single-instance environment with a public IP and plain HTTP on port 80, plus the broad AWSElasticBeanstalkWebTier policy on the instance role. In production: a load-balanced environment with instances in private subnets (aws:ec2:vpc → AssociatePublicIpAddress: false, Subnets, ELBSubnets), an HTTPS listener with an ACM certificate (aws:elbv2:listener:443), an internal ALB for staff-only apps, AWS WAF, and an instance role that adds only the application's own data permissions on top of a scoped-down copy of the tier policy.

  • One role per instance, shared by every process. The nginx proxy, the Beanstalk agent and your app all use the same instance profile. Keep application permissions minimal and resource-scoped.
  • No secrets in environment properties. Use environmentsecrets or fetch at runtime from Secrets Manager with caching (see the secrets lesson).
  • Patch automatically. Enable managed platform updates; they apply OS and runtime patches in a weekly window using immutable deployments. Without them, a bank's vulnerability scanner will find months-old kernels.
  • No SSH keys. Leave EC2KeyName empty and use Session Manager for break-glass access, so every session is logged.
  • Encrypt and limit logs. Log groups and the Beanstalk S3 bucket can contain personal data. Set retention, restrict access and use KMS keys where policy requires it.
  • The CloudFormation stack is managed by Beanstalk. Do not edit awseb-… stack resources directly; changes drift and are overwritten. Change settings through Beanstalk.

Banking use case

Harbourline's branch appointment booker is an ASP.NET Core 10 app used by 400 staff. The team chooses Beanstalk on Linux because it is a classic web app with no container expertise in the team. The environment is load-balanced with an internal ALB reachable only over the corporate network, instances are t4g.small in private subnets across two AZs, deployment policy is immutable, and managed updates run every Sunday at 02:00 UK time.

Meanwhile, a legacy .NET Framework 4.8 FX-rate admin tool is lifted onto the Windows Server 2022 with IIS platform unchanged, as a stepping stone. Its modernisation ticket references the porting lesson later in this module. Both environments are defined in CDK so that the configuration review in the change process is a code review, not a console screenshot.

Common mistakes

  • Zipping the folder instead of its contents → Beanstalk cannot find Procfile or the .dll → zip from inside the publish folder.
  • App listens on 8080 because of ASPNETCORE_HTTP_PORTS → nginx returns 502 → listen on PORT (default 5000) or configure nginx accordingly.
  • Hard-coding a solution stack version → creation fails after the version is retired → look it up at deploy time.
  • Secrets as environment properties → visible in console and API → use environmentsecrets or runtime fetch.
  • Leaving default scaling triggers → the Auto Scaling group scales on network out, not load → switch to CPU or RequestCountPerTarget.
  • Forgetting that console changes override .ebextensions → a setting in code appears to be ignored → remove the console override or manage everything through IaC.
  • Assuming managed updates are on → months-old platform → enable ManagedActionsEnabled.

Troubleshooting

SymptomLikely causeFix
502 Bad Gateway from nginxApp not listening on PORT, or crashed on starteb logs → web.stdout.log; listen on PORT
Environment creation fails: instance profile not foundNo aws-elasticbeanstalk-ec2-role and none specifiedCreate the instance profile and set IamInstanceProfile
Version status Failed after uploadMalformed .ebextensions YAML/JSONValidate YAML; tabs are not allowed
Health Red: "100% of requests failing with 5xx"App exceptions or wrong health check pathCheck health check path and application logs
Health Yellow/Red: "Instance ELB health state has been Unhealthy"Health check path requires authenticationMake /health/ready anonymous
Deployment "completed" but old version still runningImmutable deployment failed health and was rolled backCheck events; the deployer's version-label check catches this
AccessDenied in app calling DynamoDBInstance profile lacks permissionAdd a scoped inline policy to the instance role
Logs not in CloudWatchStreamLogs off or role lacks logs:* permissions from the tier policyEnable streaming; attach AWSElasticBeanstalkWebTier

Cost and cleanup

What this lesson costs (us-east-1, checked 2026-11-18; confirm on the EC2 pricing page):

ResourceRateOne hour
Beanstalk serviceNo chargeUSD 0
1 × t4g.small Linux On-Demandabout USD 0.0168 per hour ⚠ VERIFYabout USD 0.02
Public IPv4 address on the instanceUSD 0.005 per hourUSD 0.005
EBS root volume (gp3, 8–10 GB)about USD 0.08 per GB-monthunder USD 0.01
S3 bundle storage and CloudWatch Logscentscents

Total: about USD 0.03 for an hour in a single-instance environment. A load-balanced environment adds an ALB (about USD 0.0225 per hour plus LCUs) and at least one more instance. Windows instances cost noticeably more than Linux because the licence is included. t4g instances may be covered by the account's free-tier offers ⚠ VERIFY your account's current free-tier terms.

Free alternative: run the app locally with dotnet run and PORT=5000, build the bundle, and run cdk synth or terraform plan without deploying.

Teardown:

export AWS_PROFILE=learn-sandbox AWS_REGION=us-east-1
aws elasticbeanstalk terminate-environment --environment-name hl-m03-accounts-dev
aws elasticbeanstalk wait environment-terminated --environment-names hl-m03-accounts-dev
# Deletes the application, all versions and their source bundles in S3.
aws elasticbeanstalk delete-application --application-name hl-m03-accounts --terminate-env-by-force
# Remove the IAM roles you created (skip if other environments use them).
aws iam remove-role-from-instance-profile --instance-profile-name hl-m03-eb-ec2 --role-name hl-m03-eb-ec2
aws iam delete-instance-profile --instance-profile-name hl-m03-eb-ec2
aws iam detach-role-policy --role-name hl-m03-eb-ec2 --policy-arn arn:aws:iam::aws:policy/AWSElasticBeanstalkWebTier
aws iam delete-role --role-name hl-m03-eb-ec2
aws iam detach-role-policy --role-name hl-m03-eb-service --policy-arn arn:aws:iam::aws:policy/service-role/AWSElasticBeanstalkEnhancedHealth
aws iam detach-role-policy --role-name hl-m03-eb-service --policy-arn arn:aws:iam::aws:policy/AWSElasticBeanstalkManagedUpdatesCustomerRolePolicy
aws iam delete-role --role-name hl-m03-eb-service
# Log groups are deleted on termination because DeleteOnTerminate=true; verify:
aws logs describe-log-groups --log-group-name-prefix /aws/elasticbeanstalk/hl-m03 --query 'logGroups[].logGroupName'
aws resourcegroupstaggingapi get-resources --tag-filters Key=Project,Values=cea-lab --query 'ResourceTagMappingList[].ResourceARN'

The elasticbeanstalk-us-east-1-<account> bucket itself remains (Beanstalk protects it with a bucket policy). It costs nothing when empty.

Exercises

  • 🟢 Guided: Deploy the Accounts API as a single-instance environment using the CLI steps, confirm /health/ready returns 200, then deploy v2 with the C# deployer.
  • 🟡 Challenge: Convert the environment to load-balanced with instances in private subnets, an internal ALB and the Immutable deployment policy. Deploy a version whose /health/ready returns 503 and observe the immutable rollback.
  • 🔴 Live problem: Ticket CHG-2209: "Security scan flagged our Beanstalk complaints app: IMDSv1 enabled, database password visible in console configuration, platform version 14 months old, instances with public IPs." Produce a remediation plan that can be applied without downtime.

Assignment

Add a beanstalk/ folder to your portfolio repository with the Procfile, the two .ebextensions files, the C# deployer and a Terraform or CDK definition of a hardened load-balanced environment. In the README, include a table of every AWS resource the environment creates and its hourly cost.

Solutions

Knowledge check

Interview questions

  • "When would you choose Beanstalk over ECS on Fargate?" — Small or legacy web apps where the team has no container skills, IIS-dependent apps, or .NET Framework apps that need Windows. For new, containerised banking APIs, Fargate offers per-task isolation, faster scaling and no instance patching.
  • "What does Beanstalk actually create?" — A CloudFormation stack with an Auto Scaling group, launch template, EC2 instances, security groups, optionally an ALB, CloudWatch alarms and scaling policies, plus an S3 bucket for bundles and logs. All billed normally.
  • "How do you keep Beanstalk instances patched?" — Managed platform updates with a weekly window and minor/patch level, which use immutable deployments; plus blue/green for major platform branch changes.
  • "How do you handle secrets on Beanstalk?" — Never as environment properties. Use the environmentsecrets namespace for bootstrap-time injection, or fetch at runtime from Secrets Manager with caching when rotation must be picked up without redeployment.

Certification practice

Completion checklist

  • I can name the AWS resources a load-balanced Beanstalk environment creates
  • I deployed the API to a single-instance .NET 10 environment (or completed the free design-only alternative)
  • I can pick a deployment policy and explain the rollback for each
  • I know how to keep secrets out of environment properties
  • I terminated the environment, deleted the application and checked for leftover tagged resources

Key takeaways

  • Beanstalk is the AWS service closest to Azure App Service, but it creates real EC2, Auto Scaling, ALB and CloudFormation resources in your account.
  • On Linux, nginx proxies to your app on PORT (5000 by default); always ship a Procfile.
  • Use immutable or traffic-splitting deployments in production, and blue/green (CNAME swap) for platform upgrades.
  • Harden by default: IMDSv2 only, private instances, managed platform updates, log streaming with retention, and no secrets in environment properties.
  • Choose the Windows/IIS platform only for apps that cannot run on Linux yet.

Further reading

Independent learning resource — not affiliated with, endorsed or sponsored by Amazon Web Services. AWS and related marks are trademarks of Amazon.com, Inc. or its affiliates. All banking data in examples is fictional. Sample architectures are for learning and are not automatically compliant with GDPR, PCI DSS or any banking regulation.

On this page