Replace <instance-id> with the ID of the EC2 instance and <security-group-id> with the ID of the security group that you want to keep.
Repeat step 3 for all the EC2 instances returned by the first command.
Finally, run the first command again to verify that all the EC2 instances now have only one security group assigned to them.
That’s it! You have successfully remediated the issue of EC2 instances with multiple security groups in AWS using AWS CLI.
Using Python
To remediate EC2 instances with multiple security groups in AWS using Python, follow these steps:Step 1: Import the Boto3 library
Copy
Ask AI
import boto3
Step 2: Create an EC2 client object
Copy
Ask AI
ec2 = boto3.client('ec2')
Step 3: Get a list of all EC2 instances
Copy
Ask AI
instances = ec2.describe_instances()
Step 4: Loop through the instances and check if they have multiple security groups
Copy
Ask AI
for reservation in instances['Reservations']: for instance in reservation['Instances']: if len(instance['SecurityGroups']) > 1: instance_id = instance['InstanceId'] security_group_ids = [sg['GroupId'] for sg in instance['SecurityGroups']]
Step 5: Remove the extra security groups from the instance
This will remove all the extra security groups from the instance and leave only the first security group in the list. You can run this script periodically to ensure that all your EC2 instances have only one security group assigned to them.