From 1aabd3fd955cc86763b32c0e752bfb57d334e40c Mon Sep 17 00:00:00 2001 From: rafcio19 Date: Sat, 29 Oct 2022 23:06:21 +0100 Subject: [PATCH] EC2: link IAM instance profile with instance (#5617) --- moto/ec2/models/iam_instance_profile.py | 5 ++++ moto/ec2/models/instances.py | 1 + moto/ec2/responses/instances.py | 26 +++++++++++++++++ tests/test_ec2/test_instances.py | 39 ++++++++++++++++++++++++- 4 files changed, 70 insertions(+), 1 deletion(-) diff --git a/moto/ec2/models/iam_instance_profile.py b/moto/ec2/models/iam_instance_profile.py index 2f8ea69fb..629ae46b9 100644 --- a/moto/ec2/models/iam_instance_profile.py +++ b/moto/ec2/models/iam_instance_profile.py @@ -17,6 +17,11 @@ class IamInstanceProfileAssociation(CloudFormationModel): self.instance = instance self.iam_instance_profile = iam_instance_profile self.state = "associated" + ec2_backend.modify_instance_attribute( + instance.id, + "iam_instance_profile", + {"Arn": self.iam_instance_profile.arn, "Id": association_id}, + ) class IamInstanceProfileAssociationBackend: diff --git a/moto/ec2/models/instances.py b/moto/ec2/models/instances.py index d6afd75a5..61b4d5b35 100644 --- a/moto/ec2/models/instances.py +++ b/moto/ec2/models/instances.py @@ -140,6 +140,7 @@ class Instance(TaggedEC2Resource, BotoInstance, CloudFormationModel): self.architecture = ami.architecture if ami else "x86_64" self.root_device_name = ami.root_device_name if ami else None self.disable_api_stop = False + self.iam_instance_profile = kwargs.get("iam_instance_profile") # handle weird bug around user_data -- something grabs the repr(), so # it must be clean diff --git a/moto/ec2/responses/instances.py b/moto/ec2/responses/instances.py index 2d7ef980b..e0cb86eac 100644 --- a/moto/ec2/responses/instances.py +++ b/moto/ec2/responses/instances.py @@ -73,6 +73,10 @@ class InstanceResponse(EC2BaseResponse): ), "launch_template": self._get_multi_param_dict("LaunchTemplate"), "hibernation_options": self._get_multi_param_dict("HibernationOptions"), + "iam_instance_profile_name": self._get_param("IamInstanceProfile.Name") + or None, + "iam_instance_profile_arn": self._get_param("IamInstanceProfile.Arn") + or None, } if len(kwargs["nics"]) and kwargs["subnet_id"]: raise InvalidParameterCombination( @@ -87,6 +91,16 @@ class InstanceResponse(EC2BaseResponse): new_reservation = self.ec2_backend.add_instances( image_id, min_count, user_data, security_group_names, **kwargs ) + if kwargs.get("iam_instance_profile_name"): + self.ec2_backend.associate_iam_instance_profile( + instance_id=new_reservation.instances[0].id, + iam_instance_profile_name=kwargs.get("iam_instance_profile_name"), + ) + if kwargs.get("iam_instance_profile_arn"): + self.ec2_backend.associate_iam_instance_profile( + instance_id=new_reservation.instances[0].id, + iam_instance_profile_arn=kwargs.get("iam_instance_profile_arn"), + ) template = self.response_template(EC2_RUN_INSTANCES) return template.render( @@ -422,6 +436,12 @@ EC2_RUN_INSTANCES = """