Example #1
0
 def test_default_profile_specified_raises_exception(self):
     # If you explicity set the default profile and you don't
     # have that in your config file, an exception is raised.
     config_path = os.path.join(os.path.dirname(__file__), 'cfg',
                                'boto_config_empty')
     self.environ['FOO_CONFIG_FILE'] = config_path
     self.environ['FOO_PROFILE'] = 'default'
     session = create_session(session_vars=self.env_vars)
     # In this case, even though we specified default, because
     # the boto_config_empty config file does not have a default
     # profile, we should be raising an exception.
     with self.assertRaises(botocore.exceptions.ProfileNotFound):
         session.get_scoped_config()
Example #2
0
 def test_default_profile_specified_raises_exception(self):
     # If you explicity set the default profile and you don't
     # have that in your config file, an exception is raised.
     config_path = os.path.join(os.path.dirname(__file__), 'cfg',
                                'boto_config_empty')
     self.environ['FOO_CONFIG_FILE'] = config_path
     self.environ['FOO_PROFILE'] = 'default'
     session = create_session(session_vars=self.env_vars)
     # In this case, even though we specified default, because
     # the boto_config_empty config file does not have a default
     # profile, we should be raising an exception.
     with self.assertRaises(botocore.exceptions.ProfileNotFound):
         session.get_scoped_config()
Example #3
0
 def test_profile_does_not_exist_with_default_profile(self):
     session = create_session(session_vars=self.env_vars)
     config = session.get_scoped_config()
     # We should have loaded this properly, and we'll check
     # that foo_access_key which is defined in the config
     # file should be present in the loaded config dict.
     self.assertIn('aws_access_key_id', config)
Example #4
0
def main():
    profile, command = parse_args()
    session = botocore.session.Session(profile=profile)
    configure_cache(session)
    config = session.get_scoped_config()
    creds = session.get_credentials()

    # Unset variables for sanity sake
    os.unsetenv('AWS_ACCESS_KEY_ID')
    os.unsetenv('AWS_SECRET_ACCESS_KEY')
    os.unsetenv('AWS_SESSION_TOKEN')
    os.unsetenv('AWS_DEFAULT_PROFILE')
    os.unsetenv('AWS_PROFILE')

    region = config.get('region', None)
    if region:
        os.putenv('AWS_DEFAULT_REGION', region)
        os.putenv('AWS_REGION', region)

    os.putenv('AWS_ACCESS_KEY_ID', creds.access_key)
    os.putenv('AWS_SECRET_ACCESS_KEY', creds.secret_key)
    if creds.token:
        if os.getenv('AWS_TOKEN_TYPE') == 'security':
            os.putenv('AWS_SECURITY_TOKEN', creds.token)
        else:
            os.putenv('AWS_SESSION_TOKEN', creds.token)

    my_env = os.environ.copy()
    command_status = os.system(command)
    exit(os.WEXITSTATUS(command_status))
Example #5
0
 def test_profile_does_not_exist_with_default_profile(self):
     session = create_session(session_vars=self.env_vars)
     config = session.get_scoped_config()
     # We should have loaded this properly, and we'll check
     # that foo_access_key which is defined in the config
     # file should be present in the loaded config dict.
     self.assertIn('aws_access_key_id', config)
Example #6
0
def main():
    profile, command, cache = parse_args()
    session = botocore.session.Session(profile=profile)
    if cache == 'true':
        configure_cache(session)
    config = session.get_scoped_config()
    creds = session.get_credentials()

    # Unset variables for sanity sake
    os.unsetenv('AWS_ACCESS_KEY_ID')
    os.unsetenv('AWS_SECRET_ACCESS_KEY')
    os.unsetenv('AWS_SESSION_TOKEN')

    region = config.get('region', None)
    if region:
        os.putenv('AWS_DEFAULT_REGION', region)
        os.putenv('AWS_REGION', region)

    os.putenv('AWS_ACCESS_KEY_ID', creds.access_key)
    os.putenv('AWS_SECRET_ACCESS_KEY', creds.secret_key)
    if creds.token:
        if os.getenv('AWS_TOKEN_TYPE') == 'security':
            os.putenv('AWS_SECURITY_TOKEN', creds.token)
        else:
            os.putenv('AWS_SESSION_TOKEN', creds.token)

    returncode = subprocess.call(command,
                                 stdin=sys.stdin,
                                 stdout=sys.stdout,
                                 stderr=sys.stderr)

    exit(sys.exit(returncode))
