Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions PKG-INFO
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
Metadata-Version: 1.2
Name: pyaws
Version: 0.4.1
Summary: Python Utilities for Amazon Web Services
Home-page: http://pyaws.readthedocs.io
Author: Blake Huber
Author-email: blakeca00@gmail.com
License: GPL-3.0
Description:
**pyaws** | Utilities Library for Amazon Web Services (AWS)
-----------------------------------------------------------

PACKAGE: pyaws

``pyaws``: reusable library of utility classes and functions common AWS use cases and capabilities:

* uploading to s3
* adding/ deleting resource tags
* adding data elements to dynamodb table
* Determining the latest Amazon Machine Image in a region for Windows, Linux, etc



Keywords: Amazon Web Services AWS iam ec2 lambda rds s3 sts
Platform: UNKNOWN
Classifier: Topic :: System :: Systems Administration
Classifier: Topic :: Utilities
Classifier: Development Status :: 4 - Beta
Classifier: Programming Language :: Python :: 3.5
Classifier: Programming Language :: Python :: 3.6
Classifier: Programming Language :: Python :: 3.7
Classifier: License :: OSI Approved :: GNU General Public License v3 (GPLv3)
Classifier: Operating System :: POSIX :: Linux
Requires-Python: >=3.6, <4
22 changes: 22 additions & 0 deletions build/lib/pyaws/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
from pyaws._version import __version__ as version


__author__ = 'Blake Huber'
__version__ = version
__credits__ = []
__license__ = "GPL-3.0"
__maintainer__ = "Blake Huber"
__email__ = "blakeca00@gmail.com"
__status__ = "Development"


# the following imports require __version__ #

try:
import logging

# shared, global logger object
logger = logging.getLogger(__version__)

except Exception:
pass
1 change: 1 addition & 0 deletions build/lib/pyaws/_version.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
__version__ = '0.4.1'
6 changes: 6 additions & 0 deletions build/lib/pyaws/awslambda/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
"""
Functional Utilities for AWS Lambda
"""

from pyaws.awslambda.lambda_utils import *
from pyaws.awslambda.env import read_env_variable
90 changes: 90 additions & 0 deletions build/lib/pyaws/awslambda/env.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
"""

lambda_utils (python3)

Common functionality for use with AWS Lambda Service

Author:
Blake Huber
Copyright Blake Huber, All Rights Reserved.

License:

MIT License.
Additional terms may be found in the complete license agreement:
https://opensource.org/licenses/MIT

Project README:
https://github.com/fstab50/pyaws/blob/master/README.md
"""

import os
import re
import inspect
from pyaws import logger


def read_env_variable(arg, default=None, patterns=None):
"""
Summary.

Parse environment variables, validate characters, convert
type(s). default should be used to avoid conversion of an
variable and retain string type

Usage:
>>> from lambda_utils import read_env_variable
>>> os.environ['DBUGMODE'] = 'True'
>>> myvar = read_env_variable('DBUGMODE')
>>> type(myvar)
True

>>> from lambda_utils import read_env_variable
>>> os.environ['MYVAR'] = '1345'
>>> myvar = read_env_variable('MYVAR', 'default')
>>> type(myvar)
str

Args:
:arg (str): Environment variable name (external name)
:default (str): Default if no variable found in the environment under
name in arg parameter
:patterns (None): Unused; not user callable. Used preservation of the
patterns tuple between calls during runtime

Returns:
environment variable value, TYPE str

"""
if patterns is None:
patterns = (
(re.compile('^[-+]?[0-9]+$'), int),
(re.compile('\d+\.\d+'), float),
(re.compile(r'^(true|false)$', flags=re.IGNORECASE), lambda x: x.lower() == 'true'),
(re.compile('[a-z/]+', flags=re.IGNORECASE), str),
(re.compile('[a-z/]+\.[a-z/]+', flags=re.IGNORECASE), str),
)

