How to stop all EC2 in all AWS regions at the same time?

·

3 min read

Việc dừng tất cả các EC2 instance trên toàn bộ vùng của AWS cùng một lúc nên được thực hiện cẩn thận vì có thể gây ra gián đoạn dịch vụ. Tuy nhiên, nếu bạn cần thực hiện điều này, dưới đây là các cách:

1. Sử dụng AWS Lambda và CloudWatch Event (phù hợp cho người dùng thành thạo)

  • Tạo một IAM role với chính sách chỉ cho phép tìm và dừng EC2 instance.

  • Tạo một Lambda function sử dụng AWS CLI để liệt kê các EC2 instance đang chạy trên tất cả các vùng, sau đó dừng từng instance.

  • Tạo một CloudWatch Event theo lịch trình hoặc kích hoạt theo sự kiện để kích hoạt Lambda function.

2. Sử dụng AWS CLI (cần lưu ý tính an toàn)

Lưu ý: Sử dụng phương pháp này cần thận vì nó có thể dẫn đến việc dừng các instance quan trọng một cách vô tình

Dưới đây là một ví dụ script bằng Python sử dụng Boto3 (thư viện AWS SDK cho Python) để thực hiện điều này:

import boto3

def stop_all_instances():
    # Lấy danh sách tất cả các vùng AWS
    ec2_client = boto3.client('ec2')
    regions = [region['RegionName'] for region in ec2_client.describe_regions()['Regions']]

    for region in regions:
        print(f"Stopping instances in region {region}")
        ec2 = boto3.resource('ec2', region_name=region)

        # Lấy tất cả các instance đang chạy trong vùng
        running_instances = ec2.instances.filter(Filters=[{
            'Name': 'instance-state-name',
            'Values': ['running']
        }])

        # Lấy ID của các instance đang chạy
        instance_ids = [instance.id for instance in running_instances]

        if instance_ids:
            # Dừng các instance
            ec2.instances.filter(InstanceIds=instance_ids).stop()
            print(f"Stopped instances: {instance_ids}")
        else:
            print("No running instances found in this region")

if __name__ == "__main__":
    stop_all_instances()

Hoặc có thể sử dụng qua lambda

import boto3 
ec2_client = boto3.client('ec2')
regions = [region['RegionName'] for region in ec2_client.describe_regions()['Regions']]

def lambda_handler(event, context):
    for region in regions:
        ec2_client = boto3.client('ec2', region)
        all_instances = ec2_client.describe_instances()
        if all_instances:
            print("List all instances:")
            for reservation in all_instances['Reservations']:
                for instance in reservation['Instances']:
                    print(instance['InstanceId'] + "-" + instance['State']['Name'])

                    if instance['State']['Name'] == 'running':
                        print("Stopping ec2: " + instance['InstanceId'])
                        ec2_client.stop_instances(InstanceIds=[instance['InstanceId']])

Tạo một IAM role mới với các quyền cần thiết để dừng EC2 instances và cho phép Lambda sử dụng role này. Gán chính sách sau vào role:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "ec2:DescribeRegions",
        "ec2:DescribeInstances",
        "ec2:StopInstances"
      ],
      "Resource": "*"
    }
  ]
}

Hoặc sử dụng code sau:

import boto3

def lambda_handler(event, context):
    ec2_client = boto3.client('ec2')
    regions = [region['RegionName'] for region in ec2_client.describe_regions()['Regions']]

    for region in regions:
        print(f"Stopping instances in region {region}")
        ec2 = boto3.client('ec2', region_name=region)

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

        instance_ids = []
        for reservation in running_instances['Reservations']:
            for instance in reservation['Instances']:
                instance_ids.append(instance['InstanceId'])

        if instance_ids:
            ec2.stop_instances(InstanceIds=instance_ids)
            print(f"Stopped instances: {instance_ids}")
        else:
            print("No running instances found in this region")