Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I access a low-level client from a Boto 3 resource instance?

For example, I have this code:

import boto3

ec2 = boto3.resource('ec2')

# Where is the client???

Do I need to call boto3.client('ec2') or is there another way?

like image 378
Daniel Avatar asked Nov 11 '14 18:11

Daniel


People also ask

What is the difference between Boto3 resource and client?

00:00 Boto3's primary function is to make AWS API calls for you. It extracts these APIs in two main ways: clients and resources. Clients give you low-level service access, while resources provide an object-oriented way of working with these services.

What is a low-level service client?

Clients provide a low-level interface to AWS whose methods map close to 1:1 with service APIs. All service operations are supported by clients. Clients are generated from a JSON service definition file.

How do I connect my AWS 3 to Boto3?

Setting up a client To access any AWS service with Boto3, we have to connect to it with a client. Here, we create an S3 client. We specify the region in which our data lives. We also have to pass the access key and the password, which we can generate in the AWS console, as described here.

Are Boto3 client thread safe?

boto3. client function is not thread-safe. It can fail when called from multiple threads · Issue #2750 · boto/boto3 · GitHub.


1 Answers

Every resource object has a special attribute called meta, which is a Python dict containing information about the service, access to the low-level client, and sometimes the lazy-loaded cached attributes of the resource. You can access it like so:

client = ec2.meta.client

response = client.reboot_instances(InstanceIds=[...])

This is particularly useful if you created the resource using custom parameters which you don't want to have to keep track of for later:

ec2 = boto3.resource('ec2', region_name='us-west-2')

# This client is now a US-West-2 client
client = ec2.meta.client

As always, be sure to check out the official documentation. Note: this interface changed in boto3#45. Previously meta was a dict.

like image 138
Daniel Avatar answered Oct 28 '22 09:10

Daniel