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.
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,.ebextensionsand 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
- Deploying .NET to ECS on Fargate — useful for comparison, not required.
- ASP.NET Core Web API on AWS: the baseline and Hosting options compared.
- VPC fundamentals and IAM in depth.
- Tools: AWS CLI v2 with the
learn-sandboxprofile, .NET 10 SDK, a zip tool (PowerShellCompress-Archiveorzip). Optional: the EB CLI (pip install awsebcli).
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:
| Term | Plain meaning | Azure App Service analogy |
|---|---|---|
| Application | A named container for versions and environments. | The App Service "app" name grouping |
| Application version | A specific, labelled source bundle (a zip in S3). Immutable. | A deployment package |
| Environment | A 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) |
| Platform | The 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 (
.ebextensionsand 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 publishto 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:DescribeConfigurationSettingscan 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 branch | Solution stack name | Runtime |
|---|---|---|
| .NET 10 on AL2023 version 3.12.3 | 64bit 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.10 | e.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-sandboxMicrosoft / Azure comparison
| You know (Microsoft/Azure) | AWS equivalent | What's different |
|---|---|---|
| Azure App Service (Linux) | Beanstalk .NET on AL2023 | Real 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 VM | Beanstalk .NET on Windows Server with IIS | Supports .NET Framework 4.x; deploy with Web Deploy archive or a deployment manifest |
| App Service plan (instance count/size) | Auto Scaling group + instance type settings | Scaling triggers are CloudWatch alarms (default: network out) — change them to CPU or request count |
| Deployment slots + swap | Second environment + Swap environment URLs (CNAME swap) | The swap changes DNS, so clients with cached DNS take time to move |
| App settings | Environment properties (aws:elasticbeanstalk:application:environment) | Plain text — use aws:elasticbeanstalk:application:environmentsecrets for secrets |
| Key Vault references | Environment secrets (Secrets Manager / Parameter Store ARNs) | Values fetched at instance bootstrap only, not on rotation |
| Managed identity | EC2 instance profile | One role for the whole instance; every process on it gets the permissions |
| Application Insights / Log stream | Enhanced health + CloudWatch Logs streaming | Health is a colour (Green/Yellow/Red/Grey) with causes; logs need StreamLogs turned on |
Kudu / web.config transforms | .ebextensions/*.config, .platform/ hooks and nginx config | YAML/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():
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:
| Boundary | Control | Default | What a bank sets |
|---|---|---|---|
| Internet → ALB | Listener, security group, WAF | HTTP 80 public | HTTPS 443 with ACM certificate; internal scheme for staff-only apps; WAF |
| ALB → instance | Instance security group | Allows 80 from ALB security group | Same; instances in private subnets |
| Instance → AWS APIs | Instance profile | aws-elasticbeanstalk-ec2-role with broad Beanstalk tier policies | Custom role: tier policy + only the app's data permissions |
| Instance metadata | IMDS | IMDSv1 and v2 may both be allowed | DisableIMDSv1: true |
| Logs | CloudWatch Logs | Off; bundles go to S3 | StreamLogs: true, retention, KMS-encrypted log groups |
| Patching | Managed platform updates | Off unless enabled | On, weekly window, minor + patch |
Deployment policies
| Policy | How it works | Downtime | Extra cost during deploy | Rollback |
|---|---|---|---|---|
| All at once | Deploy to every instance simultaneously | Yes, briefly | None | Redeploy previous version |
| Rolling | Batches of instances taken out of service and updated | No, but reduced capacity | None | Redeploy previous version |
| Rolling with additional batch | Launch an extra batch first, then roll | No, full capacity | One extra batch | Redeploy previous version |
| Immutable | Launch a full new set of instances in a temporary Auto Scaling group; swap in when healthy | No | Double the fleet briefly | Terminate the new group — fastest safe rollback |
| Traffic splitting | Canary: send a percentage of traffic to new instances for an evaluation period | No | New fleet | Automatic if health degrades |
| Blue/green (not a policy setting) | Clone to a new environment, deploy there, swap environment URLs | No | Second environment | Swap 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
- Console → Elastic Beanstalk → Create application. Environment tier Web server environment. Application name
hl-m03-accounts, environment namehl-m03-accounts-dev. - Platform: Managed platform → .NET Core on Linux → platform branch .NET 10 running on 64bit Amazon Linux 2023 → recommended version.
- Application code: Upload your code → choose the zip, version label
v1. - Presets: Single instance (free tier eligible) for the lab; High availability for production.
- 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-rolefirst.) - 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.
- Configure instance traffic and scaling: instance type
t4g.small(Graviton) ort3.small; IMDSv1: Deactivated. - 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. - Submit. Watch Events; when health turns Green, open the environment URL and request
/health/ready. - 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-greenWith 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.
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
web: dotnet ./Harbourline.Accounts.Api.dlloption_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# 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/KeyA 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.
<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>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
Procfile→web: dotnet ./Harbourline.Accounts.Api.dll— thewebprocess is the one nginx proxies to. Without a Procfile, the platform guesses the entry point from the*.runtimeconfig.jsonfile it finds; with several projects in the bundle, that guess fails, so always include one.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.DeploymentPolicy: Immutable— every deployment launches a fresh set of instances, so a bad version never touches the running fleet.DisableIMDSv1: true— the instance metadata service only accepts session-token (v2) requests, which blocks the classic SSRF credential theft.aws:elasticbeanstalk:cloudwatch:logs— streams/var/log/web.stdout.log, nginx logs and Beanstalk agent logs to CloudWatch with 7-day retention.aws:elasticbeanstalk:application:environment— plain-text environment variables.Hosting__TrustedProxyNetworks__0binds to the first element of theHosting:TrustedProxyNetworksarray used by the forwarded-headers setup.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
CreateStorageLocationAsync— returns (and creates if necessary) the per-Regionelasticbeanstalk-<region>-<account>bucket.PutObjectAsyncwithFilePath— uploads the zip. Credentials come from the default chain.CreateApplicationVersionAsyncwithProcess = true— Beanstalk validates the bundle (for example, malformed.ebextensionsYAML) before allowing deployment.DescribeApplicationVersionsAsyncloop — waits forProcessedorFailed. Note the v4 SDK pattern:ApplicationVersions?.FirstOrDefault().UpdateEnvironmentAsync— starts the deployment using the environment's configured policy.DescribeEventsAsyncwithStartTime— only events from this deployment. Beanstalk returns newest first, so the list is reversed.env.Status == Readyandenv.VersionLabel != label— after a failed immutable deployment Beanstalk returns to Ready on the old version. Checking the label catches this silent failure.env.Health—Green,Yellow,RedorGrey.HealthStatusgives 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:
{
"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
environmentsecretsor 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
EC2KeyNameempty 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
Procfileor the.dll→ zip from inside the publish folder. - App listens on 8080 because of
ASPNETCORE_HTTP_PORTS→ nginx returns 502 → listen onPORT(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
environmentsecretsor 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
| Symptom | Likely cause | Fix |
|---|---|---|
| 502 Bad Gateway from nginx | App not listening on PORT, or crashed on start | eb logs → web.stdout.log; listen on PORT |
| Environment creation fails: instance profile not found | No aws-elasticbeanstalk-ec2-role and none specified | Create the instance profile and set IamInstanceProfile |
Version status Failed after upload | Malformed .ebextensions YAML/JSON | Validate YAML; tabs are not allowed |
| Health Red: "100% of requests failing with 5xx" | App exceptions or wrong health check path | Check health check path and application logs |
| Health Yellow/Red: "Instance ELB health state has been Unhealthy" | Health check path requires authentication | Make /health/ready anonymous |
| Deployment "completed" but old version still running | Immutable deployment failed health and was rolled back | Check events; the deployer's version-label check catches this |
AccessDenied in app calling DynamoDB | Instance profile lacks permission | Add a scoped inline policy to the instance role |
| Logs not in CloudWatch | StreamLogs off or role lacks logs:* permissions from the tier policy | Enable streaming; attach AWSElasticBeanstalkWebTier |
Cost and cleanup
What this lesson costs (us-east-1, checked 2026-11-18; confirm on the EC2 pricing page):
| Resource | Rate | One hour |
|---|---|---|
| Beanstalk service | No charge | USD 0 |
1 × t4g.small Linux On-Demand | about USD 0.0168 per hour ⚠ VERIFY | about USD 0.02 |
| Public IPv4 address on the instance | USD 0.005 per hour | USD 0.005 |
| EBS root volume (gp3, 8–10 GB) | about USD 0.08 per GB-month | under USD 0.01 |
| S3 bundle storage and CloudWatch Logs | cents | cents |
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/readyreturns 200, then deployv2with the C# deployer. - 🟡 Challenge: Convert the environment to load-balanced with instances in private subnets, an internal ALB and the
Immutabledeployment policy. Deploy a version whose/health/readyreturns 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
Publish, add the Procfile, zip the folder contents, upload, create-application-version --process, then create-environment with EnvironmentType=SingleInstance. When describe-environment-health shows Ready/Green, curl http://$URL/health/ready returns the JSON health report. For v2, rebuild the zip and run dotnet run -- hl-m03-accounts hl-m03-accounts-dev ./accounts-v2.zip v2. Why single instance updates in place: there is no load balancer to drain, so Beanstalk deploys to the one instance and restarts the app. Expect a few seconds of errors — acceptable for dev, not for production.
Set aws:elasticbeanstalk:environment → EnvironmentType=LoadBalanced, LoadBalancerType=application; aws:ec2:vpc → VPCId, Subnets (private), ELBSubnets (private for internal), ELBScheme=internal, AssociatePublicIpAddress=false. With DeploymentPolicy=Immutable, Beanstalk launches a temporary Auto Scaling group with the new version. Because /health/ready returns 503, the new instances never pass the ALB health check, Beanstalk reports the deployment failed, terminates the temporary group, and the original instances never stopped serving. The environment returns to Ready on the old version label, which the C# deployer reports as a failure.
(1) IMDSv1: set DisableIMDSv1=true — it changes the launch template, so apply it with an immutable or rolling-with-additional-batch update. (2) Password: move it to Secrets Manager (with rotation) and reference it through environmentsecrets or fetch at runtime; then rotate the exposed password, because anyone who could read the configuration may have copied it; remove the property. (3) Old platform: clone the environment, upgrade the clone's platform, test, then swap CNAMEs (blue/green) — no downtime; then enable managed updates. (4) Public IPs: move instances to private subnets with AssociatePublicIpAddress=false; VPC/subnet changes require a new environment, so do it as part of the same blue/green clone. Record each change in the change ticket with before/after describe-configuration-settings output as evidence.
Knowledge check
Answer: Immutable. The new version runs on a separate temporary Auto Scaling group; rollback is just terminating it. Rolling policies have already modified existing instances, so rollback means another deployment.
Answer: nginx on the instance forwards to the port in the PORT environment variable (5000 by default). Kestrel is listening elsewhere, so nginx gets connection refused and returns 502.
Answer: Nothing until instances bootstrap again. The value is fetched at bootstrap, so you must update or rebuild the environment, or fetch the secret at runtime instead.
Answer: The Windows Server licence is included in the On-Demand instance price. Beanstalk itself costs nothing on either platform.
Answer: Create (or clone) a second environment, deploy the new version there, test it, then swap environment URLs, which swaps the CNAME records. Swap back to roll back. Keep DNS TTL effects in mind.
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
environmentsecretsnamespace for bootstrap-time injection, or fetch at runtime from Secrets Manager with caching when rotation must be picked up without redeployment.
Certification practice
A team deploys a .NET application to a load-balanced Elastic Beanstalk environment with four instances. Deployments must keep full capacity at all times and allow the quickest possible rollback if the new version fails health checks. Which deployment policy should they choose?
A. All at once B. Rolling C. Rolling with additional batch D. Immutable
Answer: D. Immutable deploys to a fresh temporary Auto Scaling group and only swaps when healthy; rollback is terminating that group. C keeps capacity but modifies existing instances, so rollback needs a redeploy. A causes downtime. B reduces capacity.
A developer must give a Beanstalk .NET application a database password. The password must not be visible in the Beanstalk console and must be centrally managed. What should the developer do?
A. Add the password as an environment property.
B. Store the password in Secrets Manager and map it with the aws:elasticbeanstalk:application:environmentsecrets namespace; grant the instance profile secretsmanager:GetSecretValue on that secret.
C. Put the password in appsettings.Production.json inside the source bundle.
D. Store the password in an .ebextensions file.
Answer: B. The secret stays in Secrets Manager and only its ARN appears in configuration. A is visible in the console. C and D put the secret in the bundle in S3 and in source control.
A company must move a .NET Framework 4.8 web application that depends on IIS to AWS within two weeks, with minimal code changes, managed patching and load balancing across two Availability Zones. Which solution fits best?
A. Containerise the app on Linux and run it on ECS on Fargate. B. Deploy it to Elastic Beanstalk on a Windows Server with IIS platform in a load-balanced environment with managed updates enabled. C. Rewrite the app as Lambda functions. D. Run it on a single EC2 Windows instance with a public IP.
Answer: B. The Windows/IIS platform runs .NET Framework 4.x unchanged and adds load balancing, Auto Scaling and managed updates. A needs a port to .NET 10 first. C is a rewrite. D has no high availability or managed patching.
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
- Elastic Beanstalk supported platforms
- Using the Elastic Beanstalk .NET Core on Linux platform
- Using a Procfile on the .NET Core on Linux platform
- Fetching secrets and parameters to Elastic Beanstalk environment variables
- Creating and deploying .NET applications on Elastic Beanstalk with the AWS Toolkit for Visual Studio
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.
Deploying .NET to ECS on Fargate
Deploy a containerised ASP.NET Core API to Amazon ECS on Fargate in private subnets behind an Application Load Balancer, with separate task and execution roles, safe rolling deployments and a C# rollout watcher.
Lambda with C#
Write, test and deploy C# Lambda functions on the dotnet10 runtime: plain handlers, the Lambda Annotations framework, a whole ASP.NET Core API inside Lambda, Native AOT, and the real options for cold starts including SnapStart and provisioned concurrency.