modify_instance_attribute()只接受关键字参数

时间:2018-06-13 09:25:18

标签: python amazon-ec2 aws-lambda boto3

我有以下任务:

1.检查实例是否有标签“Terminate_On”

如果是:

2.检查实例是否应该今天终止

如果是:

3.如果启用,请删除实例终止保护 终止实例

我被困在第3部分:不知道如果启用了如何删除保护

response=ec.modify_instance_attribute(instance_ids,"disableApiTermination", "true" )
  File "/var/runtime/botocore/client.py", line 312, in _api_call
    "%s() only accepts keyword arguments." % py_operation_name)
TypeError: modify_instance_attribute() only accepts keyword arguments.

如果我修改为:

ec.modify_instance_attribute(InstanceIds=instance_ids,"disableApiTermination", "true" )

然后得到:

关键字arg之后的非关键字arg(lambda_function.py,第34行)

import boto3   
import collections     
import datetime     
import time     
import sys 

ec = boto3.client('ec2', 'eu-west-1')     
ec2 = boto3.resource('ec2', 'eu-west-1')     
from datetime import datetime
from dateutil.relativedelta import relativedelta

date_after_month = datetime.now()+ relativedelta(days=7)
#print date_after_month.strftime('%d/%m/%Y')
today=datetime.now().strftime('%d/%m/%Y')


def lambda_handler(event, context):           
    instance_ids = []
    reservations = ec.describe_instances(     
        Filters=[     
            {'Name': 'tag:Owner', 'Values': ['Unknown', 'unknown']},     
        ]     
    ).get('Reservations', []) 

    for reservation in reservations:
          instances = reservation['Instances']
          for instance in instances:
              instance_ids.append(instance['InstanceId'])
              tags = {}
              for tag in instance['Tags']:
                tags[tag['Key']] = tag['Value']  
                if 'TerminateOn' in tags:  
                  if tags["TerminateOn"]==today:
                    #remove termination protection if enabled
                    ec.modify_instance_attribute(instance_ids,"disableApiTermination", "true" )
                    #terminate instance
                    ec.terminate_instances(InstanceIds=instance_ids)
                  else: 
                    print "No need for termination"
                if not 'TerminateOn' in tags:  
                     ec2.create_tags(Resources=instance_ids,Tags=[{'Key':'TerminateOn','Value':date_after_month.strftime('%d/%m/%Y')}])



print("Stopping instances: {}".format(','.join(instance_ids)))

1 个答案:

答案 0 :(得分:2)

根据boto3 modify_instance_attribute documentation,试试这个(未经过测试的代码):

ec.modify_instance_attribute(
    InstanceIds=instance_id, 
    DisableApiTermination={'Value': True})