Skip to content
New issue

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

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

Already on GitHub? # to your account

❗️NOTICE: ECR: Template error: Cannot use Fn::ImportValue in Conditions. #32238

Closed
1 task done
Joe-Zer0 opened this issue Nov 21, 2024 · 3 comments · Fixed by #32241
Closed
1 task done

❗️NOTICE: ECR: Template error: Cannot use Fn::ImportValue in Conditions. #32238

Joe-Zer0 opened this issue Nov 21, 2024 · 3 comments · Fixed by #32241
Labels
@aws-cdk/aws-ecr Related to Amazon Elastic Container Registry bug This issue is a bug. effort/medium Medium work item – several days of effort management/tracking Issues that track a subject or multiple issues p0 potential-regression Marking this issue as a potential regression to be checked by team member

Comments

@Joe-Zer0
Copy link

Joe-Zer0 commented Nov 21, 2024

Please add your +1 👍 to let us know you have encountered this

Status: RESOLVED

Overview:

When retrieving an image with a tag equal to the environment name, which is stored as a CFN Export.

aws_ecs.ContainerImage.from_ecr_repository(
    repository=aws_ecr.Repository.from_repository_arn(
        self, "ECRRepo", repository_arn="arn:aws:ecr:us-east-1:12345:repository/my-repo"
    ),
    tag=Fn.import_value("Environment")
)

Resultant CFN YAML
aws-cdk-lib==2.166.0

  TaskDefinitionB36D86D9:
    Type: AWS::ECS::TaskDefinition
    Properties:
      ContainerDefinitions:
        - Essential: true
          Image:
            Fn::Join:
              - ""
              - - 12345.dkr.ecr.us-east-1.
                - Ref: AWS::URLSuffix
                - "/my-repo:"
                - Fn::ImportValue: Environment
          Name: Container

aws-cdk-lib==2.167.0

  TaskDefinitionB36D86D9:
    Type: AWS::ECS::TaskDefinition
    Properties:
      ContainerDefinitions:
        - Essential: true
          Image:
            Fn::Join:
              - ""
              - - 12345.dkr.ecr.us-east-1.
                - Ref: AWS::URLSuffix
                - /my-repo
                - Fn::If:
                    - ECRRepoIsInputDigest1074C652E
                    - Fn::Join:
                        - ""
                        - - "@"
                          - Fn::ImportValue: Environment
                    - Fn::Join:
                        - ""
                        - - ":"
                          - Fn::ImportValue: Environment
          Name: Container

In 2.167.0 there exists Fn::ImportValue is now in an Fn::If Condition. Which gives the error "Template error: Cannot use Fn::ImportValue in Conditions." when deploying.

Complete Error Message:

Template error: Cannot use Fn::ImportValue in Conditions.

Workaround:

Pin aws-cdk-lib to "2.166.0".

Solution:

Describe the bug

This works in 2.166.0, but does not work in 2.167.0. I believe it is due to this commit.

We are retrieving an image with a tag equal to the environment name, which is stored as a CFN Export.

aws_ecs.ContainerImage.from_ecr_repository(
    repository=aws_ecr.Repository.from_repository_arn(
        self, "ECRRepo", repository_arn="arn:aws:ecr:us-east-1:12345:repository/my-repo"
    ),
    tag=Fn.import_value("Environment")
)

Resultant CFN YAML
aws-cdk-lib==2.166.0

  TaskDefinitionB36D86D9:
    Type: AWS::ECS::TaskDefinition
    Properties:
      ContainerDefinitions:
        - Essential: true
          Image:
            Fn::Join:
              - ""
              - - 12345.dkr.ecr.us-east-1.
                - Ref: AWS::URLSuffix
                - "/my-repo:"
                - Fn::ImportValue: Environment
          Name: Container

aws-cdk-lib==2.167.0

  TaskDefinitionB36D86D9:
    Type: AWS::ECS::TaskDefinition
    Properties:
      ContainerDefinitions:
        - Essential: true
          Image:
            Fn::Join:
              - ""
              - - 12345.dkr.ecr.us-east-1.
                - Ref: AWS::URLSuffix
                - /my-repo
                - Fn::If:
                    - ECRRepoIsInputDigest1074C652E
                    - Fn::Join:
                        - ""
                        - - "@"
                          - Fn::ImportValue: Environment
                    - Fn::Join:
                        - ""
                        - - ":"
                          - Fn::ImportValue: Environment
          Name: Container

In 2.167.0 you can see that the Fn::ImportValue is now in an Fn::If Condition. Which gives the error "Template error: Cannot use Fn::ImportValue in Conditions." when deploying.

Regression Issue

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

Last Known Working CDK Version

2.166.0

Expected Behavior

Resultant CFN will deploy to AWS.

