> ## 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.

# Ec2 older than x days remediation

### Triage and Remediation

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

    <AccordionGroup>
      <Accordion title="Using Console" defaultOpen="true">
        To remediate the issue of long running instances in AWS using the AWS console, you can follow the below steps:

        1. Log in to your AWS Management Console.

        2. Go to the EC2 dashboard.

        3. Under the Instances section, select the instance that has been running for a long time.

        4. Stop the instance by right-clicking on it and selecting "Instance State" > "Stop".

        5. Once the instance is stopped, right-click on it again and select "Instance Settings" > "Change Shutdown Behavior".

        6. From the drop-down menu, select "Terminate".

        7. Click "Apply" and then "Save".

        8. Start a new instance with the same configuration as the terminated instance.

        9. Once the new instance is running, ensure that all the data and configurations from the old instance are properly transferred to the new instance.

        10. Finally, terminate the old instance to avoid any unnecessary charges.

        By following these steps, you can remediate the issue of long running instances in AWS and ensure that your cloud infrastructure is optimized for performance and cost.

        #
      </Accordion>

      <Accordion title="Using CLI">
        To remediate the misconfiguration of long-running instances in AWS using AWS CLI, follow the steps below:

        1. Open the AWS CLI on your local machine or EC2 instance.

        2. List all the instances that are currently running using the following command:

           ```
           aws ec2 describe-instances --query 'Reservations[*].Instances[*].[InstanceId,InstanceType,State.Name,LaunchTime]' --output text
           ```

           This command will list all the instances that are currently running in your AWS account.

        3. Identify the instances that have been running for a long time and need to be relaunched.

        4. Stop the identified instances using the following command:

           ```
           aws ec2 stop-instances --instance-ids instance_id
           ```

           Replace `instance_id` with the ID of the instance that needs to be stopped. This command will stop the instance.

        5. Once the instance is stopped, launch a new instance using the same configuration as the stopped instance.

           ```
           aws ec2 run-instances --image-id ami-xxxxxxxx --count 1 --instance-type t2.micro --key-name MyKeyPair --security-group-ids sg-xxxxxxxx --subnet-id subnet-xxxxxxxx
           ```

           Replace the `image-id`, `instance-type`, `key-name`, `security-group-ids`, and `subnet-id` with the same configuration as the stopped instance. This command will launch a new instance.

        6. Once the new instance is launched, terminate the old instance using the following command:

           ```
           aws ec2 terminate-instances --instance-ids instance_id
           ```

           Replace `instance_id` with the ID of the stopped instance. This command will terminate the old instance.

        7. Verify that the new instance is running and functioning properly.

        By following these steps, you can remediate the misconfiguration of long-running instances in AWS using AWS CLI.
      </Accordion>

      <Accordion title="Using Python">
        To remediate the misconfiguration of long running instances in AWS using Python, you can follow these steps:

        1. Import the necessary AWS SDK modules in Python. For example, you can use the `boto3` module.

        ```
        import boto3
        ```

        2. Create a session with AWS using the `boto3.Session()` method.

        ```
        session = boto3.Session(
            aws_access_key_id='ACCESS_KEY',
            aws_secret_access_key='SECRET_KEY',
            region_name='REGION'
        )
        ```

        3. Use the `boto3.client()` method to connect to the EC2 service.

        ```
        ec2 = session.client('ec2')
        ```

        4. Use the `describe_instances()` method to get a list of all running instances.

        ```
        instances = ec2.describe_instances(
            Filters=[
                {
                    'Name': 'instance-state-name',
                    'Values': ['running']
                }
            ]
        )
        ```

        5. Loop through the list of instances and use the `terminate_instances()` method to terminate them.

        ```
        for instance in instances['Reservations'][0]['Instances']:
            instance_id = instance['InstanceId']
            ec2.terminate_instances(
                InstanceIds=[
                    instance_id
                ]
            )
        ```

        6. Alternatively, you can use the `stop_instances()` method to stop the instances instead of terminating them.

        ```
        for instance in instances['Reservations'][0]['Instances']:
            instance_id = instance['InstanceId']
            ec2.stop_instances(
                InstanceIds=[
                    instance_id
                ]
            )
        ```

        7. You can also add additional filters to the `describe_instances()` method to target specific instances based on tags or other attributes.

        ```
        instances = ec2.describe_instances(
            Filters=[
                {
                    'Name': 'tag:Environment',
                    'Values': ['Production']
                },
                {
                    'Name': 'instance-state-name',
                    'Values': ['running']
                }
            ]
        )
        ```

        8. Finally, you can schedule this Python script to run periodically using a task scheduler or cron job to ensure that long running instances are always re-launched.
      </Accordion>

      <Accordion title="Using Terraform">
        Terraform cannot enforce “relaunch after 180 days” for an EC2 instance, because that is an operational/lifecycle action, not a static configuration exposed in the `aws_instance` resource.

        Use Terraform to define the instance, and then use an external mechanism (for example, AWS Instance Scheduler, EventBridge + Lambda, or a CI job calling `aws ec2 stop-instances` / `terminate-instances` and recreating via `terraform apply`) to enforce the 180‑day relaunch policy.

        Console-equivalent steps (one-time, manual remediation for an existing long-running instance):

        1. In the EC2 console, note the instance configuration (AMI, instance type, security groups, IAM role, user data, tags).
        2. Stop or terminate the long-running instance.
        3. Launch a new instance with the same configuration (or re-`terraform apply` the same `aws_instance` definition so Terraform creates a fresh instance).

        There is no Terraform argument on `aws_instance` (or a related AWS resource) that can automatically detect instance age and restart/recreate it after 180 days, so this control must be implemented outside Terraform.
      </Accordion>
    </AccordionGroup>
  </Tab>
</Tabs>
