Exemple #1
0
def generate_report():
    logging.info('reading dynamodb table')

    try:
        region = boto.sts.regions()
        sts = boto.sts.connect_to_region(region[0].name)

        logging.info('assuming role: {} ({})'.format(role[dynamo_role], dynamo_role))
        sts.assume_role(role_arn=role[dynamo_role], role_session_name=dynamo_role)

    except BotoServerError as e:
        logging.warning('exception: {}'.format(e.error_message))
        logging.critical('could not assume role')
        raise

    table = Table(table_name)
    res = table.scan()
    print 'Report:\n'
    total=0
    for row in res:
        total=total+1
        acc, reg, serv, id, tag = row['id'].split(kdelim)
        since_n = row['tsfirst']
        since_s = time.ctime(since_n)
        days = round((tsnow - since_n) / 86400, 2)
        print ('Acount:       {}\n'
               'Region:       {}\n'
               'Service:      {}\n'
               'Id:           {}\n'
               'Missing tag:  {}\n'
               'First seen:   {}\n'
               'Days missing: {}\n').format(acc, reg, serv, id, tag, since_s, days)

    print '{} missing tags found.'.format(total)
Exemple #2
0
def assume_role(acc):
    try:
        region = boto.sts.regions()
        sts = boto.sts.connect_to_region(region[0].name)

        logging.info('assuming role: {} ({})'.format(role[acc], acc))
        sts.assume_role(role_arn=role[acc], role_session_name=acc)

    except BotoServerError as e:
        logging.warning('exception: {}'.format(e.error_message))
        return -1

    return 1
Exemple #3
0
def assume_role(acc):
    try:
        region = boto.sts.regions()
        sts = boto.sts.connect_to_region(region[0].name)

        logging.info('assuming role: {} ({})'.format(role[acc], acc))
        sts.assume_role(role_arn=role[acc], role_session_name=acc)

    except BotoServerError as e:
        logging.warning('exception: {}'.format(e.error_message))
        return -1

    return 1
def connect_to_aws(module, instance):
    try:
        # Check if we have a AWS_ROLE_ARN_ID set, if so we will attempt
        # to assume a role and connect no matter whether we're on the
        # cross-account profile or not.
        if (instance.aws_profile_name == 'cross-account'
                or os.environ.get('AWS_ROLE_ARN_ID', False)):
            sts = boto.sts.connect_to_region(
                region_name=instance.aws_region_name,
                profile_name=instance.aws_profile_name)
            role = sts.assume_role(role_arn=os.environ['AWS_ROLE_ARN_ID'],
                                   role_session_name="AssumeRoleSession1")
            conn = module.connect_to_region(
                region_name=instance.aws_region_name,
                aws_access_key_id=role.credentials.access_key,
                aws_secret_access_key=role.credentials.secret_key,
                security_token=role.credentials.session_token)
            return conn
        conn = module.connect_to_region(region_name=instance.aws_region_name,
                                        profile_name=instance.aws_profile_name)
        return conn
    except boto.exception.NoAuthHandlerFound:
        raise errors.NoCredentialsError()
    except boto.provider.ProfileNotFoundError as e:
        raise errors.ProfileNotFoundError(instance.aws_profile_name)
def connect_to_aws(module, instance):
    try:
        if instance.aws_profile_name == 'cross-account':
            sts = boto.sts.connect_to_region(
                region_name=instance.aws_region_name,
                profile_name=instance.aws_profile_name
            )
            role = sts.assume_role(
                role_arn=os.environ['AWS_ROLE_ARN_ID'],
                role_session_name="AssumeRoleSession1"
            )
            conn = module.connect_to_region(
                region_name=instance.aws_region_name,
                aws_access_key_id=role.credentials.access_key,
                aws_secret_access_key=role.credentials.secret_key,
                security_token=role.credentials.session_token
            )
            return conn
        conn = module.connect_to_region(
            region_name=instance.aws_region_name,
            profile_name=instance.aws_profile_name
        )
        return conn
    except boto.exception.NoAuthHandlerFound:
        raise errors.NoCredentialsError()
    except boto.provider.ProfileNotFoundError:
        raise errors.ProfileNotFoundError(instance.aws_profile_name)
