CFN/EC2: fix KeyError for EC2:Instance PublicIpAddress #12176
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Motivation
We got a report from a support case that trying to deploy an EC2 instance with CDK and a basic stack would fail with a
KeyError
:The Stack:
(Note: To run on AWS, I had to update the stack to use
machine_image=ec2.MachineImage.latest_amazon_linux2(),
to find the proper AMI, and also create a key pair).This is due because the
PublicIpAddress
response field is optional, and is not given to be returned depending on the configuration of the instance (and if the VPC of the instance is the default one or not, see https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-instance-addressing.html#concepts-public-addresses).This stack did not failed for me, possibly due to the different platform (macOS).
I do not know how to add a test for this, because spawning real instance is pretty difficult as it is very platform dependent, and the fact that we do not return the
PublicIpAddress
seems to also be dependent on the platform.I've done a lot of testing on AWS, and with this stack, the instance does not have a Public Address, but it deploys correctly. However, trying to add the following to the stack and deploying again, or deploying from scratch:
See https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ec2.Instance.html#instancepublicip
Will fail in AWS with the following message:
Attribute 'PublicIp' does not exist
, meaning that the field is actually not attached to the "model", and thus failing.I believe we can get close to this behavior by conditionally adding the field to the model.
If you have an idea about the testing, please feel free to suggest it.
Changes
PublicIpAddress
andPublicDnsName
to the CFNmodel
if those are present