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

aws_ecs_patterns: ApplicationLoadBalancedFargateService does not honor task image options (cpu, memory, environment,) and secrets are typed incorrectly not allowing them to be used. #33988

Closed
1 task
Xenoha opened this issue Mar 31, 2025 · 6 comments
Labels
@aws-cdk/aws-ecs-patterns Related to ecs-patterns library bug This issue is a bug. closed-for-staleness This issue was automatically closed because it hadn't received any attention in a while. p3 response-requested Waiting on additional info and feedback. Will move to "closing-soon" in 7 days.

Comments

@Xenoha
Copy link

Xenoha commented Mar 31, 2025

Describe the bug

When I create a alb fargate construct as the following

const fargate = new ApplicationLoadBalancedFargateService(this, 'fargate', { cluster, publicLoadBalancer: true, memoryLimitMiB: 1024, cpu: 512, desiredCount: 1, circuitBreaker: { rollback: true, }, taskImageOptions: { image: ContainerImage.fromRegistry('nginx'), containerName: 'pdp', containerPort: 7000, enableLogging: true, environment: { ENVIRONMENT_ONE: process.env.environmentOne, }, }, })

It will create cloudformation that looks correct, however, the stack doesn't look to honor the configured cpu, memoryLimitMiB and the environment.

When I went to use a the secrets property in typescript it is typed with values being Secret.

When creating a new Secret and passing in as a value, I get a type error signifying that Secret is missing the property 'arn'.

when looking up a Secret you get back a type ISecret, so I don't see a way that this is used.

Regression Issue

  • Select this option if this issue appears to be a regression.

Last Known Working CDK Version

No response

Expected Behavior

I would expect environment to be passed to my fargate task def.

Current Behavior

environment is showing up as an empty array.

Reproduction Steps

Using typescript, create a ALB fargate service with a simple docker image from the registry and place environment variables per the props.

After this synth's correctly, see that the deployed task def doesn't include the properties in the environments array.

Try to use this construct while defining secrets.

Possible Solution

Secrets should be able to be defined from ISecret using the latest Secret.fromSecretNameV2 method on the Secret construct.

Additional Information/Context

No response

CDK CLI Version

2.1006.0 (build a3b9762)

Framework Version

2.1006.0

Node.js Version

22.12.0

OS

Linux 24.04.2 LTS

Language

TypeScript

Language Version

5.8.2

Other information

No response

@Xenoha Xenoha added bug This issue is a bug. needs-triage This issue or PR still needs to be triaged. labels Mar 31, 2025
@github-actions github-actions bot added the @aws-cdk/aws-ecs-patterns Related to ecs-patterns library label Mar 31, 2025
@pahud
Copy link
Contributor

pahud commented Mar 31, 2025

Hi

Are you able to provide a minimal code with all relevant properties and what you expect to see as well as what you actually have so we can reproduce it?

@Xenoha
Copy link
Author

Xenoha commented Mar 31, 2025

const fargate = new ApplicationLoadBalancedFargateService(this, 'fargate', { cluster, publicLoadBalancer: true, memoryLimitMiB: 1024, cpu: 512, desiredCount: 1, circuitBreaker: { rollback: true, }, taskImageOptions: { image: ContainerImage.fromRegistry('nginx'), containerName: 'pdp', containerPort: 7000, enableLogging: true, environment: { ENVIRONMENT_ONE: process.env.environmentOne, }, }, })

