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

# Ssm managed instances remediation

### Triage and Remediation

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

    <AccordionGroup>
      <Accordion title="Using Console" defaultOpen="true">
        To remediate the misconfiguration "EC2 Instances Should Be Managed By SSM" in AWS using the AWS console, follow the below steps:

        1. Open the AWS Management Console and navigate to the EC2 dashboard.
        2. Select the EC2 instance that needs to be managed by SSM.
        3. Click on the "Actions" button and select "Instance Settings" and then click on "Attach/Replace IAM Role".
        4. In the "Attach/Replace IAM Role" window, select the option "SSMManagedInstanceCore" in the "IAM Role" drop-down menu.
        5. Click on "Apply" to attach the IAM role to the EC2 instance.
        6. Once the IAM role is attached, navigate to the SSM dashboard.
        7. Select "Managed Instances" from the left-hand menu.
        8. Verify that the EC2 instance is listed as a managed instance. If it is not listed, select "Register instances" to add the EC2 instance to SSM.
        9. After registering the instance, select the instance and click on "Actions" and then select "Run Command".
        10. In the "Run a Command" window, select the "AWS-ConfigureAWSPackage" document.
        11. In the "Command Parameters" section, select the "Install" option for the "action" parameter.
        12. Click on "Run" to install the SSM agent on the EC2 instance.
        13. Once the SSM agent is installed, the EC2 instance will be managed by SSM.

        By following the above steps, the misconfiguration "EC2 Instances Should Be Managed By SSM" can be remediated for AWS using the AWS console.

        #
      </Accordion>

      <Accordion title="Using CLI">
        To remediate the misconfiguration "EC2 Instances Should Be Managed By SSM" in AWS using AWS CLI, follow the below steps:

        Step 1: Install and configure AWS CLI on your local machine.

        Step 2: Run the following command to identify the EC2 instances that are not managed by SSM:

        ```
        aws ec2 describe-instances --filters "Name=instance-state-name,Values=running" --query 'Reservations[*].Instances[*].[InstanceId,Tags[?Key==`Name`].Value|[0], [not contains(Tags[?Key==`aws: ssm: managed`, Value==`true`)], InstanceId]]' --output text
        ```

        Step 3: The above command will output a list of all EC2 instances that are not managed by SSM. Identify the instances that need to be remediated.

        Step 4: Run the following command to enable SSM management for the identified EC2 instances:

        ```
        aws ssm send-command --document-name "AWS-ConfigureAWSPackage" --document-version "1" --targets "Key=InstanceIds,Values=<Instance-ID>" --parameters '{"action":["Install"],"installationType":["Uninstall and reinstall"],"name":["AmazonCloudWatchAgent"],"version":["latest"]}' --timeout-seconds 600 --max-concurrency "50" --max-errors "0" --output-s3-bucket-name "<S3-Bucket-Name>" --output-s3-key-prefix "output" --region "<Region>"
        ```

        Note: Replace `<Instance-ID>`, `<S3-Bucket-Name>`, and `<Region>` with the appropriate values.

        Step 5: Repeat Step 4 for all the identified EC2 instances.

        Step 6: Verify that SSM management is enabled for the EC2 instances by running the following command:

        ```
        aws ec2 describe-instances --filters "Name=instance-state-name,Values=running" --query 'Reservations[*].Instances[*].[InstanceId,Tags[?Key==`Name`].Value|[0], [not contains(Tags[?Key==`aws: ssm: managed`, Value==`true`)], InstanceId]]' --output text
        ```

        The above command should not return any output, indicating that all EC2 instances are now managed by SSM.
      </Accordion>

      <Accordion title="Using Python">
        To remediate the misconfiguration "EC2 Instances Should Be Managed By SSM" in AWS using Python, you can follow these steps:

        1. Install the AWS SDK for Python (Boto3) using pip: `pip install boto3`

        2. Create an AWS SSM client object using the following code:

        ```python theme={null}
        import boto3

        ssm_client = boto3.client('ssm')
        ```

        3. Retrieve a list of all EC2 instances in the AWS account using the following code:

        ```python theme={null}
        import boto3

        ec2_client = boto3.client('ec2')

        response = ec2_client.describe_instances()
        instances = []

        for reservation in response['Reservations']:
            for instance in reservation['Instances']:
                instances.append(instance['InstanceId'])
        ```

        4. For each EC2 instance, check if it is already managed by SSM using the following code:

        ```python theme={null}
        import boto3

        ssm_client = boto3.client('ssm')

        response = ssm_client.describe_instance_information(
            InstanceInformationFilterList=[
                {
                    'key': 'InstanceIds',
                    'valueSet': [
                        'INSTANCE_ID'
                    ]
                },
            ]
        )

        if len(response['InstanceInformationList']) > 0:
            print('Instance is already managed by SSM')
        else:
            print('Instance is not managed by SSM')
        ```

        Replace `INSTANCE_ID` with the ID of the EC2 instance you want to check.

        5. If the EC2 instance is not already managed by SSM, you can remediate the misconfiguration by running the following command:

        ```python theme={null}
        import boto3

        ssm_client = boto3.client('ssm')

        response = ssm_client.send_command(
            InstanceIds=[
                'INSTANCE_ID',
            ],
            DocumentName='AWS-ConfigureAWSPackage',
            Parameters={
                'action': ['Install'],
                'name': ['AmazonCloudWatchAgent'],
            }
        )

        command_id = response['Command']['CommandId']
        ```

        Replace `INSTANCE_ID` with the ID of the EC2 instance you want to remediate.

        This command will install the Amazon CloudWatch agent on the EC2 instance and configure it to be managed by SSM. You can monitor the progress of the command using the `command_id` returned by the `send_command` method.
      </Accordion>

      <Accordion title="Using Terraform">
        ```hcl theme={null}
        # IAM role that EC2 instances can assume for SSM
        resource "aws_iam_role" "ssm_managed_instance_role" {
          name = "SSMManagedInstanceRole"

          assume_role_policy = jsonencode({
            Version = "2012-10-17"
            Statement = [
              {
                Effect = "Allow"
                Principal = {
                  Service = "ec2.amazonaws.com"
                }
                Action = "sts:AssumeRole"
              }
            ]
          })
        }

        # Attach the AWS-managed SSM core policy to the role
        resource "aws_iam_role_policy_attachment" "ssm_managed_instance_core" {
          role       = aws_iam_role.ssm_managed_instance_role.name
          policy_arn = "arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore"
        }

        # Instance profile that holds the SSM role
        resource "aws_iam_instance_profile" "ssm_instance_profile" {
          name = "SSMManagedInstanceProfile"
          role = aws_iam_role.ssm_managed_instance_role.name
        }

        # EC2 instance configured to use the SSM instance profile
        resource "aws_instance" "TARGET_INSTANCE" {
          ami           = "AMI_ID_TO_USE"          # replace with a valid AMI ID
          instance_type = "INSTANCE_TYPE"          # e.g., "t3.micro"

          # This attaches the SSM instance profile to the instance,
          # equivalent to aws ec2 associate-iam-instance-profile ...
          iam_instance_profile = aws_iam_instance_profile.ssm_instance_profile.name

          subnet_id              = "SUBNET_ID"     # replace with your subnet ID
          vpc_security_group_ids = ["SECURITY_GROUP_ID"] # replace with your SG ID(s)

          # ...other arguments you already use for this instance...
        }
        ```

        Changing `iam_instance_profile` on an existing `aws_instance` forces replacement of that instance, which can cause downtime and will remove any previously attached instance profile and its permissions.

        After you wire this into your existing configuration, `terraform plan` should show:

        * creation of `aws_iam_role.ssm_managed_instance_role`
        * creation of `aws_iam_role_policy_attachment.ssm_managed_instance_core`
        * creation of `aws_iam_instance_profile.ssm_instance_profile`
        * for any existing instance you modify, a `-/+` (destroy and create replacement) on `aws_instance.TARGET_INSTANCE` with `iam_instance_profile` changing from `null` (or the old profile) to `SSMManagedInstanceProfile`.
      </Accordion>
    </AccordionGroup>
  </Tab>
</Tabs>
