有效管理 AWS 安全群組對於維護安全且經濟高效的雲端環境至關重要。安全群組是 AWS 網路安全的重要組成部分,但隨著時間的推移,未使用的安全群組會不斷累積。這些未使用的群組不僅會使您的環境變得混亂,還可能帶來安全風險或不必要地增加成本。
在本文中,我們將探討如何使用 Python 和 Boto3 識別 AWS 環境中未使用的安全群組、驗證它們並確保它們不被任何其他資源引用。我們還將研究如何安全地確定是否可以刪除這些群組。
要學習本教程,您需要以下內容:
AWS 帳戶:確保您有權存取要搜尋未使用的安全群組的 AWS 環境。
Boto3 已安裝:您可以透過執行以下命令來安裝 Boto3 Python SDK:
pip install boto3
已設定 AWS 憑證:確保您使用 AWS CLI 或使用 IAM 角色或環境變數直接在程式碼中配置了 AWS 憑證。
讓我們看一下程式碼,用於識別給定 AWS 區域中未使用的安全性群組、驗證它們並檢查它們是否被任何其他群組引用。
pip install boto3
import boto3 from botocore.exceptions import ClientError def get_unused_security_groups(region='us-east-1'): """ Find security groups that are not being used by any resources. """ ec2_client = boto3.client('ec2', region_name=region) try: # Get all security groups security_groups = ec2_client.describe_security_groups()['SecurityGroups'] # Get all network interfaces enis = ec2_client.describe_network_interfaces()['NetworkInterfaces'] # Create set of security groups in use used_sg_ids = set() # Check security groups attached to ENIs for eni in enis: for group in eni['Groups']: used_sg_ids.add(group['GroupId']) # Find unused security groups unused_groups = [] for sg in security_groups: if sg['GroupId'] not in used_sg_ids: # Skip default security groups as they cannot be deleted if sg['GroupName'] != 'default': unused_groups.append({ 'GroupId': sg['GroupId'], 'GroupName': sg['GroupName'], 'Description': sg['Description'], 'VpcId': sg.get('VpcId', 'EC2-Classic') }) # Print results if unused_groups: print(f"\nFound {len(unused_groups)} unused security groups in {region}:") print("-" * 80) for group in unused_groups: print(f"Security Group ID: {group['GroupId']}") print(f"Name: {group['GroupName']}") print(f"Description: {group['Description']}") print(f"VPC ID: {group['VpcId']}") print("-" * 80) else: print(f"\nNo unused security groups found in {region}") return unused_groups except ClientError as e: print(f"Error retrieving security groups: {str(e)}") return None
def check_sg_references(ec2_client, group_id): """ Check if a security group is referenced in other security groups' rules """ try: # Check if the security group is referenced in other groups response = ec2_client.describe_security_groups( Filters=[ { 'Name': 'ip-permission.group-id', 'Values': [group_id] } ] ) referencing_groups = response['SecurityGroups'] # Check for egress rules response = ec2_client.describe_security_groups( Filters=[ { 'Name': 'egress.ip-permission.group-id', 'Values': [group_id] } ] ) referencing_groups.extend(response['SecurityGroups']) return referencing_groups except ClientError as e: print(f"Error checking security group references: {str(e)}") return None
要執行腳本,只需執行 validate_unused_groups 函數即可。例如,當區域設定為 us-east-1 時,腳本將:
def validate_unused_groups(region='us-east-1'): """ Validate and provide detailed information about unused security groups """ ec2_client = boto3.client('ec2', region_name=region) unused_groups = get_unused_security_groups(region) if not unused_groups: return print("\nValidating security group references...") print("-" * 80) for group in unused_groups: group_id = group['GroupId'] referencing_groups = check_sg_references(ec2_client, group_id) if referencing_groups: print(f"\nSecurity Group {group_id} ({group['GroupName']}) is referenced by:") for ref_group in referencing_groups: print(f"- {ref_group['GroupId']} ({ref_group['GroupName']})") else: print(f"\nSecurity Group {group_id} ({group['GroupName']}) is not referenced by any other groups") print("This security group can be safely deleted if not needed")
使用此腳本,您可以自動執行在 AWS 中尋找未使用的安全群組的流程,並確保您不會保留不必要的資源。這有助於減少混亂、改善安全狀況,並可能透過刪除未使用的資源來降低成本。
您可以將此腳本擴展為:
確保您的 AWS 環境安全且組織良好!
以上是使用 Python 和 Boto3 尋找並驗證 AWS 中未使用的安全性群組的詳細內容。更多資訊請關注PHP中文網其他相關文章!