Current Behavior

Resultant CFN gives the error "Template error: Cannot use Fn::ImportValue in Conditions." when deploying to AWS.

Reproduction Steps

Run cdk synth with the following files with aws-cdk-lib==2.167.0.

cdk.json

{
  "app": "python app.py"
}

app.py

from aws_cdk import (
    App,
    Environment,
    Fn,
    Stack,
    aws_ecr,
    aws_ecs
)
from constructs import Construct
import os

class AwsCdkStack(Stack):
    def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
        super().__init__(scope, construct_id, **kwargs)

        task_definition = aws_ecs.FargateTaskDefinition(
            self,
            'TaskDefinition'
        )
        task_definition.add_container(
            'Container',
            image = aws_ecs.ContainerImage.from_ecr_repository(
                repository=aws_ecr.Repository.from_repository_arn(
                    self, "ECRRepo", repository_arn="arn:aws:ecr:us-east-1:12345:repository/my-repo"
                ),
                tag=Fn.import_value("Environment")
            )
        )

app = App()
AwsCdkStack(
    app,
    'my-stack',
    env = Environment(account = os.environ.get('CDK_DEFAULT_ACCOUNT'), region = os.environ.get('CDK_DEFAULT_REGION'))
)
app.synth()

Possible Solution

No response

Additional Information/Context

No response

CDK CLI Version

2.167.0

Framework Version

No response

Node.js Version

v20.17.0

OS

Windows 10

Language

Python

Language Version

No response

Other information

No response

@Joe-Zer0 Joe-Zer0 added bug This issue is a bug. needs-triage This issue or PR still needs to be triaged. labels Nov 21, 2024
@github-actions github-actions bot added the @aws-cdk/aws-ecr Related to Amazon Elastic Container Registry label Nov 21, 2024
@ashishdhingra
Copy link
Contributor

Reproducible using CDK version 2.169.0 using customer's code.

Running cdk synth produces the below CFN template:

Resources:
  TaskDefinitionTaskRoleFD40A61D:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Statement:
          - Action: sts:AssumeRole
            Effect: Allow
            Principal:
              Service: ecs-tasks.amazonaws.com
        Version: "2012-10-17"
    Metadata:
      aws:cdk:path: my-stack/TaskDefinition/TaskRole/Resource
  TaskDefinitionB36D86D9:
    Type: AWS::ECS::TaskDefinition
    Properties:
      ContainerDefinitions:
        - Essential: true
          Image:
            Fn::Join:
              - ""
              - - 12345.dkr.ecr.us-east-1.
                - Ref: AWS::URLSuffix
                - /my-repo
                - Fn::If:
                    - ECRRepoIsInputDigest1074C652E
                    - Fn::Join:
                        - ""
                        - - "@"
                          - Fn::ImportValue: Environment
                    - Fn::Join:
                        - ""
                        - - ":"
                          - Fn::ImportValue: Environment
          Name: Container
      Cpu: "256"
      ExecutionRoleArn:
        Fn::GetAtt:
          - TaskDefinitionExecutionRole8D61C2FB
          - Arn
      Family: mystackTaskDefinition2584F5A1
      Memory: "512"
      NetworkMode: awsvpc
      RequiresCompatibilities:
        - FARGATE
      TaskRoleArn:
        Fn::GetAtt:
          - TaskDefinitionTaskRoleFD40A61D
          - Arn
    Metadata:
      aws:cdk:path: my-stack/TaskDefinition/Resource
  TaskDefinitionExecutionRole8D61C2FB:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Statement:
          - Action: sts:AssumeRole
            Effect: Allow
            Principal:
              Service: ecs-tasks.amazonaws.com
        Version: "2012-10-17"
      Tags:
        - Key: aws-cdk:id
          Value: my-stack_c8c1b9dd68a0daa0e77928f61c00ac4bca0bd07573
    Metadata:
      aws:cdk:path: my-stack/TaskDefinition/ExecutionRole/Resource
  TaskDefinitionExecutionRoleDefaultPolicy1F3406F5:
    Type: AWS::IAM::Policy
    Properties:
      PolicyDocument:
        Statement:
          - Action:
              - ecr:BatchCheckLayerAvailability
              - ecr:BatchGetImage
              - ecr:GetDownloadUrlForLayer
            Effect: Allow
            Resource: arn:aws:ecr:us-east-1:12345:repository/my-repo
          - Action: ecr:GetAuthorizationToken
            Effect: Allow
            Resource: "*"
        Version: "2012-10-17"
      PolicyName: TaskDefinitionExecutionRoleDefaultPolicy1F3406F5
      Roles:
        - Ref: TaskDefinitionExecutionRole8D61C2FB
    Metadata:
      aws:cdk:path: my-stack/TaskDefinition/ExecutionRole/DefaultPolicy/Resource
  CDKMetadata:
    Type: AWS::CDK::Metadata
    Properties:
      Analytics: v2:deflate64:H4sIAAAAAAAA/12NQQuCQBSEf4v39ZUWQdeMzmLd47U+66Xui90VkcX/HioVdJqZbxgmhWS3h3WEvYt1WccN3yCcPepaYe+ugbSDcEJ7R08XdPWRKjbsWYzKKvNPxHhkQ/bHRsXYQiikoWkway4N62GKixsVaQsFvcSxFzsc0NGoCnLSWT3PMjHl9/RTjCof/EPMagNJCtvo6Zhj2xnPLUGx6BttU00i3wAAAA==
    Metadata:
      aws:cdk:path: my-stack/CDKMetadata/Default