should produce a template of:
"fargateTaskDefFoo": { "Type": "AWS::ECS::TaskDefinition", "Properties": { "ContainerDefinitions": [ { "Environment": [ { "Name": "ENVIRONMENT_ONE", "Value": "foo_Bar_test" } ], "Essential": true, "Image": "nginx:latest", "LogConfiguration": { "LogDriver": "awslogs", "Options": { "awslogs-group": { "Ref": "fargateTaskDefpdpLogGroupFoo" }, "awslogs-stream-prefix": "fargate", "awslogs-region": "us-east-1" } }, "Name": "pdp", "PortMappings": [ { "ContainerPort": 7000, "Protocol": "tcp" } ] } ], "Cpu": "512", "ExecutionRoleArn": { "Fn::GetAtt": [ "fargateTaskDefExecutionRoleFoo", "Arn" ] }, "Family": "awsFamily", "Memory": "1024", "NetworkMode": "awsvpc", "RequiresCompatibilities": [ "FARGATE" ], "TaskRoleArn": { "Fn::GetAtt": [ "fargateTaskDefTaskRoleFoo", "Arn" ] } }, "Metadata": { "aws:cdk:path": "path" } },

Which should product the following task Def:

{ "taskDefinitionArn": "arn:aws:ecs:us-east-1:foo", "containerDefinitions": [ { "name": "foo", "image": "nginx:latest", "cpu": 256, "memory": 1024, "portMappings": [ { "containerPort": 7000, "hostPort": 7000, "protocol": "tcp" } ], "essential": true, "environment": [ { "name": "ENVIRONMENT_ONE", "value": "foo_Bar_test" } ], "mountPoints": [], "volumesFrom": [], "dockerLabels": {}, "logConfiguration": { "logDriver": "awslogs", "options": { "awslogs-group": "Foo-Group", "awslogs-region": "us-east-1", "awslogs-stream-prefix": "fargate" } }, "systemControls": [] } ], "family": "awsFamily", "taskRoleArn": "arn", "executionRoleArn": "arn", "networkMode": "awsvpc", "revision": 1, "volumes": [], "status": "ACTIVE", "requiresAttributes": [ { "name": "com.amazonaws.ecs.capability.logging-driver.awslogs" }, { "name": "ecs.capability.execution-role-awslogs" }, { "name": "com.amazonaws.ecs.capability.docker-remote-api.1.19" }, { "name": "com.amazonaws.ecs.capability.task-iam-role" }, { "name": "com.amazonaws.ecs.capability.docker-remote-api.1.18" }, { "name": "ecs.capability.task-eni" } ], "placementConstraints": [], "compatibilities": [ "EC2", "FARGATE" ], "requiresCompatibilities": [ "FARGATE" ], "cpu": "512", "memory": "1024", "registeredAt": "timestamp", "registeredBy": "fooRole" }

@pahud pahud removed the needs-triage This issue or PR still needs to be triaged. label Mar 31, 2025
@pahud
Copy link
Contributor

pahud commented Apr 1, 2025

Reproduction

import * as cdk from 'aws-cdk-lib';
import { Construct } from 'constructs';
import * as ec2 from 'aws-cdk-lib/aws-ec2';
import * as ecs from 'aws-cdk-lib/aws-ecs';
import * as ecs_patterns from 'aws-cdk-lib/aws-ecs-patterns';

export class Issue33988ReproStack extends cdk.Stack {
  constructor(scope: Construct, id: string, props?: cdk.StackProps) {
    super(scope, id, props);

   // default VPC
    const vpc = ec2.Vpc.fromLookup(this, 'DefaultVpc', { isDefault: true });

    // Create an ECS cluster
    const cluster = new ecs.Cluster(this, 'ReproCluster', { vpc });

    // Define the ALB Fargate Service as described in the issue comment
    const fargateService = new ecs_patterns.ApplicationLoadBalancedFargateService(this, 'ReproFargateService', {
      cluster,
      publicLoadBalancer: true,
      memoryLimitMiB: 1024,
      cpu: 512,
      desiredCount: 1,
      circuitBreaker: {
        rollback: true,
      },
      taskImageOptions: {
        image: ecs.ContainerImage.fromRegistry('nginx'), // Using nginx as specified
        containerName: 'pdp', // Container name from comment
        containerPort: 7000, // Container port from comment
        enableLogging: true,
        environment: {
          // Hardcoding the value for reproducibility instead of process.env
          ENVIRONMENT_ONE: 'repro_value_from_cdk',
        },
        // Note: Secrets part of the issue is not included here to focus on the environment variable problem first.
      },
      // Assign public IP to easily test the nginx service if needed, though not strictly required for the repro
      assignPublicIp: true,
    });

    // Output the Load Balancer DNS Name
    new cdk.CfnOutput(this, 'LoadBalancerDNS', {
      value: fargateService.loadBalancer.loadBalancerDnsName,
    });
  }
}

