def get_instances_by_region(self, region): ''' Makes an AWS EC2 API call to the list of instances in a particular region ''' try: cfg = Config() cfg.load_credential_file(os.path.expanduser("~/.aws/credentials")) cfg.load_credential_file(os.path.expanduser("~/.aws/config")) session_token = cfg.get(self.boto_profile, "aws_session_token") conn = ec2.connect_to_region(region, security_token=session_token, profile_name=self.boto_profile) # connect_to_region will fail "silently" by returning None if the # region name is wrong or not supported if conn is None: print("region name: {} likely not supported, or AWS is down. " "connection to region failed.".format(region)) sys.exit(1) reservations = conn.get_all_instances(filters=self.filters) bastion_ip = self.find_bastion_box(conn) instances = [] for reservation in reservations: instances.extend(reservation.instances) # sort the instance based on name and index, in this order def sort_key(instance): name = instance.tags.get('Name', '') return "{}-{}".format(name, instance.id) for instance in sorted(instances, key=sort_key): self.add_instance(bastion_ip, instance, region) except boto.provider.ProfileNotFoundError as e: raise Exception( "{}, configure it with 'aws configure --profile {}'".format( e.message, self.boto_profile)) except boto.exception.BotoServerError as e: print(e) sys.exit(1)
import os import sys from boto.pyami.config import Config from fabric.colors import red # Load the configuration file if os.path.exists('config.ini'): boto_config = Config() boto_config.load_credential_file('config.ini') if boto_config.items('Credentials'): AWS_ID = boto_config.get('Credentials', 'aws_access_key_id') AWS_KEY = boto_config.get('Credentials', 'aws_secret_access_key') REGION = boto_config.get('Credentials', 'region') else: print(red('Error: credentials section is missing, abort!')) sys.exit(1) if boto_config.items('Config'): DEFAULT_OS = boto_config.get('Config', 'default_os') DEFAULT_SSH_DIR = os.path.expanduser(boto_config.get('Config', 'default_ssh_dir')) DEFAULT_FILE_DIR = os.path.expanduser(boto_config.get('Config', 'default_file_dir')) DEFAULT_INTERNAL_DOMAIN = boto_config.get('Config', 'default_internal_domain') else: print(red('Error: config section is missing, abort!')) sys.exit(1) else: print(red('Error: configuration file missing, abort!')) sys.exit(1) AWS_REGIONS = { 'ap-northeast-1': 'Asia Pacific (Tokyo)', 'ap-southeast-1': 'Asia Pacific (Singapore)',