Conditions:
  ECRRepoIsInputDigest1074C652E:
    Fn::Equals:
      - Fn::Select:
          - 0
          - Fn::Split:
              - ":"
              - Fn::ImportValue: Environment
      - sha256
Parameters:
  BootstrapVersion:
    Type: AWS::SSM::Parameter::Value<String>
    Default: /cdk-bootstrap/hnb659fds/version
    Description: Version of the CDK Bootstrap resources in this environment, automatically retrieved from SSM Parameter Store. [cdk:skip]

Running cdk deploy gives the error:

   Synthesis time: 5.13s

Stack undefined
This deployment will make potentially sensitive changes according to your current security approval level (--require-approval broadening).
Please confirm you intend to make the following modifications:

IAM Statement Changes
┌───┬────────────────────────────────────────────────┬────────┬────────────────────────────────────────────────────────────────────────────┬─────────────────────────────────────┬───────────┐
│   │ Resource                                       │ Effect │ Action                                                                     │ Principal                           │ Condition │
├───┼────────────────────────────────────────────────┼────────┼────────────────────────────────────────────────────────────────────────────┼─────────────────────────────────────┼───────────┤
│ + │ ${TaskDefinition/ExecutionRole.Arn}            │ Allow  │ sts:AssumeRole                                                             │ Service:ecs-tasks.amazonaws.com     │           │
├───┼────────────────────────────────────────────────┼────────┼────────────────────────────────────────────────────────────────────────────┼─────────────────────────────────────┼───────────┤
│ + │ ${TaskDefinition/TaskRole.Arn}                 │ Allow  │ sts:AssumeRole                                                             │ Service:ecs-tasks.amazonaws.com     │           │
├───┼────────────────────────────────────────────────┼────────┼────────────────────────────────────────────────────────────────────────────┼─────────────────────────────────────┼───────────┤
│ + │ *                                              │ Allow  │ ecr:GetAuthorizationToken                                                  │ AWS:${TaskDefinition/ExecutionRole} │           │
├───┼────────────────────────────────────────────────┼────────┼────────────────────────────────────────────────────────────────────────────┼─────────────────────────────────────┼───────────┤
│ + │ arn:aws:ecr:us-east-1:12345:repository/my-repo │ Allow  │ ecr:BatchCheckLayerAvailability                                            │ AWS:${TaskDefinition/ExecutionRole} │           │
│   │                                                │        │ ecr:BatchGetImage                                                          │                                     │           │
│   │                                                │        │ ecr:GetDownloadUrlForLayer                                                 │                                     │           │
└───┴────────────────────────────────────────────────┴────────┴────────────────────────────────────────────────────────────────────────────┴─────────────────────────────────────┴───────────┘
(NOTE: There may be security-related changes not in this list. See https://github.com/aws/aws-cdk/issues/1299)

Do you wish to deploy these changes (y/n)? y
my-stack: deploying... [1/1]
my-stack: creating CloudFormation changeset...
❌  my-stack failed: ValidationError: Template error: Cannot use Fn::ImportValue in Conditions.

Using CDK version 2.166.0 produces the below CFN template when running cdk synth:

Resources:
  TaskDefinitionTaskRoleFD40A61D:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Statement:
          - Action: sts:AssumeRole
            Effect: Allow
            Principal:
              Service: ecs-tasks.amazonaws.com
        Version: "2012-10-17"
    Metadata:
      aws:cdk:path: my-stack/TaskDefinition/TaskRole/Resource
  TaskDefinitionB36D86D9:
    Type: AWS::ECS::TaskDefinition
    Properties:
      ContainerDefinitions:
        - Essential: true
          Image:
            Fn::Join:
              - ""
              - - 12345.dkr.ecr.us-east-1.
                - Ref: AWS::URLSuffix
                - "/my-repo:"
                - Fn::ImportValue: Environment
          Name: Container
      Cpu: "256"
      ExecutionRoleArn:
        Fn::GetAtt:
          - TaskDefinitionExecutionRole8D61C2FB
          - Arn
      Family: mystackTaskDefinition2584F5A1
      Memory: "512"
      NetworkMode: awsvpc
      RequiresCompatibilities:
        - FARGATE
      TaskRoleArn:
        Fn::GetAtt:
          - TaskDefinitionTaskRoleFD40A61D
          - Arn
    Metadata:
      aws:cdk:path: my-stack/TaskDefinition/Resource
  TaskDefinitionExecutionRole8D61C2FB:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Statement:
          - Action: sts:AssumeRole
            Effect: Allow
            Principal:
              Service: ecs-tasks.amazonaws.com
        Version: "2012-10-17"
      Tags:
        - Key: aws-cdk:id
          Value: my-stack_c8c1b9dd68a0daa0e77928f61c00ac4bca0bd07573
    Metadata:
      aws:cdk:path: my-stack/TaskDefinition/ExecutionRole/Resource
  TaskDefinitionExecutionRoleDefaultPolicy1F3406F5:
    Type: AWS::IAM::Policy
    Properties:
      PolicyDocument:
        Statement:
          - Action:
              - ecr:BatchCheckLayerAvailability
              - ecr:BatchGetImage
              - ecr:GetDownloadUrlForLayer
            Effect: Allow
            Resource: arn:aws:ecr:us-east-1:12345:repository/my-repo
          - Action: ecr:GetAuthorizationToken
            Effect: Allow
            Resource: "*"
        Version: "2012-10-17"
      PolicyName: TaskDefinitionExecutionRoleDefaultPolicy1F3406F5
      Roles:
        - Ref: TaskDefinitionExecutionRole8D61C2FB
    Metadata:
      aws:cdk:path: my-stack/TaskDefinition/ExecutionRole/DefaultPolicy/Resource
  CDKMetadata:
    Type: AWS::CDK::Metadata
    Properties:
      Analytics: v2:deflate64:H4sIAAAAAAAA/12LQQrCMBBFz9J9OtoqPYCK6xLdyxinOrZNJJNSSsjdpVYQXL33H/wSiqqCdYaj5ObW5h1fIZ4CmlbhKJdIRiAe0d8x0BmlPVDDlgM7q/aN/S/OBmRL/teSYuwhatfRfPiwdh2baZ6LJUXGg6aXEw7OTzsUSkqTuMGb5fb1pOopPJxdbaAoYZs9hTn3gw3cE+iFb6pXnajSAAAA
    Metadata:
      aws:cdk:path: my-stack/CDKMetadata/Default
Parameters:
  BootstrapVersion:
    Type: AWS::SSM::Parameter::Value<String>
    Default: /cdk-bootstrap/hnb659fds/version
    Description: Version of the CDK Bootstrap resources in this environment, automatically retrieved from SSM Parameter Store. [cdk:skip]

Running cdk deploy works fine thereafter.

@ashishdhingra ashishdhingra self-assigned this Nov 22, 2024
@ashishdhingra ashishdhingra added p1 effort/medium Medium work item – several days of effort p0 and removed needs-triage This issue or PR still needs to be triaged. p1 labels Nov 22, 2024
@ashishdhingra ashishdhingra removed their assignment Nov 22, 2024
@github-actions github-actions bot added the potential-regression Marking this issue as a potential regression to be checked by team member label Nov 22, 2024
@Leo10Gama Leo10Gama added the management/tracking Issues that track a subject or multiple issues label Nov 22, 2024
@Leo10Gama Leo10Gama pinned this issue Nov 22, 2024
@mergify mergify bot closed this as completed in #32241 Nov 22, 2024
@mergify mergify bot closed this as completed in b3e39a9 Nov 22, 2024
Copy link

Comments on closed issues and PRs are hard for our team to see.
If you need help, please open a new issue that references this one.

1 similar comment
Copy link

Comments on closed issues and PRs are hard for our team to see.
If you need help, please open a new issue that references this one.

@github-actions github-actions bot locked as resolved and limited conversation to collaborators Nov 22, 2024
@Leo10Gama Leo10Gama changed the title ECR: Template error: Cannot use Fn::ImportValue in Conditions. ❗️NOTICE: ECR: Template error: Cannot use Fn::ImportValue in Conditions. Nov 22, 2024
@shikha372 shikha372 unpinned this issue Dec 23, 2024
# for free to subscribe to this conversation on GitHub. Already have an account? #.
Labels
@aws-cdk/aws-ecr Related to Amazon Elastic Container Registry bug This issue is a bug. effort/medium Medium work item – several days of effort management/tracking Issues that track a subject or multiple issues p0 potential-regression Marking this issue as a potential regression to be checked by team member
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants