How to reboot the Aurora Instance with Failover using Lambda? - amazon-web-services

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
)

Related

Trying to create a python function that creates an ec2 with aws marketplace software

I am trying to make a function that should launch an ec2 instance that contains aws marketplace software. What commands from the boto3 documents would you guys recommend because I am having trouble searching for one that
launches a new ec2
utilizes the aws marketplace software product code to launch with the ami
Thank you
You will most likely want to make use of the DescribeImages and RunInstances actions, which are available methods in the boto3 API (describe_images and run_instances).
The following snippet is a brief example that uses a product code from the AWS Marketplace to launch a new EC2 instance using the image ID:
import boto3
def main():
client = boto3.client("ec2")
# Ubuntu 18.04 LTS - Bionic
product_id = "3b73ef49-208f-47e1-8a6e-4ae768d8a333"
response = client.describe_images(
Filters=[{"Name": "name", "Values": [f"*{product_id}*"]}]
)
images = response["Images"]
image = images[0]
image_id = image["ImageId"] # ami-02ad37ec9b98d835f
response = client.run_instances(
ImageId=image_id,
InstanceType="t2.micro",
MaxCount=1,
MinCount=1,
SubnetId="<your_subnet_id>",
)
print(response)
if __name__ == "__main__":
main()

How to change termination protection by boto3

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'

Iteration not working in Lambda as I want to run lambda in two regions listed in code

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.

Copy AMI to another region using boto3

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'])

fetch vpc peering connection id in boto

I wish to retrieve the vpc peering connection id in boto, something that would be done by "aws ec2 describe-vpc-peering-connections". I couldn't locate its boto equivalent. Is it possible to retrieve it in boto ?
boto3 is different from the previous boto. Here is the solution in boto3:
import boto3
prevar = boto3.client('ec2')
var1 = prevar.describe_vpc_peering_connections()
print(var1)
In boto you would use boto.vpc.get_all_peering_connections(), as in:
import boto.vpc
c = boto.vpc.connect_to_region('us-east-1')
vpcs = c.get_all_vpcs()
vpc_peering_connection = c.create_vpc_peering_connection(vpcs[0].id, vpcs[1].id)
Get all vpc peering IDs
import boto.vpc
conn = boto.vpc.connect_to_region('us-east-1')
vpcpeering = conn.get_all_vpc_peering_connections()
for peering in vpcpeering:
print peering.id
If you know the accepter VPC id and requester vpc ID, you should get the vpc peering id by this way:
import boto.vpc
conn = boto.vpc.connect_to_region('us-east-1')
peering = conn.get_all_vpc_peering_connections(filters = {'accepter-vpc-info.vpc-id' = 'vpc-12345abc','requester-vpc-info.vpc-id' = 'vpc-cba54321'})[0]
print peering.id
If that's the only vpc peering in your environment, an easier way:
import boto.vpc
conn = boto.vpc.connect_to_region('us-east-1')
peering = conn.get_all_vpc_peering_connections()[0]
peering.id