if arg in os.environ:
var = os.environ[arg]
if var is None:
ex = KeyError('environment variable %s not set' % arg)
logger.exception(ex)
raise ex
else:
if default:
return str(var) # force default type (str)
else:
for pattern, func in patterns:
if pattern.match(var):
return func(var)
# type not identified
logger.warning(
'%s: failed to identify environment variable [%s] type. May contain \
special characters' % (inspect.stack()[0][3], arg)
)
return str(var)
else:
ex = KeyError('environment variable %s not set' % arg)
logger.exception(ex)
raise ex
144 changes: 144 additions & 0 deletions build/lib/pyaws/awslambda/lambda_utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
"""

lambda_utils (python3)

Common functionality for use with AWS Lambda Service

Author:
Blake Huber
Copyright Blake Huber, All Rights Reserved.

License:

MIT License.
Additional terms may be found in the complete license agreement:
https://opensource.org/licenses/MIT

Project README:
https://github.com/fstab50/pyaws/blob/master/README.md
"""


import os
import re
import json
import time
import inspect
import boto3
from botocore.exceptions import ClientError
from pyaws import logger


def get_account_info(account_profile=None):
"""
Summary.

Queries AWS iam and sts services to discover account id information
in the form of account name and account alias (if assigned)

Returns:
TYPE: tuple

Example usage:

>>> account_number, account_name = lambda_utils.get_account_info()
>>> print(account_number, account_name)
103562488773 tooling-prod

"""
if account_profile:
session = boto3.Session(profile_name=account_profile)
sts_client = session.client('sts')
iam_client = session.client('iam')
else:
sts_client = boto3.client('sts')
iam_client = boto3.client('iam')

try:
number = sts_client.get_caller_identity()['Account']
name = iam_client.list_account_aliases()['AccountAliases'][0]

except IndexError as e:
name = '<no_alias_assigned>'
logger.info('Error: %s. No account alias defined. account_name set to %s' % (e, name))
return (number, name)
except ClientError as e:
logger.warning(
"%s: problem retrieving caller identity (Code: %s Message: %s)" %
(inspect.stack()[0][3], e.response['Error']['Code'], e.response['Error']['Message'])
)
raise e
return (number, name)


def get_regions():
"""
Summary.

Returns list of region codes for all AWS regions worldwide

Returns:
TYPE: list

"""
try:
client = boto3.client('ec2')
region_response = client.describe_regions()
regions = [region['RegionName'] for region in region_response['Regions']]

except ClientError as e:
logger.critical(
"%s: problem retrieving aws regions (Code: %s Message: %s)" %
(inspect.stack()[0][3], e.response['Error']['Code'],
e.response['Error']['Message']))
raise e
return regions


def sns_notification(topic_arn, subject, message, account_id=None, account_name=None):
"""
Summary.

Sends message to AWS sns service topic provided as a
parameter

Args:
topic_arn (str): sns topic arn
subject (str): subject of sns message notification
message (str): message body

Returns:
TYPE: Boolean | Success or Failure

"""
if not (account_id or account_name):
account_id, account_name = get_account_info()

# assemble msg
header = 'AWS Account: %s (%s) | %s' % \
(str(account_name).upper(), str(account_id), subject)
msg = '\n%s\n\n%s' % (time.strftime('%c'), message)
msg_dict = {'default': msg}

# client
region = (topic_arn.split('sns:', 1)[1]).split(":", 1)[0]
client = boto3.client('sns', region_name=region)

try:
# sns publish
response = client.publish(
TopicArn=topic_arn,
Subject=header,
Message=json.dumps(msg_dict),
MessageStructure='json'
)
if response['ResponseMetadata']['HTTPStatusCode'] == '200':
return True
else:
return False
except ClientError as e:
logger.exception(
'%s: problem sending sns msg (Code: %s Message: %s)' %
(inspect.stack()[0][3], e.response['Error']['Code'],
e.response['Error']['Message']))
return False
Loading