I want to teminate many AWS ec2 instance,then i use boto3 like this:
#!/usr/bin/env python
#coding=utf8
import boto3
ec2 = boto3.resource(
'ec2',
aws_access_key_id="<AK>",
aws_secret_access_key="<SK>",
region_name='eu-central-1'
)
instances = ec2.instances.filter(
Filters=[{'Name': 'instance-state-name', 'Values': ['stopped']}])
ids = ['id1','id2'.....'idn']
status = ec2.instances.filter(InstanceIds=ids).terminate()
print(status)
But I got a ERROR:
botocore.exceptions.ClientError: An error occurred (OperationNotPermitted) when calling the TerminateInstances operation: The instance 'i-0f06b49c1f16dcfde' may not be terminated. Modify its 'disableApiTermination' instance attribute and try again.
please tell me how to modify the disableApiTermination.
Use modify_attribute. See the documentation.
import boto3
ec2 = boto3.resource('ec2')
instances = ec2.instances.filter(
Filters=[{'Name': 'instance-state-name', 'Values': ['stopped']}])
for instance in instances:
print(instance.id)
# after choosing the instances to terminate:
ids = ['id1', 'id2']
for id in ids:
ec2.Instance(id).modify_attribute(
DisableApiTermination={
'Value': False
})
ec2.Instance(id).terminate()
Adding to previous answer, you can also use the following method from client module
client.modify_instance_attribute(InstanceId='string',Attribute="disableApiTermination",Value='True|False'
Related
Below is my working code already (rebooting the Aurora RDS instance on Lambda without failover).
import boto3
region = 'ap-northeast-1'
instances = 'myAuroraInstanceName'
rds = boto3.client('rds', region_name=region)
def lambda_handler(event, context):
rds.reboot_db_instance(
DBInstanceIdentifier=instances
)
print('Rebooting your DB Instance: ' + str(instances))
Please take a second to read the documentation. It's extremely clear from the documentation how you specify the failover setting:
rds.reboot_db_instance(
DBInstanceIdentifier=instances,
ForceFailover=True
)
I am trying to launch EC2 instance and attachig to Target group using following code in lambda function But i am getting following error. But lambda funciton not getting Intsance ID and giving and error, please guide
Error is:
An error occurred (ValidationError) when calling the RegisterTargets operation: Instance ID 'instance_id' is not valid",
"errorType": "ClientError",
Code is :
import boto3
import json
import time
import os
AMI = 'ami-047a51fa27710816e'
INSTANCE_TYPE = os.environ['MyInstanceType']
KEY_NAME = 'miankeyp'
REGION = 'us-east-1'
ec2 = boto3.client('ec2', region_name=REGION)
def lambda_handler(event, context):
instance = ec2.run_instances(
ImageId=AMI,
InstanceType=INSTANCE_TYPE,
KeyName=KEY_NAME,
MaxCount=1,
MinCount=1
)
print ("New instance created:")
instance_id = instance['Instances'][0]['InstanceId']
print (instance_id)
client=boto3.client('elbv2')
time.sleep(5)
response = client.register_targets(
TargetGroupArn='arn:aws:elasticloadbalancing:us-east-1::targetgroup/target-demo/c46e6bfc00b6886f',
Targets=[
{
'Id': 'instance_id'
},
]
)
To wait until an instance is running, you can use an Instance State waiter.
This is a boto3 capability that will check the state of an instance every 15 seconds until it reaches the desired state, up to a limit of 40 checks, which allows 10 minutes.
Hi I have this simple lambda function which stops all EC-2 instances tagged with Auto_off. I have set a for loop so that it works for two regions us-east-1 and us-east-2. I am running the function in us-east-2 region.
the problem is that only the instance located in us-east2 is stopping and the other instance is not(located in us-east-1). what modifications can i make.
please suggest as i am new to python and boto library
import boto3
import logging
#setup simple logging for INFO
logger = logging.getLogger()
logger.setLevel(logging.INFO)
#define the connection
ec2 = boto3.resource('ec2')
client = boto3.client('ec2', region_name='us-east-1')
ec2_regions = ['us-east-1','us-east-2']
for region in ec2_regions:
conn = boto3.resource('ec2',region_name=region)
def lambda_handler(event, context):
# Use the filter() method of the instances collection to retrieve
# all running EC2 instances.
filters = [{
'Name': 'tag:AutoOff',
'Values': ['True']
},
{
'Name': 'instance-state-name',
'Values': ['running']
}
]
#filter the instances
instances = ec2.instances.filter(Filters=filters)
#locate all running instances
RunningInstances = [instance.id for instance in instances]
#print the instances for logging purposes
#print RunningInstances
#make sure there are actually instances to shut down.
if len(RunningInstances) > 0:
#perform the shutdown
shuttingDown = ec2.instances.filter(InstanceIds=RunningInstances).stop()
print shuttingDown
else:
print "Nothing to see here"
You are creating 2 instances of ec2 resource, and 1 instance of ec2 client. You are only using one instance of ec2 resource, and not using the client at all. You are also setting the region in your loop on a different resource object from the one you are actually using.
Change all of this:
ec2 = boto3.resource('ec2')
client = boto3.client('ec2', region_name='us-east-1')
ec2_regions = ['us-east-1','us-east-2']
for region in ec2_regions:
conn = boto3.resource('ec2',region_name=region)
To this:
ec2_regions = ['us-east-1','us-east-2']
for region in ec2_regions:
ec2 = boto3.resource('ec2',region_name=region)
Also your indentation is all wrong in the code in your question. I hope that's just a copy/paste issue and not how your code is really indented, because indentation is syntax in Python.
The loop you do here
ec2_regions = ['us-east-1','us-east-2']
for region in ec2_regions:
conn = boto3.resource('ec2',region_name=region)
Firstly assigns us-east-1 to the conn variable and on the second step, it overwrites it with us-east-2 and then it enters your function.
So what you can do is put that loop inside your function and do the current definition of the function inside that loop.
I'm trying to automate "Copy AMI" functionality I have on my AWS EC2 console, can anyone point me to some Python code that does this through boto3?
From EC2 — Boto 3 documentation:
response = client.copy_image(
ClientToken='string',
Description='string',
Encrypted=True|False,
KmsKeyId='string',
Name='string',
SourceImageId='string',
SourceRegion='string',
DryRun=True|False
)
Make sure you send the request to the destination region, passing in a reference to the SourceRegion.
To be more precise.
Let's say the AMI you want to copy is in us-east-1 (Source region).
Your requirement is to copy this into us-west-2 (Destination region)
Get the boto3 EC2 client session to us-west-2 region and then pass the us-east-1 in the SourceRegion.
import boto3
session1 = boto3.client('ec2',region_name='us-west-2')
response = session1.copy_image(
Name='DevEnv_Linux',
Description='Copied this AMI from region us-east-1',
SourceImageId='ami-02a6ufwod1f27e11',
SourceRegion='us-east-1'
)
I use high-level resources like EC2.ServiceResource most of time, so the following is the code I use to use both EC2 resource and low-level client,
source_image_id = '....'
profile = '...'
source_region = 'us-west-1'
source_session = boto3.Session(profile_name=profile, region_name=source_region)
ec2 = source_session.resource('ec2')
ami = ec2.Image(source_image_id)
target_region = 'us-east-1'
target_session = boto3.Session(profile_name=profile, region_name=target_region)
target_ec2 = target_session.resource('ec2')
target_client = target_session.client('ec2')
response = target_client.copy_image(
Name=ami.name,
Description = ami.description,
SourceImageId = ami.id,
SorceRegion = source_region
)
target_ami = target_ec2.Image(response['ImageId'])
boto3 mentioned on Github that they added support for deleting tags. However, when I execute the code below, it throws an exception:
ec2 = boto3.resource('ec2', region_name=aws_region)
ec2.delete_tags(Resources=[instance.id],Tags=[{"Key": non_compliant_tag_name}])
'ec2.ServiceResource' object has no attribute 'delete_tags'
$ pip show boto3
Name: boto3
Version: 1.4.4
What am I doing wrong?
The delete_tags() method should be called on a client object rather than a resource object:
import boto3
client = boto3.client('ec2', region_name='ap-southeast-2')
...
client.delete_tags(Resources=[instance.id],Tags=[{"Key": non_compliant_tag_name}])
You can use it as follows in Python
import boto3
reservations = ec2.describe_instances(
Filters=[
#{'Name': 'tag:Type', 'Values': ['management']},
]
).get(
'Reservations', []
)
instances = sum(
[
[i for i in r['Instances']]
for r in reservations
], [])
for instance in instances:
# Delete the tag 'baz' if it exists
ec2.delete_tags(Resources=[instance['InstanceId']], Tags=[{"Key": "TAGNAME"}])