lemur/lemur/plugins/lemur_aws/sts.py

63 lines
2.4 KiB
Python
Raw Normal View History

2015-06-22 22:47:27 +02:00
"""
.. module: lemur.plugins.lemur_aws.sts
2015-06-22 22:47:27 +02:00
:platform: Unix
:copyright: (c) 2018 by Netflix Inc., see AUTHORS for more
2015-06-22 22:47:27 +02:00
:license: Apache, see LICENSE for more details.
.. moduleauthor:: Kevin Glisson <kglisson@netflix.com>
"""
2016-06-27 23:40:46 +02:00
from functools import wraps
import boto3
2015-06-22 22:47:27 +02:00
2019-01-11 20:13:43 +01:00
from botocore.config import Config
2015-06-22 22:47:27 +02:00
from flask import current_app
2019-05-16 16:57:02 +02:00
config = Config(retries=dict(max_attempts=20))
2019-01-11 20:13:43 +01:00
2019-05-16 16:57:02 +02:00
def sts_client(service, service_type="client"):
2016-06-27 23:40:46 +02:00
def decorator(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if current_app.config.get("LEMUR_AWS_REGION"):
deployment_region = current_app.config.get("LEMUR_AWS_REGION")
sts = boto3.client('sts', region_name=deployment_region,
endpoint_url=f"https://sts.{deployment_region}.amazonaws.com/",
config=config)
else:
sts = boto3.client("sts", config=config)
2019-05-16 16:57:02 +02:00
arn = "arn:aws:iam::{0}:role/{1}".format(
kwargs.pop("account_number"),
current_app.config.get("LEMUR_INSTANCE_PROFILE", "Lemur"),
2016-06-27 23:40:46 +02:00
)
2016-06-27 23:40:46 +02:00
# TODO add user specific information to RoleSessionName
2019-05-16 16:57:02 +02:00
role = sts.assume_role(RoleArn=arn, RoleSessionName="lemur")
2016-06-27 23:40:46 +02:00
2019-05-16 16:57:02 +02:00
if service_type == "client":
2016-06-27 23:40:46 +02:00
client = boto3.client(
service,
2019-05-16 16:57:02 +02:00
region_name=kwargs.pop("region", "us-east-1"),
aws_access_key_id=role["Credentials"]["AccessKeyId"],
aws_secret_access_key=role["Credentials"]["SecretAccessKey"],
aws_session_token=role["Credentials"]["SessionToken"],
config=config,
2016-06-27 23:40:46 +02:00
)
2019-05-16 16:57:02 +02:00
kwargs["client"] = client
elif service_type == "resource":
2016-06-27 23:40:46 +02:00
resource = boto3.resource(
service,
2019-05-16 16:57:02 +02:00
region_name=kwargs.pop("region", "us-east-1"),
aws_access_key_id=role["Credentials"]["AccessKeyId"],
aws_secret_access_key=role["Credentials"]["SecretAccessKey"],
aws_session_token=role["Credentials"]["SessionToken"],
config=config,
2016-06-27 23:40:46 +02:00
)
2019-05-16 16:57:02 +02:00
kwargs["resource"] = resource
2016-06-27 23:40:46 +02:00
return f(*args, **kwargs)
return decorated_function
return decorator