本文整理汇总了Python中boto3.Session.client方法的典型用法代码示例。如果您正苦于以下问题:Python Session.client方法的具体用法?Python Session.client怎么用?Python Session.client使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类boto3.Session
的用法示例。
在下文中一共展示了Session.client方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: deliver_sns_message
# 需要导入模块: from boto3 import Session [as 别名]
# 或者: from boto3.Session import client [as 别名]
def deliver_sns_message(self, topic, subject, rendered_jinja_body, sqs_message):
# Max length of subject in sns is 100 chars
if len(subject) > 100:
subject = subject[:97] + '..'
try:
account = topic.split(':')[4]
if account in self.sns_cache:
sns = self.sns_cache[account]
else:
# if cross_accounts isn't set, we'll try using the current credentials
if account not in self.config.get('cross_accounts', []):
session = Session()
else:
creds = self.aws_sts.assume_role(
RoleArn=self.config['cross_accounts'][account],
RoleSessionName="CustodianNotification")['Credentials']
session = Session(
aws_access_key_id=creds['AccessKeyId'],
aws_secret_access_key=creds['SecretAccessKey'],
aws_session_token=creds['SessionToken'])
self.sns_cache[account] = sns = session.client('sns')
self.logger.info("Sending account:%s policy:%s sns:%s to %s" % (
sqs_message.get('account', ''),
sqs_message['policy']['name'],
sqs_message['action'].get('template', 'default'),
topic))
sns.publish(TopicArn=topic, Subject=subject, Message=rendered_jinja_body)
except Exception as e:
self.logger.warning(
"Error policy:%s account:%s sending sns to %s \n %s" % (
sqs_message['policy'], sqs_message.get('account', 'na'), topic, e))
示例2: configure_sqs_client
# 需要导入模块: from boto3 import Session [as 别名]
# 或者: from boto3.Session import client [as 别名]
def configure_sqs_client(graph):
endpoint_url = graph.config.sqs_consumer.endpoint_url
profile_name = graph.config.sqs_consumer.profile_name
region_name = graph.config.sqs_consumer.region_name
session = Session(profile_name=profile_name)
return session.client(
"sqs",
endpoint_url=endpoint_url,
region_name=region_name,
)
示例3: AWSClient
# 需要导入模块: from boto3 import Session [as 别名]
# 或者: from boto3.Session import client [as 别名]
class AWSClient(object):
"""Manages automatically creating and destroying clients to AWS services."""
def __init__(self, resource, config, credentials=None, region_name=None):
"""Constructor
:param resource: AWS specific token for resource type. e.g., 's3', 'sqs', etc.
:type resource: string
:param config: Resource specific configuration
:type config: :class:`botocore.client.Config`
:param credentials: Authentication values needed to access AWS. If no credentials are passed, then IAM
role-based access is assumed.
:type credentials: :class:`util.aws.AWSCredentials`
:param region_name: The AWS region the resource resides in.
:type region_name: string
"""
self.credentials = credentials
self.region_name = region_name
self._client = None
self._resource_name = resource
self._config = config
def __enter__(self):
"""Callback handles creating a new client for AWS access."""
logger.debug('Setting up AWS client...')
session_args = {}
if self.credentials:
session_args['aws_access_key_id'] = self.credentials.access_key_id
session_args['aws_secret_access_key'] = self.credentials.secret_access_key
if self.region_name:
session_args['region_name'] = self.region_name
self._session = Session(**session_args)
self._client = self._session.client(self._resource_name, config=self._config)
self._resource = self._session.resource(self._resource_name, config=self._config)
return self
def __exit__(self, type, value, traceback):
"""Callback handles destroying an existing client."""
pass
@staticmethod
def instantiate_credentials_from_config(config):
if 'credentials' in config and config['credentials']:
credentials_dict = config['credentials']
if 'access_key_id' not in credentials_dict or not credentials_dict['access_key_id']:
raise InvalidAWSCredentials('"credentials" requires "access_key_id" to be populated')
if 'secret_access_key' not in credentials_dict or not credentials_dict['secret_access_key']:
raise InvalidAWSCredentials('"credentials" requires "secret_access_key" to be populated')
return AWSCredentials(credentials_dict['access_key_id'], credentials_dict['secret_access_key'])
示例4: decrypt
# 需要导入模块: from boto3 import Session [as 别名]
# 或者: from boto3.Session import client [as 别名]
def decrypt(self, value, context=None):
if not context:
context = {}
session = Session(profile_name=self.profile_name)
kms = session.client('kms', region_name=self.region)
key_service = KeyService(kms, self.kms_key, context)
return open_aes_ctr_legacy(
key_service,
dict(
key=value.key,
contents=value.contents,
hmac=value.hmac,
)
)
示例5: configure_sns_producer
# 需要导入模块: from boto3 import Session [as 别名]
# 或者: from boto3.Session import client [as 别名]
def configure_sns_producer(graph):
"""
Configure an SNS producer.
The SNS Producer requires the following collaborators:
- Opaque from microcosm.opaque for capturing context information
- an aws sns client, i.e. from boto.
- pubsub message codecs: see tests for examples.
- sns topic arns: see tests for examples.
"""
if graph.metadata.testing:
from unittest.mock import MagicMock
if not graph.config.sns_producer.mock_sns:
return MagicMock()
sns_client = MagicMock()
else:
endpoint_url = graph.config.sns_producer.endpoint_url
profile_name = graph.config.sns_producer.profile_name
region_name = graph.config.sns_producer.region_name
session = Session(profile_name=profile_name)
sns_client = session.client(
"sns",
endpoint_url=endpoint_url,
region_name=region_name,
)
try:
opaque = graph.opaque
except NotBoundError:
opaque = None
if graph.config.sns_producer.skip is None:
# In development mode, default to not publishing because there's typically
# not anywhere to publish to (e.g. no SNS topic)
skip = graph.metadata.debug
else:
# If configured explicitly, respect the flag
skip = strtobool(graph.config.sns_producer.skip)
return SNSProducer(
opaque=opaque,
pubsub_message_schema_registry=graph.pubsub_message_schema_registry,
sns_client=sns_client,
sns_topic_arns=graph.sns_topic_arns,
skip=skip,
deferred_batch_size=graph.config.sns_producer.deferred_batch_size,
)
示例6: encrypt
# 需要导入模块: from boto3 import Session [as 别名]
# 或者: from boto3.Session import client [as 别名]
def encrypt(self, plaintext, context=None):
if not context:
context = {}
session = Session(profile_name=self.profile_name)
kms = session.client('kms', region_name=self.region)
key_service = KeyService(kms, self.kms_key, context)
sealed = seal_aes_ctr_legacy(
key_service,
plaintext,
)
return EncryptedValue(
sealed["key"],
sealed["contents"],
sealed["hmac"],
)
示例7: DatabaseResource
# 需要导入模块: from boto3 import Session [as 别名]
# 或者: from boto3.Session import client [as 别名]
class DatabaseResource(object):
def __init__(self):
self.session = Session(profile_name=profile_name, region_name="us-east-1")
self.content_type = "application/json"
def on_get(self, request, response):
rds = self.session.client('rds')
databases = rds.describe_db_instances()
for instance in databases['DBInstances']:
instance['InstanceCreateTime'] = str(instance["InstanceCreateTime"])
instance['LatestRestorableTime'] = str(instance["LatestRestorableTime"])
response.status = falcon.HTTP_200
response.content_type = self.content_type
response.body = json.dumps(databases)
示例8: CacheResource
# 需要导入模块: from boto3 import Session [as 别名]
# 或者: from boto3.Session import client [as 别名]
class CacheResource(object):
def __init__(self):
self.session = Session(profile_name=profile_name, region_name="us-east-1")
self.content_type = "application/json"
def on_get(self, request, response):
redis = self.session.client('elasticache')
clusters = redis.describe_cache_clusters(ShowCacheNodeInfo=True)
for cluster in clusters['CacheClusters']:
cluster['CacheClusterCreateTime'] = str(cluster['CacheClusterCreateTime'])
for node in cluster["CacheNodes"]:
node['CacheNodeCreateTime'] = str(node['CacheNodeCreateTime'])
response.status = falcon.HTTP_200
response.content_type = self.content_type
response.body = json.dumps(clusters)
示例9: openGate
# 需要导入模块: from boto3 import Session [as 别名]
# 或者: from boto3.Session import client [as 别名]
def openGate(accName, carParkName, bookNum):
session = Session(region_name="us-east-1")
polly = session.client('polly')
s3 = boto3.client('s3')
filename = "voice/", bookNum,".mp3"
filename = str(filename)
text = accName + \
". Welcome to " + \
carParkName + \
". The gate will now open. Enjoy your last day at S.A. Launch."
print (text)
#try:
response = polly.synthesize_speech(
Text=str(text),
OutputFormat="mp3",
VoiceId="Joanna")
with closing(response["AudioStream"]) as stream:
s3.put_object(ACL='public-read', Bucket='sa-launch-demo-onedimsum', Key='voice/filename.mp3', Body=stream.read())
示例10: get_session
# 需要导入模块: from boto3 import Session [as 别名]
# 或者: from boto3.Session import client [as 别名]
def get_session(self):
if self.profile_name:
self._log.info(
'using AWS credential profile %s', self.profile_name)
try:
kwargs = {'profile_name': self.profile_name}
if self.region:
kwargs['region_name'] = self.region
session = Session(**kwargs)
except Exception as ex:
self._log.fatal(
'Could not connect to AWS using profile %s: %s',
self.profile_name, ex)
raise
else:
self._log.debug(
'getting an AWS session with the default provider')
kwargs = {}
if self.region:
kwargs['region_name'] = self.region
session = Session(**kwargs)
if self.role_arn:
self._log.info(
'attempting to assume STS self.role %s', self.role_arn)
try:
self.role_creds = session.client('sts').assume_role(
RoleArn=self.role_arn,
RoleSessionName='repoman-%s' % time.time(),
DurationSeconds=3600)['Credentials']
except Exception as ex:
self._log.fatal(
'Could not assume self.role %s: %s',
self.role_arn, ex)
raise
kwargs = {
'aws_access_key_id': self.role_creds['AccessKeyId'],
'aws_secret_access_key': self.role_creds['SecretAccessKey'],
'aws_session_token': self.role_creds['SessionToken']}
if self.region:
kwargs['region_name'] = self.region
session = Session(**kwargs)
return session
示例11: S3
# 需要导入模块: from boto3 import Session [as 别名]
# 或者: from boto3.Session import client [as 别名]
class S3(object):
def __init__(self, bucket):
self.config = get_config()
self.aws_config = self.__aws_config()
self.session = Session(self.aws_access_key_id,
self.aws_secret_access_key)
self.bucket = bucket
self.s3 = self.session.client('s3')
def __aws_config(self):
path = os.path.expanduser('~/.aws/credentials')
if os.path.exists(path):
config = ConfigParser()
config.readfp(open(path))
return config
@property
def aws_access_key_id(self):
config = self.config.get('aws', 'aws_access_key_id')
if config:
return config
aws = self.aws_config.get('default', 'aws_access_key_id')
if aws:
return aws
raise Exception('Missing aws_access_key_id from config locations')
@property
def aws_secret_access_key(self):
config = self.config.get('aws', 'aws_secret_access_key')
if config:
return config
aws = self.aws_config.get('default', 'aws_secret_access_key')
if aws:
return aws
raise Exception('Missing aws_secret_access_key from config locations')
示例12: deliver_sns
# 需要导入模块: from boto3 import Session [as 别名]
# 或者: from boto3.Session import client [as 别名]
def deliver_sns(self, topic, subject, msg, data):
account = topic.split(':')[4]
if account in self.sns_cache:
sns = self.sns_cache[account]
else:
if account not in self.config['cross_accounts']:
log.error(
"No cross account role for sending sns to %s" % topic)
return
creds = self.sts.assume_role(
RoleArn=self.config['cross_accounts'][account],
RoleSessionName="CustodianNotification")['Credentials']
session = Session(
aws_access_key_id=creds['AccessKeyId'],
aws_secret_access_key=creds['SecretAccessKey'],
aws_session_token=creds['SessionToken'])
self.sns_cache[account] = sns = session.client('sns')
log.info("Sending account:%s policy:%s sns:%s to %s" % (
data.get('account', ''),
data['policy']['name'],
data['action'].get('template', 'default'),
topic))
sns.publish(TopicArn=topic, Subject=subject, Message=msg)
示例13: assume_role
# 需要导入模块: from boto3 import Session [as 别名]
# 或者: from boto3.Session import client [as 别名]
def assume_role(accountID, rgn, event):
ec2_message = ""
cfn_message = ""
rds_message = ""
client = boto3.client('sts')
response = client.assume_role(RoleArn='arn:aws:iam::'+accountID+':role/'+event['CheckRoleName'],
RoleSessionName='AWSLimits')
session = Session(
aws_access_key_id=response['Credentials']['AccessKeyId'],
aws_secret_access_key=response['Credentials']['SecretAccessKey'],
aws_session_token=response['Credentials']['SessionToken'],
region_name=rgn
)
##############
# call trusted advisor for the limit checks
##############
support_client = session.client('support', region_name='us-east-1')
response = support_client.describe_trusted_advisor_check_result(
checkId='eW7HH0l7J9',
language='en'
)
print "Contacting Trusted Advisor..."
# parse the json and find flagged resources that are in warning mode
flag_list = response['result']['flaggedResources']
warn_list=[]
for fr in flag_list:
if fr['metadata'][5] != "Green":
warn_list.append(fr['metadata'][2]+'\n'+'Region: '+fr['metadata'][0]+'\n------------------------'+'\nResource Limit: '+fr['metadata'][3]+'\n'+'Resource Usage: '+fr['metadata'][4]+'\n')
if not warn_list:
print "TA all green"
else:
global ta_message
ta_message = trustedAlert(warn_list)
###############
#call EC2 limits for rgn
###############
ec2_client = session.client('ec2', region_name=rgn)
response = ec2_client.describe_account_attributes()
attribute_list = response['AccountAttributes']
for att in attribute_list:
if att['AttributeName'] == 'max-instances':
limit_of_instances = att['AttributeValues'][0]['AttributeValue']
print"num of limit: "+limit_of_instances
response = ec2_client.describe_instances()
reservation_list = response['Reservations']
num_of_instances = 0
for rsrv in reservation_list:
instance_list = rsrv['Instances']
num_of_instances += len(instance_list)
print "num of instances: "+str(num_of_instances)
#calculate if limit is within threshold
if (float(num_of_instances) / float(limit_of_instances) >= 0.8):
ec2_message = ec2Alert(limit_of_instances, num_of_instances, rgn)
print ec2_message
###############
#cfn resource limit
###############
cfn_client = session.client('cloudformation', region_name=rgn)
stack_limit = cfn_client.describe_account_limits()
if stack_limit['AccountLimits'][0]['Name'] == 'StackLimit':
limit_of_stacks = stack_limit['AccountLimits'][0]['Value']
stacks = cfn_client.describe_stacks()
stack_list = stacks['Stacks']
num_of_stacks = len(stack_list)
if (float(num_of_stacks) / float(limit_of_stacks) >= 0.8):
cfn_message = cloudformationAlert(limit_of_stacks, num_of_stacks, rgn)
print cfn_message
################
#call RDS Limits for rgn
################
rds_client = session.client('rds', region_name=rgn)
instance_limit = rds_client.describe_account_attributes()
service_limit = instance_limit['AccountQuotas'][0]['Max']
service_usage = instance_limit['AccountQuotas'][0]['Used']
if (float(service_usage) / float(service_limit) >= 0.8):
rds_message = rdsAlert(service_limit, service_usage, rgn)
print rds_message
print "Assumed session for "+accountID+" in region "+rgn
rgn_message = ec2_message + cfn_message + rds_message
return rgn_message;
示例14: VpcHandler
# 需要导入模块: from boto3 import Session [as 别名]
# 或者: from boto3.Session import client [as 别名]
class VpcHandler(base.BaseHandler):
"""Manage ``EC2.Vpc`` object lifecycle."""
def __init__(self, ctx, credentials):
"""Create boto3 session and clients."""
super().__init__()
# Create a boto session and add extra
# features to the base class EC2.Vpc
event = 'creating-resource-class.ec2.Vpc'
self._session = Session(**credentials)
self._session.events.register(event, _add_wrapper)
# boto3 clients
self._ec2 = self._session.resource('ec2')
self._client = self._session.client('ec2')
# Context for the resource we want
# to create, update or delete
self._ctx = ctx
self._name = ctx.get('name')
def create_resource(self):
"""Create a VPC, or update it if it already exists."""
self._resource = self._load(self._name, manager_name='vpcs')
if self._resource:
logger.info('VPC %(name)s|%(cidr_block)s already exists.', self._ctx)
else:
self._create_vpc()
# Store the object in the cache for future use
with self._lock:
self._cache[self._name] = self._resource
def update_resource(self):
"""Update a VPC object."""
self._resource = self._load(self._name, manager_name='vpcs')
if self._resource:
self._update_vpc()
# Store the object in the cache for future use
with self._lock:
self._cache[self._name] = self._resource
else:
logger.error('VPC %s does not exist.', self._name)
def delete_resource(self):
"""Delete a ``Vpc`` object."""
self._resource = self._load(self._name, manager_name='vpcs')
if self._resource:
# If an internet gateway is attached to the VPC,
# we try to detach it first
filters = [{
'Name': 'attachment.vpc-id',
'Values': [self._resource.id]
}]
items = list(self._resource.internet_gateways.filter(Filters=filters))
if items:
igw = items[0]
try:
self._resource.detach_internet_gateway(InternetGatewayId=igw.id)
except ClientError as exc:
logger.error(exc)
# Delete the VPC
logger.info('Removing VPC %(name)s|%(cidr_block)s.', self._ctx)
try:
self._client.delete_vpc(VpcId=self._resource.id)
except ClientError as exc:
logger.error(exc)
else:
logger.error('VPC %s does not exist.', self._name)
def _create_vpc(self):
"""Create a ``Vpc`` object."""
logger.info('Creating VPC %(name)s|%(cidr_block)s.', self._ctx)
try:
self._resource = self._ec2.create_vpc(CidrBlock=self._ctx['cidr_block'])
except ClientError as exc:
logger.error(exc)
return
# Wait for the new VPC to become
# available before going any further
waiter = self._client.get_waiter('vpc_available')
waiter.wait(VpcIds=[self._resource.id])
# Set the value of the 'Name' tag
self._resource.name = self._name
# Update other object attributes
self._update_vpc()
def _update_vpc(self):
"""Update a ``Vpc`` object."""
self._update_tags()
self._manage_dhcp_options_set()
#.........这里部分代码省略.........
示例15: RouteTableHandler
# 需要导入模块: from boto3 import Session [as 别名]
# 或者: from boto3.Session import client [as 别名]
class RouteTableHandler(base.BaseHandler):
"""Manage ``EC2.RouteTable`` object lifecycle."""
def __init__(self, ctx, credentials):
"""Create boto3 session and clients."""
super().__init__()
# Create a boto session and add extra
# features to the base class EC2.RouteTable
event = 'creating-resource-class.ec2.RouteTable'
self._session = Session(**credentials)
self._session.events.register(event, _add_wrapper)
# boto3 clients
self._ec2 = self._session.resource('ec2')
self._client = self._session.client('ec2')
# Context for the resource we want
# to create, update or delete
self._ctx = ctx
self._name = ctx.get('name')
def create_resource(self):
"""Create a route table, or update it if it already exists."""
self._resource = self._load(self._name, manager_name='route_tables')
if self._resource:
logger.info('Route table %s already exists.', self._name)
else:
self._create_route_table()
# Store the object in the cache for future use
with self._lock:
self._cache[self._name] = self._resource
def update_resource(self):
"""Update a route table object."""
self._resource = self._load(self._name, manager_name='route_tables')
if self._resource:
self._update_route_table()
# Store the object in the cache for future use
with self._lock:
self._cache[self._name] = self._resource
else:
logger.error('Route table %s does not exist.', self._name)
def delete_resource(self):
"""Delete a ``RouteTable`` object."""
self._resource = self._load(self._name, manager_name='route_tables')
if self._resource:
# Remove subnet associations before deleting the route table
for subnet_name in self._ctx.get('subnets') or []:
subnet = self._load(subnet_name, manager_name='subnets')
if subnet:
filters = [
{
'Name': 'association.subnet-id',
'Values': [subnet.id]
},
{
'Name': 'association.route-table-id',
'Values': [self._resource.id]
}
]
associations = list(self._resource.associations.filter(Filters=filters))
if associations:
# The subnet is associated with this route table
try:
associations[0].delete()
except ClientError as exc:
logger.error(exc)
# Remove the route table
logger.info('Removing route table %s.', self._name)
try:
self._client.delete_route_table(RouteTableId=self._resource.id)
except ClientError as exc:
logger.error(exc)
else:
logger.error('Route table %s does not exist.', self._name)
def _create_route_table(self):
"""Create a ``RouteTable`` object."""
vpc_name = self._ctx['vpc']
vpc = self._load(vpc_name, manager_name='vpcs')
if vpc:
logger.info('Creating route table %s.', self._name)
try:
self._resource = self._ec2.create_route_table(VpcId=vpc.id)
except ClientError as exc:
logger.error(exc)
return
# Set the value of the 'Name' tag
self._resource.name = self._name
# Update other object attributes
#.........这里部分代码省略.........