Turn on logging for a CloudTrail Trail

        Args:
            region (`str`): Name of the AWS region
            name (`str`): Name of the CloudTrail Trail

        Returns:
            `None`
498784
def start_logging(self, region, name):
        
        ct = self.session.client('cloudtrail', region_name=region)
        ct.start_logging(Name=name)

        auditlog(
            event='cloudtrail.start_logging',
            actor=self.ns,
            data={
                'account': self.account.account_name,
                'region': region
            }
        )
        self.log.info('Enabled logging for {} ({})'.format(name, region))
1275517
def from_store_name(bucket_name, region=None):
    
    # Late-bind `region` for the sake of tests that inject the
    # AWS_REGION environment variable.
    if region is None:
        region = os.getenv('AWS_REGION')

    mostly_ok = _is_mostly_subdomain_compatible(bucket_name)

    if not mostly_ok:
        return CallingInfo(
            bucket_name=bucket_name,
            region=region,
            calling_format=connection.OrdinaryCallingFormat,
            ordinary_endpoint=must_resolve(region))
    else:
        if '.' in bucket_name:
            # The bucket_name might have been DNS compatible, but once
            # dots are involved TLS certificate validations will
            # certainly fail even if that's the case.
            return CallingInfo(
                bucket_name=bucket_name,
                calling_format=connection.OrdinaryCallingFormat,
                region=region,
                ordinary_endpoint=must_resolve(region))
        else:
            # If the bucket follows naming rules and has no dots in
            # the name, SubdomainCallingFormat can be used, with TLS,
            # world-wide.
            return CallingInfo(
                bucket_name=bucket_name,
                calling_format=connection.SubdomainCallingFormat,
                region=region,
                ordinary_endpoint=None)

    assert False
834304
def cloudtrail_policy(original, bucket_name, account_id, bucket_region):
    ''''''
    ct_actions = [
        {
            'Action': 's3:GetBucketAcl',
            'Effect': 'Allow',
            'Principal': {'Service': 'cloudtrail.amazonaws.com'},
            'Resource': generate_arn(
                service='s3', resource=bucket_name, region=bucket_region),
            'Sid': 'AWSCloudTrailAclCheck20150319',
        },
        {
            'Action': 's3:PutObject',
            'Condition': {
                'StringEquals':
                {'s3:x-amz-acl': 'bucket-owner-full-control'},
            },
            'Effect': 'Allow',
            'Principal': {'Service': 'cloudtrail.amazonaws.com'},
            'Resource': generate_arn(
                service='s3', resource=bucket_name, region=bucket_region),
            'Sid': 'AWSCloudTrailWrite20150319',
        },
    ]
    # parse original policy
    if original is None:
        policy = {
            'Statement': [],
            'Version': '2012-10-17',
        }
    else:
        policy = json.loads(original['Policy'])
    original_actions = [a.get('Action') for a in policy['Statement']]
    for cta in ct_actions:
        if cta['Action'] not in original_actions:
            policy['Statement'].append(cta)
    return json.dumps(policy)
107403
def db_aws_list_regions(self):
        '''  '''
        regions = self.db_services.list_regions()
        if regions != []:
            print "Avaliable AWS regions:"
        for reg in regions:
            print '\t' + reg,
            if reg == self.db_services.get_region():
                print "(currently selected)"
            else:
                print ''
1292346
def validate_sns_topic_subscription(self, region):
        
        sns = self.session.client('sns', region_name=region)
        arn = 'arn:aws:sns:{}:{}:{}'.format(region, self.account.account_number, self.topic_name)
        try:
            data = sns.list_subscriptions_by_topic(TopicArn=arn)
        except ClientError as ex:
            self.log.error('Failed to list subscriptions by topic in {} ({}): {}'.format(
                self.account.account_name,
                region,
                ex
            ))
            return False

        for sub in data['Subscriptions']:
            if sub['Endpoint'] == self.sqs_queue:
                if sub['SubscriptionArn'] == 'PendingConfirmation':
                    self.log.warning('Subscription pending confirmation for {} in {}'.format(
                        self.account.account_name,
                        region
                    ))
                    return False
                return True

        return False
