AWS-使用公共​​IP自动修复EC2

时间:2019-06-04 11:06:45

标签: python amazon-web-services aws-lambda boto3

希望开发一个Python脚本,该脚本将扫描EC2实例以查找公共IP,如果找到,则停止这些实例。

我是Python的新手,因此在尝试将两段代码放在一起时遇到了挑战。


ec2Resource = boto3.resource('ec2')
def lambda_handler(event, context):
        instances = ec2Resource.instances.all()
        for instance in instances:
            #print("inst.public_ip_address",inst.public_ip_address)
            if instance.public_ip_address:
                print("Instance ID: ",instance.id," , Instance Platform: ",instance.platform," , Public IP: ",instance.public_ip_address,", Instance Type:",instance.instance_type,",Instance Image Id: ",instance.image.id) 
response = client.stop_instances(
    InstanceIds=[
        'string',
    ],
    Hibernate=True,
    DryRun=False,
    Force=False
)

基本上,寻找一种自动脚本来发现EC2上的公共IP,然后将其停止。如果上面的脚本看起来很汉堡,我深表歉意

更新: 想想我清理了它以创建列表,然后从该列表中发出停止命令。

#!/usr/bin/python
'''
    Finds instance id, Instance Platform, Public IP, instance type based on tags.
    Returns a list of instances found
'''

import boto3

def instances_find(name, value):
    '''
    Finds instance id's based on tags.
    Returns a list of instances found.
    '''
    list_instances = []
    # filter based on tags
    filters =[
        {
        'Name': name,
        'Values': [
            value,
            ]
        },
    ]
    instances = ec2_resource.instances.filter(Filters=filters)
    for instance in instances:
        # for each instance, append to list
        list_instances.append("Instance ID: ",instance.id," , Instance Platform: ",instance.platform," , Public IP: ",instance.public_ip_address,", Instance Type:",instance.instance_type,",Instance Image Id: ",instance.image.id)
    return list_instances

def instances_stop(list):
    '''
    Stops instances defined in the list.
    '''
    ec2_client.stop_instances(InstanceIds=list)

# enter tag name and value
tag_name = 'tag:environment'
tag_value = 'dev'

ec2_resource = boto3.resource('ec2')
ec2_client = boto3.client('ec2')

# find instances
ec2_list = instances_find(tag_name, tag_value)
# stop instances
ec2_stop = instances_stop(ec2_list)
print('stopped instances: ' + str(ec2_list))

0 个答案:

没有答案