> ## Documentation Index
> Fetch the complete documentation index at: https://cloudanix.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Instance in auto scaling group remediation

### Triage and Remediation

<Tabs>
  <Tab title="Remediation">
    ### Remediation

    <AccordionGroup>
      <Accordion title="Using Console" defaultOpen="true">
        To remediate the misconfiguration "Instance Should Be Launched In Auto Scaling Group" for AWS using AWS console, follow the below steps:

        1. Open the AWS Management Console and navigate to the EC2 dashboard.
        2. Select the instance that needs to be launched in an Auto Scaling Group.
        3. Stop the instance by selecting the instance and clicking on the "Instance State" button, then click on "Stop".
        4. Create a new Auto Scaling Group by selecting "Auto Scaling Groups" from the left-hand menu and clicking on the "Create Auto Scaling Group" button.
        5. Follow the prompts to create the new Auto Scaling Group, making sure to select the appropriate instance type and other settings.
        6. Once the Auto Scaling Group has been created, add the stopped instance to the group by selecting the instance and clicking on the "Actions" button, then selecting "Instance Settings" and "Move instance to another Auto Scaling group".
        7. Select the new Auto Scaling Group from the list and click "Move instance".
        8. Start the instance by selecting the instance and clicking on the "Instance State" button, then clicking on "Start".

        After completing these steps, the instance will be launched in an Auto Scaling Group, which will help ensure that it is always running and available to handle traffic.

        #
      </Accordion>

      <Accordion title="Using CLI">
        To remediate the misconfiguration "Instance Should Be Launched In Auto Scaling Group" for AWS using AWS CLI, follow the below steps:

        Step 1: Create an Auto Scaling Group (ASG) using the following command:

        ```
        aws autoscaling create-auto-scaling-group --auto-scaling-group-name <ASG_NAME> --launch-configuration-name <LAUNCH_CONFIG_NAME> --min-size <MIN_SIZE> --max-size <MAX_SIZE> --desired-capacity <DESIRED_CAPACITY> --availability-zones <AVAILABILITY_ZONES>
        ```

        In the above command, replace the placeholders with the appropriate values:

        * `<ASG_NAME>`: Name of the Auto Scaling Group you want to create.
        * `<LAUNCH_CONFIG_NAME>`: Name of the Launch Configuration you want to use for the Auto Scaling Group.
        * `<MIN_SIZE>`: Minimum number of instances you want to launch in the Auto Scaling Group.
        * `<MAX_SIZE>`: Maximum number of instances you want to launch in the Auto Scaling Group.
        * `<DESIRED_CAPACITY>`: Desired number of instances you want to launch in the Auto Scaling Group.
        * `<AVAILABILITY_ZONES>`: Comma-separated list of availability zones in which you want to launch the instances.

        Step 2: Update the instance to be launched in the Auto Scaling Group using the following command:

        ```
        aws ec2 modify-instance-attribute --instance-id <INSTANCE_ID> --no-disable-api-termination --instance-lifecycle "spot"
        ```

        In the above command, replace the placeholders with the appropriate values:

        * `<INSTANCE_ID>`: ID of the instance you want to update.

        Step 3: Detach the EBS volume from the instance using the following command:

        ```
        aws ec2 modify-instance-attribute --instance-id <INSTANCE_ID> --block-device-mappings "[{\"DeviceName\": \"/dev/sda1\",\"Ebs\":{\"DeleteOnTermination\":true}}]"
        ```

        In the above command, replace the placeholder with the appropriate value:

        * `<INSTANCE_ID>`: ID of the instance you want to detach the EBS volume from.

        Step 4: Terminate the instance using the following command:

        ```
        aws ec2 terminate-instances --instance-ids <INSTANCE_ID>
        ```

        In the above command, replace the placeholder with the appropriate value:

        * `<INSTANCE_ID>`: ID of the instance you want to terminate.

        By following the above steps, you can remediate the misconfiguration "Instance Should Be Launched In Auto Scaling Group" for AWS using AWS CLI.
      </Accordion>

      <Accordion title="Using Python">
        To remediate the misconfiguration "Instance Should Be Launched In Auto Scaling Group" in AWS using Python, follow these steps:

        1. Import the necessary AWS SDK libraries:

        ```python theme={null}
        import boto3
        ```

        2. Connect to the AWS account using the `boto3` client:

        ```python theme={null}
        client = boto3.client('autoscaling')
        ```

        3. Get the instance ID of the instance that is not launched in an Auto Scaling Group:

        ```python theme={null}
        instance_id = 'INSTANCE_ID'
        ```

        4. Get the name of the Auto Scaling Group that the instance should be launched in:

        ```python theme={null}
        asg_name = 'AUTO_SCALING_GROUP_NAME'
        ```

        5. Create a new Auto Scaling Group with the desired configuration:

        ```python theme={null}
        response = client.create_auto_scaling_group(
            AutoScalingGroupName=asg_name,
            LaunchConfigurationName='LAUNCH_CONFIGURATION_NAME',
            MinSize=1,
            MaxSize=1,
            DesiredCapacity=1,
            AvailabilityZones=[
                'AVAILABILITY_ZONE',
            ],
            Tags=[
                {
                    'Key': 'KEY_NAME',
                    'Value': 'VALUE_NAME',
                    'PropagateAtLaunch': True
                },
            ]
        )
        ```

        6. Attach the instance to the newly created Auto Scaling Group:

        ```python theme={null}
        response = client.attach_instances(
            InstanceIds=[
                instance_id,
            ],
            AutoScalingGroupName=asg_name
        )
        ```

        7. Wait for the instance to be registered with the Auto Scaling Group:

        ```python theme={null}
        waiter = client.get_waiter('instance_in_service')
        waiter.wait(
            AutoScalingGroupName=asg_name,
            InstanceIds=[
                instance_id,
            ]
        )
        ```

        8. Detach the instance from the old launch configuration:

        ```python theme={null}
        response = client.detach_instances(
            InstanceIds=[
                instance_id,
            ],
            AutoScalingGroupName='OLD_AUTO_SCALING_GROUP_NAME',
            ShouldDecrementDesiredCapacity=True
        )
        ```

        9. Delete the old launch configuration:

        ```python theme={null}
        response = client.delete_launch_configuration(
            LaunchConfigurationName='OLD_LAUNCH_CONFIGURATION_NAME'
        )
        ```

        10. Verify that the instance is now launched in the new Auto Scaling Group.

        Note: This is just an example of how to remediate this misconfiguration using Python. The specific steps may vary depending on the exact details of the misconfiguration.
      </Accordion>

      <Accordion title="Using Terraform">
        ```hcl theme={null}
        # There is no Terraform resource or argument that can “attach” an already
        # running aws_instance to an existing Auto Scaling Group; that operation
        # (autoscaling attach-instances) is only available via CLI/Console.

        # The Terraform way to satisfy this control is to manage the instance
        # *through* an Auto Scaling Group instead of as a standalone aws_instance.

        resource "aws_launch_template" "EC2_LAUNCH_TEMPLATE" {
          name_prefix   = "REPLACE_WITH_LT_PREFIX-"
          image_id      = "AMI_ID"              # REPLACE_WITH_AMI_ID
          instance_type = "t3.micro"            # REPLACE_WITH_INSTANCE_TYPE

          network_interfaces {
            subnet_id       = "SUBNET_ID"       # REPLACE_WITH_SUBNET_ID
            security_groups = ["SG_ID"]         # REPLACE_WITH_SECURITY_GROUP_ID
          }

          # add any other settings your existing instance uses (key_name, user_data, etc.)
        }

        resource "aws_autoscaling_group" "EC2_ASG" {
          name                      = "REPLACE_WITH_ASG_NAME"       # existing or new ASG name
          max_size                  = 1
          min_size                  = 1
          desired_capacity          = 1
          vpc_zone_identifier       = ["SUBNET_ID"]                 # REPLACE_WITH_SUBNET_ID
          health_check_type         = "EC2"
          health_check_grace_period = 300

          launch_template {
            id      = aws_launch_template.EC2_LAUNCH_TEMPLATE.id
            version = "$Latest"
          }

          # if you must use a specific AZ: availability_zones = ["REPLACE_WITH_AZ"]
        }

        # IMPORTANT:
        # - Moving an existing, manually-created instance into Terraform and into an ASG
        #   generally forces replacement: the ASG will launch *new* instances from the
        #   launch template instead of attaching the old one.
        # - Plan for downtime or cutover when you switch traffic (e.g., via load balancer)
        #   from the old instance to the ASG-managed instances.
        ```

        Terraform cannot perform the exact `aws autoscaling attach-instances` action; to attach a specific running instance to an existing ASG you must use the AWS CLI/Console as in the verified remediation. After updating Terraform to manage the workload via an Auto Scaling Group, `terraform plan` should show creation of `aws_launch_template.EC2_LAUNCH_TEMPLATE` and `aws_autoscaling_group.EC2_ASG`, and (if you also import/delete the old instance) destruction of the standalone `aws_instance`.
      </Accordion>
    </AccordionGroup>
  </Tab>
</Tabs>