294252
def __get_connection_cloudwatch():
    
    region = get_global_option('region')
    try:
        if (get_global_option('aws_access_key_id') and
                get_global_option('aws_secret_access_key')):
            logger.debug(
                'Authenticating to CloudWatch using '
                'credentials in configuration file')
            connection = cloudwatch.connect_to_region(
                region,
                aws_access_key_id=get_global_option('aws_access_key_id'),
                aws_secret_access_key=get_global_option(
                    'aws_secret_access_key'))
        else:
            logger.debug(
                'Authenticating using boto\'s authentication handler')
            connection = cloudwatch.connect_to_region(region)

    except Exception as err:
        logger.error('Failed connecting to CloudWatch: {0}'.format(err))
        logger.error(
            'Please report an issue at: '
            'https://github.com/sebdah/dynamic-dynamodb/issues')
        raise

    logger.debug('Connected to CloudWatch in {0}'.format(region))
    return connection
1108735
def parse_trail(self, global_params, region, trail):
        
        trail_config = {}
        trail_config['name'] = trail.pop('Name')
        trail_id = self.get_non_aws_id(trail_config['name'])
        trail_details = None

        api_client = api_clients[region]

        # Do not duplicate entries for multiregion trails
        if 'IsMultiRegionTrail' in trail and trail['IsMultiRegionTrail'] and trail['HomeRegion'] != region:
            for key in ['HomeRegion', 'TrailARN']:
                trail_config[key] = trail[key]
            trail_config['scout2_link'] = 'services.cloudtrail.regions.%s.trails.%s' % (trail['HomeRegion'], trail_id)
        else:
            for key in trail:
                trail_config[key] = trail[key]
            trail_config['bucket_id'] = self.get_non_aws_id(trail_config.pop('S3BucketName'))
            for key in ['IsMultiRegionTrail', 'LogFileValidationEnabled']:
                if key not in trail_config:
                    trail_config[key] = False
            trail_details = api_client.get_trail_status(Name=trail['TrailARN'])
            for key in ['IsLogging', 'LatestDeliveryTime', 'LatestDeliveryError', 'StartLoggingTime', 'StopLoggingTime', 'LatestNotificationTime', 'LatestNotificationError', 'LatestCloudWatchLogsDeliveryError', 'LatestCloudWatchLogsDeliveryTime']:
                trail_config[key] = trail_details[key] if key in trail_details else None

        if trail_details:
            trail_config['wildcard_data_logging'] = self.data_logging_status(trail_config['name'], trail_details, api_client)

        self.trails[trail_id] = trail_config
813025
def destroy_s3_event(app, env, region):
    

    # TODO: how do we know which bucket to process if triggers dict is empty?
    # Maybe list buckets and see which has notification to that lambda defined?
    # TODO: buckets should be named the same as apps, what if one app has multiple buckets?
    # bucket = rules.get('bucket')
    generated = get_details(app=app, env=env)

    bucket = generated.s3_app_bucket()

    session = boto3.Session(profile_name=env, region_name=region)
    s3_client = session.client('s3')

    config = {}

    s3_client.put_bucket_notification_configuration(Bucket=bucket, NotificationConfiguration=config)
    LOG.debug("Deleted Lambda S3 notification")

    return True
1116485
def get_limits(self):
        
        logger.debug("Gathering %s's limits from AWS", self.service_name)

        if self.limits:
            return self.limits
        limits = {}

        limits['Trails Per Region'] = AwsLimit(
            'Trails Per Region',
            self,
            5,
            self.warning_threshold,
            self.critical_threshold,
            limit_type=self.aws_type
        )

        limits['Event Selectors Per Trail'] = AwsLimit(
            'Event Selectors Per Trail',
            self,
            5,
            self.warning_threshold,
            self.critical_threshold,
            limit_type=self.aws_type,
            limit_subtype='AWS::CloudTrail::EventSelector'
        )

        limits['Data Resources Per Trail'] = AwsLimit(
            'Data Resources Per Trail',
            self,
            250,
            self.warning_threshold,
            self.critical_threshold,
            limit_type=self.aws_type,
            limit_subtype='AWS::CloudTrail::DataResource'
        )

        self.limits = limits
        return limits
