From cfc793014f18dfbf708ce9a9c8241e09e38eaeb1 Mon Sep 17 00:00:00 2001 From: mello7tre Date: Wed, 1 Sep 2021 19:50:53 +0200 Subject: [PATCH] Fix/asg attach instances (#4258) --- moto/autoscaling/models.py | 4 +++ tests/test_autoscaling/test_autoscaling.py | 41 ++++++++++++++++++++++ 2 files changed, 45 insertions(+) diff --git a/moto/autoscaling/models.py b/moto/autoscaling/models.py index 1fd09d928..213f1d641 100644 --- a/moto/autoscaling/models.py +++ b/moto/autoscaling/models.py @@ -35,11 +35,14 @@ class InstanceState(object): lifecycle_state="InService", health_status="Healthy", protected_from_scale_in=False, + autoscaling_group=None, ): self.instance = instance self.lifecycle_state = lifecycle_state self.health_status = health_status self.protected_from_scale_in = protected_from_scale_in + if not hasattr(self.instance, "autoscaling_group"): + self.instance.autoscaling_group = autoscaling_group class FakeScalingPolicy(BaseModel): @@ -821,6 +824,7 @@ class AutoScalingBackend(BaseBackend): InstanceState( self.ec2_backend.get_instance(x), protected_from_scale_in=group.new_instances_protected_from_scale_in, + autoscaling_group=group, ) for x in instance_ids ] diff --git a/tests/test_autoscaling/test_autoscaling.py b/tests/test_autoscaling/test_autoscaling.py index 77bbec09a..078e484ce 100644 --- a/tests/test_autoscaling/test_autoscaling.py +++ b/tests/test_autoscaling/test_autoscaling.py @@ -2832,3 +2832,44 @@ def test_delete_tags_by_key(): tags = group["Tags"] tags.should.contain(tag_to_keep) tags.should_not.contain(tag_to_delete) + + +@mock_ec2 +@mock_autoscaling +def test_attach_instances(): + asg_client = boto3.client("autoscaling", region_name="us-east-1") + ec2_client = boto3.client("ec2", region_name="us-east-1") + + kwargs = { + "KeyName": "foobar", + "ImageId": "ami-pytest", + "MinCount": 1, + "MaxCount": 1, + "InstanceType": "c4.2xlarge", + "TagSpecifications": [ + {"ResourceType": "instance", "Tags": [{"Key": "key", "Value": "val"}]}, + ], + } + fake_instance = ec2_client.run_instances(**kwargs)["Instances"][0] + fake_lc = asg_client.create_launch_configuration( + LaunchConfigurationName="test_launch_configuration", + ImageId="ami-pytest", + InstanceType="t3.micro", + KeyName="foobar", + ) + fake_asg = asg_client.create_auto_scaling_group( + AutoScalingGroupName="test_asg", + LaunchConfigurationName="test_launch_configuration", + MinSize=0, + MaxSize=1, + AvailabilityZones=[fake_instance["Placement"]["AvailabilityZone"]], + ) + asg_client.attach_instances( + InstanceIds=[fake_instance["InstanceId"],], AutoScalingGroupName="test_asg" + ) + response = asg_client.describe_auto_scaling_instances() + len(response["AutoScalingInstances"]).should.equal(1) + for instance in response["AutoScalingInstances"]: + instance["LaunchConfigurationName"].should.equal("test_launch_configuration") + instance["AutoScalingGroupName"].should.equal("test_asg") + instance["InstanceType"].should.equal("c4.2xlarge")