Exemple #6
0
def connect_to_aws(module, instance):
    try:
        # Check if we have a AWS_ROLE_ARN_ID set, if so we will attempt
        # to assume a role and connect no matter whether we're on the
        # cross-account profile or not.
        if (instance.aws_profile_name == 'cross-account' or
                os.environ.get('AWS_ROLE_ARN_ID', False)):
            sts = boto.sts.connect_to_region(
                region_name=instance.aws_region_name,
                profile_name=instance.aws_profile_name
            )
            role = sts.assume_role(
                role_arn=os.environ['AWS_ROLE_ARN_ID'],
                role_session_name="AssumeRoleSession1"
            )
            conn = module.connect_to_region(
                region_name=instance.aws_region_name,
                aws_access_key_id=role.credentials.access_key,
                aws_secret_access_key=role.credentials.secret_key,
                security_token=role.credentials.session_token
            )
            return conn
        conn = module.connect_to_region(
            region_name=instance.aws_region_name,
            profile_name=instance.aws_profile_name
        )
        return conn
    except boto.exception.NoAuthHandlerFound:
        raise errors.NoCredentialsError()
    except boto.provider.ProfileNotFoundError as e:
        raise errors.ProfileNotFoundError(instance.aws_profile_name)
Exemple #7
0
def generate_report():
    logging.info('reading dynamodb table')

    try:
        region = boto.sts.regions()
        sts = boto.sts.connect_to_region(region[0].name)

        logging.info('assuming role: {} ({})'.format(role[dynamo_role],
                                                     dynamo_role))
        sts.assume_role(role_arn=role[dynamo_role],
                        role_session_name=dynamo_role)

    except BotoServerError as e:
        logging.warning('exception: {}'.format(e.error_message))
        logging.critical('could not assume role')
        raise

    table = Table(table_name)
    res = table.scan()
    print 'Report:\n'
    total = 0
    for row in res:
        total = total + 1
        acc, reg, serv, id, tag = row['id'].split(kdelim)
        since_n = row['tsfirst']
        since_s = time.ctime(since_n)
        days = round((tsnow - since_n) / 86400, 2)
        print('Acount:       {}\n'
              'Region:       {}\n'
              'Service:      {}\n'
              'Id:           {}\n'
              'Missing tag:  {}\n'
              'First seen:   {}\n'
              'Days missing: {}\n').format(acc, reg, serv, id, tag, since_s,
                                           days)

    print '{} missing tags found.'.format(total)
    def _get_sts_token(self):
        """
        Assume a role via STS and return the credentials.

        First connect to STS via :py:func:`boto.sts.connect_to_region`, then
        assume a role using :py:meth:`boto.sts.STSConnection.assume_role`
        using ``self.account_id`` and ``self.account_role`` (and optionally
        ``self.external_id``). Return the resulting
        :py:class:`boto.sts.credentials.Credentials` object.

        :returns: STS assumed role credentials
        :rtype: :py:class:`boto.sts.credentials.Credentials`
        """
        logger.debug("Connecting to STS in region %s", self.region)
        sts = boto.sts.connect_to_region(self.region)
        arn = "arn:aws:iam::%s:role/%s" % (self.account_id, self.account_role)
        logger.debug("STS assume role for %s", arn)
        role = sts.assume_role(arn, "awslimitchecker", external_id=self.external_id)
        logger.debug("Got STS credentials for role; access_key_id=%s", role.credentials.access_key)
        return role.credentials