On cdk synth

The AWS::ECS::TaskDefinition resource (ReproFargateServiceTaskDefA8C9BC97) within the template correctly includes the environment variable:

  "ReproFargateServiceTaskDefA8C9BC97": {
   "Type": "AWS::ECS::TaskDefinition",
   "Properties": {
    "ContainerDefinitions": [
     {
      "Environment": [
       {
        "Name": "ENVIRONMENT_ONE",
        "Value": "repro_value_from_cdk" // Correctly included
       }
      ],
      // ... other container properties ...
      "Name": "pdp"
     }
    ],
    // ... other task definition properties ...
    "Cpu": "512",
    "Memory": "1024"
   }
   // ...
  }

And if I go to ECS console I can see this

Image

so I think this works as expected.

Now if I define the env var like this:

        environment: {
          ENVIRONMENT_ONE: process.env.environmentOne!,
        },

And deploy like this to pass the env var

 % environmentOne=foo_Bar_test npx cdk deploy Issue33988ReproStack --require-approval never 

This works as well

% aws ecs describe-task-definition --task-definition Issue33988ReproStackReproFargateServiceTaskDef0619FE42  --query 'taskDefinition.containerDefinitions[?name==`pdp`].environment'

[
    [
        {
            "name": "ENVIRONMENT_ONE",
            "value": "foo_Bar_test"
        }
    ]
]

Let me know if it works for you.

@pahud pahud added response-requested Waiting on additional info and feedback. Will move to "closing-soon" in 7 days. p3 labels Apr 1, 2025
@Xenoha
Copy link
Author

Xenoha commented Apr 1, 2025

You are correct! I found my issue. I am doing a pipeline, and the cdk.out shows it correct in the stage template output, but when deployed and running the variable isn't available. I guess my double check before creating the issue was against the same template from cdk.out at the time of synth, not what was provided to the account stage.

This brings me to the second issue. Can you do the same thing, but show me an example where you are using a secret. The secret can be defined in the code as another contruct as 'foo_bar'.

	const secret = new Secret(this, 'secret', {
		secretName: 'test-secret',
		secretStringValue: SecretValue.unsafePlainText('foo_bar')
	})

secrets: { SECRET_ONE: secret }

Does not work as it isn't typed correctly.

@github-actions github-actions bot removed the response-requested Waiting on additional info and feedback. Will move to "closing-soon" in 7 days. label Apr 1, 2025
@pahud
Copy link
Contributor

pahud commented Apr 1, 2025

Hi @Xenoha

If you need to use secrets for container environments, check out the sample here:

https://github.com/aws/aws-cdk/tree/main/packages/aws-cdk-lib/aws-ecs#environment-variables

@pahud pahud added the response-requested Waiting on additional info and feedback. Will move to "closing-soon" in 7 days. label Apr 1, 2025
Copy link

github-actions bot commented Apr 3, 2025

This issue has not received a response in a while. If you want to keep this issue open, please leave a comment below and auto-close will be canceled.

@github-actions github-actions bot added closing-soon This issue will automatically close in 4 days unless further comments are made. closed-for-staleness This issue was automatically closed because it hadn't received any attention in a while. and removed closing-soon This issue will automatically close in 4 days unless further comments are made. labels Apr 3, 2025
@github-actions github-actions bot closed this as completed Apr 9, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
@aws-cdk/aws-ecs-patterns Related to ecs-patterns library bug This issue is a bug. closed-for-staleness This issue was automatically closed because it hadn't received any attention in a while. p3 response-requested Waiting on additional info and feedback. Will move to "closing-soon" in 7 days.
Projects
None yet
Development

No branches or pull requests

2 participants