Example #7
0
 def test_config_loader_delegation(self):
     session = create_session(profile='credfile-profile')
     with temporary_file('w') as f:
         f.write('[credfile-profile]\naws_access_key_id=a\n')
         f.write('aws_secret_access_key=b\n')
         f.flush()
         session.set_config_variable('credentials_file', f.name)
         # Now trying to retrieve the scoped config should pull in
         # values from the shared credentials file.
         self.assertEqual(session.get_scoped_config(),
                          {'aws_access_key_id': 'a',
                           'aws_secret_access_key': 'b'})
Example #8
0
 def test_config_loader_delegation(self):
     session = create_session(profile='credfile-profile')
     with temporary_file('w') as f:
         f.write('[credfile-profile]\naws_access_key_id=a\n')
         f.write('aws_secret_access_key=b\n')
         f.flush()
         session.set_config_variable('credentials_file', f.name)
         # Now trying to retrieve the scoped config should pull in
         # values from the shared credentials file.
         self.assertEqual(session.get_scoped_config(),
                          {'aws_access_key_id': 'a',
                           'aws_secret_access_key': 'b'})
Example #9
0
File: __init__.py Project: cxz/skew
 def _build_account_map(self, session):
     """
     Builds up a dictionary mapping account IDs to profile names.
     Any profile which includes an ``account_name`` variable is
     included.
     """
     account_map = {}
     for profile in session.available_profiles:
         session.profile = profile
         config = session.get_scoped_config()
         account_id = config.get('account_id')
         if account_id:
             account_map[account_id] = profile
     return account_map
Example #10
0
 def test_profile_does_not_exist_raises_exception(self):
     # Given we have no profile:
     self.environ['FOO_PROFILE'] = 'profile_that_does_not_exist'
     session = create_session(session_vars=self.env_vars)
     with self.assertRaises(botocore.exceptions.ProfileNotFound):
         session.get_scoped_config()
Example #11
0
 def test_profile_does_not_exist_raises_exception(self):
     # Given we have no profile:
     self.environ['FOO_PROFILE'] = 'profile_that_does_not_exist'
     session = create_session(session_vars=self.env_vars)
     with self.assertRaises(botocore.exceptions.ProfileNotFound):
         session.get_scoped_config()
Example #12
0
def main():

    #
    # parse args
    #

    parser = argparse.ArgumentParser()

    parser.add_argument('-v',
                        '--verbose',
                        help='verbose output',
                        action='store_true')

    parser.add_argument('command', help='command passed to aws cli', nargs='+')

    args = parser.parse_args()

    command = ' '.join(args.command)

    credentials_file = str(
        os.getenv('AWS_ENCRYPTED_CREDENTIALS_FILE', '~/.aws/credentials.gpg'))
    config_file = str(os.getenv('AWS_CONFIG_FILE', '~/.aws/config'))
    profile = str(
        os.getenv('AWS_PROFILE', os.getenv('AWS_DEFAULT_PROFILE', 'default')))

    if args.verbose:
        print 'AWS_ENCRYPTED_CREDENTIALS_FILE={}'.format(credentials_file)
        print 'AWS_CONFIG_FILE={}'.format(config_file)
        print 'AWS_DEFAULT_PROFILE={}'.format(profile)
        print 'command:', command

    #
    # parse config
    #

    config = ConfigParser.ConfigParser()
    config.read(os.path.expanduser(config_file))

    config_section = 'profile ' + profile

    source_profile = profile
    role_arn = None

    if config.has_option(config_section, 'source_profile'):
        source_profile = config.get(config_section, 'source_profile')

    if config.has_option(config_section, 'role_arn'):
        role_arn = config.get(config_section, 'role_arn')

    if args.verbose:
        print 'source_profile=' + str(source_profile)
        print 'role_arn=' + str(role_arn)

    #
    # read encrypted file
    #

    credentials_file = os.path.expanduser(credentials_file)

    if not os.path.exists(credentials_file):
        sys.exit(
            'Unable to find credentials file, {}'.format(credentials_file))

    try:
        with open(credentials_file, mode='rb') as file:
            encrypted = file.read()

    except IOError as e:
        sys.exit('I/O error({0}): {1}; credentials_file: {2}'.format(
            e.errno, e.strerror, credentials_file))

    except:
        sys.exit('Unexpected error:'.format(sys.exc_info()[0]))

    #
    # gpgme
    #

    gme = gpgme.Context()

    encrypted_bytes = io.BytesIO(encrypted)
    decrypted_bytes = io.BytesIO()

    try:
        gme.decrypt(encrypted_bytes, decrypted_bytes)
    except gpgme.GpgmeError as e:
        sys.exit('Unable to decrypt file; {}'.format(e.strerror))

    decrypted_string = decrypted_bytes.getvalue().decode('utf8')

    #
    # parse credentials
    #

    # make sure to read all of decrypted_bytes
    decrypted_bytes.seek(0)

    credentials = ConfigParser.ConfigParser()
    credentials.readfp(decrypted_bytes)

    if not credentials.has_section(source_profile):
        sys.exit(
            'Credentials file does not have source_profile "{}", AWS_PROFILE={}'
            .format(source_profile, profile))

    if not credentials.has_option(source_profile, 'aws_access_key_id'):
        sys.exit(
            'Credentials file source_profile does not have aws_access_key_id, {}'
            .format(source_profile))

    if not credentials.has_option(source_profile, 'aws_secret_access_key'):
        sys.exit(
            'Credentials file source_profile does not have aws_secret_access_key, {}'
            .format(source_profile))

    aws_access_key_id = credentials.get(source_profile, 'aws_access_key_id')
    aws_secret_access_key = credentials.get(source_profile,
                                            'aws_secret_access_key')

    #
    # setup a botocore session
    #

    session = botocore.session.Session(profile=profile)
    session.set_credentials(aws_access_key_id, aws_secret_access_key)

    try:
        scoped_config = session.get_scoped_config()
        region = scoped_config.get('region', None)
        if region:
            os.putenv('AWS_DEFAULT_REGION', region)
            os.putenv('AWS_REGION', region)

    except botocore.exceptions.ProfileNotFound as e:
        sys.exit('Profile not found in config; profile={}'.format(profile))

    if args.verbose:
        print 'AWS_DEFAULT_REGION={}'.format(region)

    #
    # switch iam roles using sts
    #

    if role_arn == None:
        os.putenv('AWS_ACCESS_KEY_ID', aws_access_key_id)
        os.putenv('AWS_SECRET_ACCESS_KEY', aws_secret_access_key)

    else:
        sts_client = session.create_client('sts')

        assumed_role_object = sts_client.assume_role(
            RoleArn=role_arn, RoleSessionName='AssumeRoleSession1')

        role_credentials = assumed_role_object['Credentials']

        os.putenv('AWS_ACCESS_KEY_ID', role_credentials['AccessKeyId'])
        os.putenv('AWS_SECRET_ACCESS_KEY', role_credentials['SecretAccessKey'])
        os.putenv('AWS_SESSION_TOKEN', role_credentials['SessionToken'])

    #
    # run the command
    #

    if args.verbose:
        print 'Command output:'

    my_env = os.environ.copy()
    command_status = os.system(command)

    exit(os.WEXITSTATUS(command_status))