Exemple #9
0
def connect_to_aws(module, instance):
    try:
        if instance.aws_profile_name == 'cross-account':
            sts = boto.sts.connect_to_region(
                region_name=instance.aws_region_name,
                profile_name=instance.aws_profile_name)
            role = sts.assume_role(role_arn=os.environ['AWS_ROLE_ARN_ID'],
                                   role_session_name="AssumeRoleSession1")
            conn = module.connect_to_region(
                region_name=instance.aws_region_name,
                aws_access_key_id=role.credentials.access_key,
                aws_secret_access_key=role.credentials.secret_key,
                security_token=role.credentials.session_token)
            return conn
        conn = module.connect_to_region(region_name=instance.aws_region_name,
                                        profile_name=instance.aws_profile_name)
        return conn
    except boto.exception.NoAuthHandlerFound:
        raise errors.NoCredentialsError()
    except boto.provider.ProfileNotFoundError:
        raise errors.ProfileNotFoundError(instance.aws_profile_name)
Exemple #10
0
    def _get_sts_token(self):
        """
        Assume a role via STS and return the credentials.

        First connect to STS via :py:func:`boto.sts.connect_to_region`, then
        assume a role using :py:meth:`boto.sts.STSConnection.assume_role`
        using ``self.account_id`` and ``self.account_role`` (and optionally
        ``self.external_id``). Return the resulting
        :py:class:`boto.sts.credentials.Credentials` object.

        :returns: STS assumed role credentials
        :rtype: :py:class:`boto.sts.credentials.Credentials`
        """
        logger.debug("Connecting to STS in region %s", self.region)
        sts = boto.sts.connect_to_region(self.region)
        arn = "arn:aws:iam::%s:role/%s" % (self.account_id, self.account_role)
        logger.debug("STS assume role for %s", arn)
        role = sts.assume_role(arn, "awslimitchecker",
                               external_id=self.external_id)
        logger.debug("Got STS credentials for role; access_key_id=%s",
                     role.credentials.access_key)
        return role.credentials
def get_session_credentials(dataset_name):
    if dataset_name == '':
        return {}
    context = {'model': model, 'session': model.Session,
               'user': c.user or c.author, 'auth_user_obj': c.userobj,
               'save': 'save' in request.params}
    try:
        logic.check_access('package_create', context)
        logic.check_access('package_update', context, {'id': dataset_name})

        sts = boto.connect_sts();
        policy=_get_policy(dataset_name)
        # tok = sts.get_session_token(duration=3600)
        tok = sts.assume_role(config.get('ckanext.s3multipart.s3_role', ''),
                              (c.user+"@"+config.get('ckan.site_id', ''))[:32],
                              policy=policy
                            ).credentials
        return tok.to_dict()
    except boto.exception.NoAuthHandlerFound, e:
        log.error("Amazon AWS credentials not set up for boto. "
                  "Please refer to https://boto.readthedocs.org/en/latest/boto_config_tut.html")
        h.flash_error("Amazon AWS credentials not set up for boto. "
                      "Please refer to https://boto.readthedocs.org/en/latest/boto_config_tut.html")
        return {}
Exemple #12
0
 def _get_sts_token(self):
     """Attempt to get STS token, exit if fail."""
     sts = boto.sts.connect_to_region(self.region)
     arn = "arn:aws:iam::%s:role/%s" % (self.account_id, self.account_role)
     role = sts.assume_role(arn, "awslimitchecker")
     return role.credentials
#!/usr/bin/python
import boto.ec2.elb
import os, boto.sts, sys, string, getopt
import boto.ec2.autoscale
import re
import time

aws_region = ""
aws_role_name = ""
aws_role = ""
aws_session_name = ""
aws_role_external_id = ""
fname = "/tmp/ec2_list.txt"

sts = boto.sts.connect_to_region(aws_region)
creds = sts.assume_role(aws_role, aws_session_name, external_id=aws_role_external_id)

# connect to ec2
ec2_conn = boto.ec2.connect_to_region(aws_region,
   aws_access_key_id=creds.credentials.access_key,
   aws_secret_access_key=creds.credentials.secret_key,
   security_token=creds.credentials.session_token)

# open file with IP addresses
with open(fname) as f:
	content= [x.strip() for x in f.readlines()]

print content

instance_internal_ip=content