aws / aws/aws-cdk

EC2 fails when importing cdk

Open
#31,724 6 comments 0 reactions 0 assignees View on GitHub
@aws-cdk/aws-ec2 bug effort/medium p2
Dominant language
TypeScript
Stars
12.9k
Forks
4.6k
Avg merge
2d 3h
Merged PRs (30d)
83

Description

### Describe the bug

When creating an EC2 in the AWS Management Console and importing it into the cdk using the cdk import command, the following error occurs and prevents importing
```
❌ ec2-1 failed: Error [ValidationError]: Template error: Mapping named 'MyInstancerestoreAmiMapA3AA9468' is not present in the 'Mappings' section of template.
at Request.extractError (C:\Users\61-202111-3263-user\Desktop\new folder\node_modules\aws-cdk\lib\index.js:373:46692)
at Request.callListeners (C:\Users\61-202111-3263-user\Desktop\new folder\node_modules\aws-cdk\lib\index.js:373:91385)
at Request.emit (C:\Users\61-202111-3263-user\Desktop\new folder\node_modules\aws-cdk\lib\index.js:373:90833)
at Request.emit (C:\Users\61-202111-3263-user\Desktop\new folder\node_modules\aws-cdk\lib\index.js:373:199229)
at Request.transition (C:\Users\61-202111-3263-user\Desktop\new folder\node_modules\aws-cdk\lib\index.js:373:192781)
at AcceptorStateMachine.runTo (C:\Users\61-202111-3263-user\Desktop\new folder\node_modules\aws-cdk\lib\index.js:373:157653)
at C:\Users\61-202111-3263-user\Desktop\new folder\node_modules\aws-cdk\lib\index.js:373:157983
at Request.callListeners (C:\Users\61-202111-3263-user\Desktop\new folder\node_modules\aws-cdk\lib\index.js:373:91553) {
code: 'ValidationError',.
time: 2024-10-09T06:27:13.516Z,.
}

Template error: Mapping named 'MyInstancerestoreAmiMapA3AA9468' is not present in the 'Mappings' section of the template.
```

### Regression Issue

- [ ] Select this option if this issue appears to be a regression.

### Last Known Working CDK Version

_No response_

### Expected Behavior

When executing the cdk import command, you will be prompted for the EC2 instanceID, and if you enter it, the EC2 instance will be imported into the CDK code.

### Current Behavior

The following error is output
```
❌ ec2-1 failed: error [ValidationError]: template error: the mapping named 'MyInstancerestoreAmiMapA3AA9468' does not exist in the 'Mappings' section of the template.
at Request.extractError (C:\Users\61-202111-3263-user\Desktop\ new folder\node_modules\aws-cdk\lib\index.js:373:46692)
at Request.callListeners (C:\Users\61-202111-3263-user\Desktop\new folder\node_modules\aws-cdk\lib\index.js:373:91385)
at Request.emit (C:\Users\61-202111-3263-user\Desktop\new folder\node_modules\aws-cdk\lib\index.js:373:90833)
at Request.emit (C:\Users\61-202111-3263-user\Desktop\new folder\node_modules\aws-cdk\lib\index.js:373:199229)
at Request.transition (C:\Users\61-202111-3263-user\Desktop\new folder\node_modules\aws-cdk\lib\index.js:373:192781)
at AcceptorStateMachine.runTo (C:◆Users61-202111-3263-user;Desktop;node_modules;aws-cdk;libindex.js:373:157653).
at C:\Users\61-202111-3263-user\Desktop\New folder\node_modules\aws-cdk\lib\index.js:373:157983
at Request.callListeners (C:\Users\61-202111-3263-user\Desktop\new folder\node_modules\aws-cdk\lib\index.js:373:91553) {
code: ValidationError',
time: 2024-10-09T06:27:13.516Z,.
}

Template error: the mapping named 'MyInstancerestoreAmiMapA3AA9468' does not exist in the 'Mappings' section of the template.
```

### Reproduction Steps