311394
def region_option(f):
    
    def callback(ctx, param, value):
        state = ctx.ensure_object(Context)
        state.region = value
        return value

    return click.option('--region',
                        expose_value=False,
                        help='Set the AWS Region of the service (e.g. us-east-1).',
                        callback=callback)(f)
1095942
def _init_boto3_clients(self):
        
        try:
            profile = self._config.get('environment', {}).get('profile')
            region = self._config.get('environment', {}).get('region')
            if profile:
                self._b3Sess = boto3.session.Session(profile_name=profile)
            else:
                self._b3Sess = boto3.session.Session()

            self._s3 = self._b3Sess.client('s3')
            self._cloudFormation = self._b3Sess.client('cloudformation', region_name=region)
            self._ssm = self._b3Sess.client('ssm', region_name=region)

            return True
        except Exception as wtf:
            logging.error('Exception caught in intialize_session(): {}'.format(wtf))
            traceback.print_exc(file=sys.stdout)
            return False
379397
def get_region_products(self, region):
        

        regions, retInfo = self.list_regions()
        if regions is None:
            return None

        for r in regions:
            if r.get('name') == region:
                return r.get('products')
1009127
def enable_sns_notification(self, region, trailName):
        
        ct = self.session.client('cloudtrail', region_name=region)
        ct.update_trail(Name=trailName, SnsTopicName=self.topic_name)

        auditlog(
            event='cloudtrail.enable_sns_notification',
            actor=self.ns,
            data={
                'account': self.account.account_name,
                'region': region
            }
        )
        self.log.info('Enabled SNS notifications for trail {} in {}/{}'.format(
            trailName,
            self.account.account_name,
            region
        ))
1064564
def _get_bucket_region(self, bucket_name):
        

        # Region set in constructor, return right here.
        if self._region:
            return self._region

        # get bucket location for Amazon S3.
        region = 'us-east-1'  # default to US standard.
        if bucket_name in self._region_map:
            region = self._region_map[bucket_name]
        else:
            region = self._get_bucket_location(bucket_name)
            self._region_map[bucket_name] = region

        # Success.
        return region
694725
def region(region)
      if(region.to_s == 'us')
        config['api_host'] = US_API_HOST
      elsif(region.to_s == 'eu')
        config['api_host'] = EU_API_HOST
      else
        raise "Region Unknown"
      end
    end
1223429
def get_elasticache_replication_groups_by_region(self, region):
        ''' '''

        # ElastiCache boto module doesn't provide a get_all_intances method,
        # that's why we need to call describe directly (it would be called by
        # the shorthand method anyway...)
        try:
            conn = elasticache.connect_to_region(region)
            if conn:
                response = conn.describe_replication_groups()

        except boto.exception.BotoServerError as e:
            error = e.reason

            if e.error_code == 'AuthFailure':
                error = self.get_auth_error_message()
            if not e.reason == "Forbidden":
                error = "Looks like AWS ElastiCache [Replication Groups] is down:\n%s" % e.message
            self.fail_with_error(error, 'getting ElastiCache clusters')

        try:
            # Boto also doesn't provide wrapper classes to ReplicationGroups
            # Because of that wo can't make use of the get_list method in the
            # AWSQueryConnection. Let's do the work manually
            replication_groups = response['DescribeReplicationGroupsResponse']['DescribeReplicationGroupsResult']['ReplicationGroups']

        except KeyError as e:
            error = "ElastiCache [Replication Groups] query to AWS failed (unexpected format)."
            self.fail_with_error(error, 'getting ElastiCache clusters')

        for replication_group in replication_groups:
            self.add_elasticache_replication_group(replication_group, region)
1205528
def cloudwatch_connection(self):
        
        if self._cloudwatch_connection is None:
            conn = self._session.create_client("cloudwatch", self.connection.region)
            self._cloudwatch_connection = conn
        return self._cloudwatch_connection