> ## 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 iam roles remediation

### Triage and Remediation

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

    <AccordionGroup>
      <Accordion title="Using Console" defaultOpen="true">
        To remediate the misconfiguration "EC2 IAM Roles Should Be Used" for AWS using the AWS console, please follow the below steps:

        1. Login to your AWS Management Console.
        2. Navigate to the EC2 dashboard.
        3. Select the EC2 instance for which you want to remediate the misconfiguration.
        4. Click on the "Actions" dropdown menu and select "Instance Settings" and then click on "Attach/Replace IAM Role".
        5. In the "Attach/Replace IAM Role" window, select the IAM role that you want to attach to the EC2 instance.
        6. Click on the "Apply" button to attach the selected IAM role to the EC2 instance.

        By following the above steps, you have successfully remediated the misconfiguration "EC2 IAM Roles Should Be Used" for AWS. Now the EC2 instance is associated with an IAM role, which provides temporary security credentials to applications that run on the instance. This helps to improve the security of your AWS infrastructure by reducing the risk of unauthorized access to resources.

        #
      </Accordion>

      <Accordion title="Using CLI">
        To remediate the issue of not using EC2 IAM roles in AWS using AWS CLI, follow the below steps:

        1. Create an IAM role with the required permissions that the EC2 instance needs. You can create this role using the AWS CLI command "aws iam create-role".

        2. Attach the required policies to the IAM role. You can attach policies using the AWS CLI command "aws iam attach-role-policy".

        3. Launch an EC2 instance and specify the IAM role created in step 1. You can do this using the AWS CLI command "aws ec2 run-instances" with the parameter "--iam-instance-profile".

        4. Verify that the IAM role is being used by the EC2 instance by logging into the instance and running the command "curl [http://169.254.169.254/latest/meta-data/iam/info](http://169.254.169.254/latest/meta-data/iam/info)". This command should return the IAM role ARN.

        5. Once verified, you can remove any access keys that were previously used by the EC2 instance. You can do this using the AWS CLI command "aws ec2 delete-key-pair".

        By following these steps, you can remediate the issue of not using EC2 IAM roles in AWS using AWS CLI.
      </Accordion>

      <Accordion title="Using Python">
        To remediate the misconfiguration of not using EC2 IAM roles in AWS, we can use the following steps using Python:

        1. First, we need to create an IAM role that has the necessary permissions for our EC2 instances. We can do this using the boto3 library in Python. Here's an example:

        ```
        import boto3

        iam = boto3.client('iam')

        response = iam.create_role(
            RoleName='EC2-Role',
            AssumeRolePolicyDocument={
                'Version': '2012-10-17',
                'Statement': [
                    {
                        'Effect': 'Allow',
                        'Principal': {
                            'Service': 'ec2.amazonaws.com'
                        },
                        'Action': 'sts:AssumeRole'
                    }
                ]
            }
        )

        # Attach necessary policies to the role
        iam.attach_role_policy(
            RoleName='EC2-Role',
            PolicyArn='arn:aws:iam::aws:policy/AmazonS3FullAccess'
        )
        ```

        2. Once the IAM role is created, we can assign it to our EC2 instances. We can do this by launching new instances with the `--iam-instance-profile` parameter or by modifying existing instances with the `modify_instance_attribute` method in the `boto3` library.

        ```
        import boto3

        ec2 = boto3.client('ec2')

        # Launch new instances with IAM role
        response = ec2.run_instances(
            ImageId='ami-0c55b159cbfafe1f0',
            InstanceType='t2.micro',
            MinCount=1,
            MaxCount=1,
            IamInstanceProfile={
                'Arn': 'arn:aws:iam::123456789012:instance-profile/EC2-Role'
            }
        )

        # Modify existing instances with IAM role
        response = ec2.modify_instance_attribute(
            InstanceId='i-0123456789abcdef0',
            IamInstanceProfile={
                'Arn': 'arn:aws:iam::123456789012:instance-profile/EC2-Role'
            }
        )
        ```

        By following these steps, we can remediate the misconfiguration of not using EC2 IAM roles in AWS using Python.
      </Accordion>

      <Accordion title="Using Terraform">
        ```hcl theme={null}
        # IAM role to be assumed by EC2
        resource "aws_iam_role" "ec2_role" {
          name = "EC2_ROLE_NAME" # replace with a suitable role name

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

        # Attach least-privilege permissions to the role
        resource "aws_iam_role_policy_attachment" "ec2_role_policy" {
          role       = aws_iam_role.ec2_role.name
          policy_arn = "arn:aws:iam::aws:policy/POLICY_NAME" # replace with an appropriate managed policy ARN
        }

        # Instance profile as a container for the IAM role
        resource "aws_iam_instance_profile" "ec2_profile" {
          name = "EC2_INSTANCE_PROFILE_NAME" # replace with desired instance profile name
          role = aws_iam_role.ec2_role.name
        }

        # Existing EC2 instance (already created elsewhere)
        # Replace INSTANCE_ID with the actual instance ID if you hard-code it,
        # or reference an existing aws_instance resource.
        resource "aws_iam_instance_profile_association" "ec2_profile_assoc" {
          instance_id         = "EC2_INSTANCE_ID"                    # replace with the existing instance ID, or aws_instance.MY_INSTANCE.id
          iam_instance_profile = aws_iam_instance_profile.ec2_profile.name
        }
        ```

        Substitute:

        * `EC2_ROLE_NAME` with the IAM role name you want.
        * `POLICY_NAME` with an AWS managed policy or use your own custom policy ARN following least privilege.
        * `EC2_INSTANCE_PROFILE_NAME` with the instance profile name you want.
        * `EC2_INSTANCE_ID` with the target EC2 instance ID, or reference an `aws_instance` resource.

        This mirrors `aws ec2 associate-iam-instance-profile` and does not recreate the instance or require a reboot.

        To verify, `terraform plan` should show:

        * `+` creation of `aws_iam_role`, `aws_iam_role_policy_attachment`, `aws_iam_instance_profile`, and `aws_iam_instance_profile_association`.
        * No `-/+` (replace) on the existing `aws_instance` resource.
      </Accordion>
    </AccordionGroup>
  </Tab>
</Tabs>