I created the following typescript in the CDK lib folder and tried to import a service with a definition of “MyInstance_restor”
```TypeScript
import * as cdk from 'aws-cdk-lib';
import { Construct } from 'constructs';
import { StackProps } from 'aws-cdk-lib'
import * as ec2 from 'aws-cdk-lib/aws-ec2';
import * as route53 from 'aws-cdk-lib/aws-route53'
import * as cloudwatch from 'aws-cdk-lib/aws-cloudwatch'
import * as elasticloadbalancingv2targets from 'aws-cdk-lib/aws-elasticloadbalancingv2-targets'
import { aws_elasticloadbalancingv2 as elbv2 } from 'aws-cdk-lib'
import { StringParameter } from 'aws-cdk-lib/aws-ssm';
import { aws_iam as iam } from 'aws-cdk-lib'

import { CfnMapping } from 'aws-cdk-lib'
import * as sqs from 'aws-cdk-lib/aws-sqs';

interface Props extends StackProps {
vpc: ec2.Vpc
}

export class EC2_1 extends cdk.Stack {

public testtg1: elbv2.ApplicationTargetGroup

constructor(scope: Construct, id: string, props: Props) {
super(scope, id, props);

const SSMPolicy = iam.ManagedPolicy.fromManagedPolicyArn(
this,
'SSMPolicy',
'arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore'
)
const CloudWatchPolicy = iam.ManagedPolicy.fromManagedPolicyArn(
this,
'CloudWatchPolicy',
'arn:aws:iam::aws:policy/CloudWatchAgentServerPolicy'
)

const rlJcWebap = new iam.Role(this, "webap", {
roleName: "webap", // ロール名
description: 'webap', //説明
assumedBy: new iam.ServicePrincipal('ec2.amazonaws.com'), // サービス
path: '/', //パス(default:/)
managedPolicies: [SSMPolicy, CloudWatchPolicy], // マネージドポリシー
maxSessionDuration: cdk.Duration.hours(1), //ロールに設定する最大セッション期間(default:1時間)
// externalIds:, //ロールの引き渡しに関する外部IDの設定
// permissionsBoundary:, // 権限の境界設定
// inlinePolicies:, //インラインポリシー
})

const instanceProfileWebap = new iam.CfnInstanceProfile(this, 'instanceProfileWebap', {
roles: [rlJcWebap.roleName],
instanceProfileName: rlJcWebap.roleName,
})

const securityGroup = new ec2.SecurityGroup(this, 'MySecurityGroup', {
vpc: props.vpc,
description: 'Allow ssh access to ec2 instances',
securityGroupName: 'MySecurityGroupEC2'
});

const instance = new ec2.Instance(this, 'MyInstance', {
vpc: props.vpc,
instanceType: new ec2.InstanceType('t2.micro'), // インスタンスタイプ
machineImage: new ec2.GenericWindowsImage({
'ap-northeast-1': "ami-0f36f4f3d34a4df19",
}), // マシンイメージ
vpcSubnets: { subnetType: ec2.SubnetType.PUBLIC }, // パブリックサブネットにデプロイ
securityGroup: securityGroup,
instanceName:"test1",
requireImdsv2:true,
role: rlJcWebap
});
cdk.Tags.of(instance).add("test", "tag1") // タグ
cdk.Tags.of(instance).add("names", "tag500000") // タグ

const jcWebap1Profile = instance.node.defaultChild as ec2.CfnInstance
instance.node.tryRemoveChild('InstanceProfile')
jcWebap1Profile.addDependency(instanceProfileWebap)
jcWebap1Profile.addPropertyOverride('IamInstanceProfile', instanceProfileWebap.ref)

const instance_restore = new ec2.Instance(this, 'MyInstance_restore', {
vpc: props.vpc,
instanceType: new ec2.InstanceType('t2.micro'), // インスタンスタイプ
machineImage: new ec2.GenericWindowsImage({
'ap-northeast-1': "ami-005dc502f025ac443"
}), // マシンイメージ
vpcSubnets: { subnetType: ec2.SubnetType.PUBLIC }, // パブリックサブネットにデプロイ
securityGroup: securityGroup,
instanceName:"test1",
requireImdsv2:true,
role: rlJcWebap
});
cdk.Tags.of(instance_restore).add("test", "tag1") // タグ
cdk.Tags.of(instance_restore).add("names", "tag500000") // タグ

const jcWebapResotreProfile = instance_restore.node.defaultChild as ec2.CfnInstance
instance_restore.node.tryRemoveChild('InstanceProfile')
jcWebapResotreProfile.addDependency(instanceProfileWebap)
jcWebapResotreProfile.addPropertyOverride('IamInstanceProfile', instanceProfileWebap.ref)

const testtg1 = new elbv2.ApplicationTargetGroup(
this,
"test1-1",
{
targetGroupName: "tg1", // ターゲットグループ名
vpc: props.vpc, //VPC
protocol: elbv2.ApplicationProtocol.HTTP, // プロトコル
protocolVersion: elbv2.ApplicationProtocolVersion.HTTP1, // プロトコルのバージョン
port: 80, // ポート
healthCheck: {
enabled: true,
protocol: elbv2.Protocol.HTTP, // プロトコル
path: '/', // パス (default: /)
port: 'traffic-port', // ポート (default: traffic-port)
healthyThresholdCount: 5, //連続成功回数の閾値 (default:5)
unhealthyThresholdCount: 2, //連続ヘルスチェック失敗の回数(default: 2)
timeout: cdk.Duration.seconds(6), // タイムアウト時間
interval: cdk.Duration.seconds(30), // インターバル
healthyHttpCodes: '200,302', // HTTP成功時の応答コード
// healthyGrpcCodes:, // grpc成功時の応答コード
}, // ヘルスチェック
targetType: elbv2.TargetType.INSTANCE, // ターゲットのタイプ
targets: [new elasticloadbalancingv2targets.InstanceTarget(instance)], //ターゲット
deregistrationDelay: cdk.Duration.seconds(300), // ターゲットの解除後,実際に解除するまでの待機時間(default:300秒)
loadBalancingAlgorithmType: elbv2.TargetGroupLoadBalancingAlgorithmType.ROUND_ROBIN, // 負荷分散アルゴリズム(default: ROUND_ROBIN)
slowStart: cdk.Duration.seconds(30), // スロースタート設定(default: 30)
stickinessCookieDuration: cdk.Duration.days(1), //スティッキーセッションの有効期間 (default: 1日)
//stickinessCookieName:'', //スティッキーセッションのクッキー名
}
)
cdk.Tags.of(testtg1).add("Names", "test110") // タグ
cdk.Tags.of(testtg1).add("test", "tag1") // タグ

const cwalJcCpuutilizationJob2Error = new cloudwatch.Alarm(
this,
`cpuutilization`,
{
alarmName: `cpuutilization`, // アラーム名
alarmDescription: `cpuutilization`, // 説明
metric: new cloudwatch.Metric({
namespace: 'AWS/EC2',
metricName: 'CPUUtilization',
dimensionsMap: {
InstanceId: instance.instanceId,
},
statistic: 'Average', // 例: Average, Sum, Min, Max など
period: cdk.Duration.minutes(5), // 監視する期間
}),
comparisonOperator: cloudwatch.ComparisonOperator.GREATER_THAN_OR_EQUAL_TO_THRESHOLD, //比較演算子 (default: GreaterThanOrEqualToThreshold)
threshold: 90, // 閾値
evaluationPeriods: 2, // : アラームが異常と判断するまでの連続する期間の数です
datapointsToAlarm: 2, // トリガーとなるデータポイントの数
treatMissingData: cloudwatch.TreatMissingData.IGNORE, // 欠落データの処理方法 (default: TreatMissingData.Missing)
actionsEnabled: false, // アクションの有効化 (default: true)
// evaluateLowSampleCountPercentile:, // データポイントが不足しているときの評価方法。パーセンタイルの時のみ
}
)

this. testtg1 = testtg1

}
}
```

### Possible Solution

_No response_

### Additional Information/Context

_No response_

### CDK CLI Version

2.126.0

### Framework Version

_No response_

### Node.js Version

18.18.2

### OS

WIndows

### Language

TypeScript

### Language Version

TypeScript 5.5.3

### Other information

_No response_

Contributor guide

Open the contributing guide

Research direction

Run the cdk import command against the TypeScript reproduction and inspect the generated template's Mappings section, focusing on the MyInstance_restore EC2 definition and the missing MyInstancerestoreAmiMapA3AA9468 mapping. Done means the EC2 import completes without the reported ValidationError.

Written by the indexing model from the issue text.

Assessment

Tech stack
aws, typescript
Domain
cloud, infrastructure
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
42/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.