Пример #1
0
    def start(self):

        env_vars = self.get_env_vars()
        DB = load_database(env_vars['db_path'])

        parser = argparse.ArgumentParser(
            description='Create a new computing instance',
            usage='''propad stop thename

for example:
    propad start box2 
    the command above will restart the stopped box2            
            
''')

        parser.add_argument(
            'name',
            nargs='?',
            help='Enter the name of the box you want to terminate')

        args = parser.parse_args(sys.argv[2:])

        boxname = args.name
        if not boxname:
            raise NameError('You need to enter the name of the box')

        start_instance(boxname, env_vars, DB)
Пример #2
0
    def terminate(self):

        env_vars = PPAD.get_env_vars()
        DB = load_database(env_vars['db_path'])

        parser = argparse.ArgumentParser(
            description='Create a new computing instance',
            usage='''propad terminate thename

for example:
    propad terminate box2
    the command above will terminate the box2 and the associated root volume

''')

        parser.add_argument(
            'name',
            nargs='?',
            help='Enter the name of the box you want to terminate')

        args = parser.parse_args(sys.argv[2:])
        boxname = args.name
        if not boxname:
            raise NameError('You need to enter the name of the box')
        terminate_instance(boxname, env_vars, DB)
Пример #3
0
    def stat(self):
        '''
        Prints out the stat of the running and stopped instances
        '''

        env_vars = self.get_env_vars()
        DB = load_database(env_vars['db_path'])
        show_status(env_vars, DB)
Пример #4
0
    def vol(self):
        '''
        attach volume to instance
        '''

        env_vars = PPAD.get_env_vars()
        DB = load_database(env_vars['db_path'])

        parser = argparse.ArgumentParser(
            description='Attach a volume to running instance',
            usage='''propad vol [instancename]

for example:
    propad vol box2 -s 10 -t g2

''')

        parser.add_argument(
            'name',
            nargs='?',
            help='Enter the name of the box you want to terminate')
        parser.add_argument("-s",
                            "--volsize",
                            type=int,
                            dest="volumesize",
                            help="Enter the volume size:")
        parser.add_argument("-t",
                            "--voltype",
                            dest="volumetype",
                            default="gp2",
                            help="Enter the volume type")
        args = parser.parse_args(sys.argv[2:])

        boxname = args.name
        if not boxname:
            raise NameError('You need to enter the name of the box')
        elif boxname not in DB['running_instances']:
            raise ValueError(
                'You can only attach a volume to running instance')

        volsize = args.volumesize
        if not volsize:
            raise ValueError('You need to provide the volume size')

        voltype = args.volumetype

        attach_volume(boxname, voltype, volsize, env_vars, DB)
Пример #5
0
    def resolvesg(self):
        '''
        limit the access to ssh-only from local machine.
        If you change your location then you need to update this function
        '''

        env_vars = PPAD.get_env_vars()
        DB = load_database(env_vars['db_path'])

        region = env_vars['aws_region']
        access_key = env_vars['access_key']
        secret_key = env_vars['secret_key']

        awssgf = AWSsgFuncs(region, access_key, secret_key)
        awssgf.check_public_ip(env_vars, DB)
        vpcparams = DB[env_vars['vpc_name']]
        awssgf.revoke_sg_permissions_all(vpcparams['vpc_id'])
        awssgf.set_sg_sshonly_local_ip(vpcparams['sg_id'], DB['public_ip'])
Пример #6
0
    def allowhttp(self):
        '''
        allow http access for the given box name
        '''

        env_vars = PPAD.get_env_vars()
        DB = load_database(env_vars['db_path'])

        region = env_vars['aws_region']
        access_key = env_vars['access_key']
        secret_key = env_vars['secret_key']

        awssgf = AWSsgFuncs(region, access_key, secret_key)
        awssgf.check_public_ip(env_vars, DB)
        vpcparams = DB[env_vars['vpc_name']]
        awssgf.revoke_sg_permissions_all(vpcparams['vpc_id'])
        awssgf.set_sg_sshonly_local_ip(vpcparams['sg_id'], DB['public_ip'])
        awssgf.set_sg_http_egress(vpcparams['sg_id'])
Пример #7
0
    def create(self):

        env_vars = self.get_env_vars()
        DB = load_database(env_vars['db_path'])

        parser = argparse.ArgumentParser(
            description='Create a new computing instance',
            usage='''propad create [option]s

If no name is provided an automatic name starting with box will be used.
Please note you can not use names starting with box.
If no instance type is provided the default t2.micro will be sued for aws
as the instance type qualifies for the free tier            
            
''')

        parser.add_argument('name',
                            nargs='?',
                            help='Enter the name you want to use')
        parser.add_argument('type',
                            nargs='?',
                            help='''Enter the type of computing instance
                                                    If you are using AWS see the following link for further info:
                                                    https://aws.amazon.com/ec2/pricing/on-demand/
                                                    ''')

        args = parser.parse_args(sys.argv[2:])

        if not args.name:
            boxname = ''
        else:
            boxname = args.name

        if not args.type:
            boxtype = 't2.micro'
        else:
            boxtype = args.type

        create_instance(boxname, boxtype, shut_down_time, env_vars, DB)
Пример #8
0
def initiate():

    home = os.path.expanduser("~")
    env_dir = os.path.join(home, '.provisionpad')
    if not os.path.isdir(env_dir):
        os.mkdir(env_dir)
    dbpath = os.path.join(env_dir, 'database.p')
    DB = load_database(dbpath)

    home = os.path.expanduser("~")
    env_dir = os.path.join(home, '.provisionpad')
    if not os.path.isdir(env_dir):
        os.mkdir(env_dir)

    env_var_path = os.path.join(env_dir, 'env_variable.json')
    input_var_path = os.path.join(env_dir, 'input_variable.json')

    if os.path.isfile(env_var_path):
        print('the env variable file already exists')
        print('If no manual intteruption seems you are all set')
        sys.exit('Exception handeling for this part will be tested later')

    if not os.path.isfile(input_var_path):
        env_vars = {}
        print('Initiating a new propad environment')
        print(
            '  You can find aws access keys under user tab (top third from right)'
        )
        print(
            '  My security credentials for the root info or under IAM users section'
        )
        print(
            '  For more information please visit: https://docs.aws.amazon.com/general/latest/gr/aws-sec-cred-types.html'
        )
        access_key = input('Please enter your aws access key ID: ')
        env_vars['access_key'] = str(access_key).strip()
        if not env_vars['access_key']:
            print('Invalid input')
            sys.exit()
        secret_key = input('Please enter your aws secret access key: ')
        env_vars['secret_key'] = str(secret_key).strip()
        if not env_vars['secret_key']:
            print('Invalid input')
            sys.exit()
        your_name = input(
            'Please enter the name you want to be associated with the env: ')
        # env_vars['your_name'] = ''.join([x.strip().upper() for x in your_name.split(' ')] )
        env_vars['your_name'] = re.sub('[^a-zA-Z0-9]', '', your_name).upper()
        if not env_vars['your_name']:
            print('Invalid input')
            sys.exit()
        env_vars['your_email'] = input(
            'Please enter the email you want to be associated with the env: ')
        print('\n\n')
        print('NOte: AMI (Image) should be in the same defined aws region')
        print('Otherwise you will encounter errors later on')
        env_vars['aws_region'] = input(
            'Please enter your aws region. If nothing entered us-east-2 would be used as default: '
        )
        if not env_vars['aws_region']:
            env_vars['aws_region'] = 'us-east-2'
        env_vars['aws_ami'] = input(
            'Please enter your aws ami. If nothing entered default Ubuntu 18 will be used: '
        )
        if not env_vars['aws_ami']:
            env_vars[
                'aws_ami'] = 'ami-029f8374ffdc9a057'  #'ami-00df714b389c23925'

        with open(input_var_path, 'w') as f:
            json.dump(env_vars, f, indent=4)

    else:

        with open(input_var_path, 'r') as f:
            env_vars = json.load(f)

    env_vars['db_path'] = dbpath
    env_vars['env_path'] = env_var_path
    env_vars['env_dir'] = env_dir

    key_pair_name = 'ec2_keypair_{0}_{1}.pem'.format(env_vars['your_name'],
                                                     env_vars['aws_region'])
    key_pair_path = os.path.join(env_dir, key_pair_name)

    env_vars['key_pair_name'] = key_pair_name
    env_vars['key_pair_path'] = key_pair_path

    env_vars['vpc_name'] = '{0}_VPC'.format(env_vars['your_name'])

    role_name = [env_vars['your_name']]
    policies = ['S3FULL']
    role_name.extend(policies)
    role_names = ''.join(role_name)

    env_vars['policy'] = policies
    env_vars['role_name'] = role_names

    env_vars['HOME'] = home

    create_vpc(env_vars, DB)

    awsec2f = AWSec2Funcs(env_vars['aws_region'], env_vars['access_key'],
                          env_vars['secret_key'])
    awsstsf = AWSstsFuncs(env_vars['aws_region'], env_vars['access_key'],
                          env_vars['secret_key'])
    awsiamf = AWSiamFuncs(env_vars['aws_region'], env_vars['access_key'],
                          env_vars['secret_key'])

    if not os.path.isfile(env_vars['key_pair_path']):
        if not awsec2f.check_key_pair(env_vars['key_pair_name']):
            try:
                print('creating key pair')
                with open(env_vars['key_pair_path'], 'w') as f:
                    key_pair = str(awsec2f.create_key_pair(key_pair_name))
                    print(key_pair)
                    f.write(key_pair)
                os.chmod(env_vars['key_pair_path'], 0o600)
            except:
                os.remove(env_vars['key_pair_path'])
                raise Exception(
                    'You do not have access to create key-pair check your permissions'
                )
        else:
            raise Exception(
                'we can find the public key but pem is not available')
    else:
        print('the key pair exists')

    account_id = awsstsf.get_account_id()
    policy_attach = []
    for policy in env_vars['policy']:
        policy_arn = 'arn:aws:iam::{0}:policy/{1}'.format(account_id, policy)
        if not awsiamf.check_policy_exists(policy_arn):
            if policy == 'S3FULL':
                awsiamf.ec2_policy_access_full(policy)
                policy_attach.append(policy_arn)
            else:
                print('the policy {0} not implemented yet'.format(policy))
        else:
            print('the policy {0} exists'.format(policy))
            policy_attach.append(policy_arn)

    # # role_arn = 'arn:aws:iam::{0}:role/{1}'.format(account_id, env_vars['role_name'])

    if not awsiamf.check_role_exists(env_vars['role_name']):
        print(awsiamf.create_role_for_ec2(env_vars['role_name']))
        awsiamf.create_instance_profile(env_vars['role_name'])

    if awsiamf.check_role_exists(env_vars['role_name'], 1, 5):
        for policy in policy_attach:
            print('attaching policy arn: {0}'.format(policy))
            awsiamf.attach_policy_to_role(env_vars['role_name'], policy)
            print('policy attached')
    else:
        raise Exception(' was not able to find the role')

    with open(env_var_path, 'w') as f:
        json.dump(env_vars, f, indent=4)
Пример #9
0
if __name__ == "__main__":

    import argparse
    parser = argparse.ArgumentParser(description='A function to create instance', 
                                     usage='%(prog)s [OPTIONS]')
    parser.add_argument("-b", "--box_name", dest="box_name", default="", 
                        help="Enter the name of the sandbox:")
    parser.add_argument("-n", "--volume_name", dest="volume_name", default="", 
                        help="Enter the name of volume:")
    parser.add_argument("-s", "--volume_size", dest="volume_size", default="", 
                        help="Enter the volume size:")
    parser.add_argument("-t", "--volume_type", dest="volume_type", default="gp2", 
                        help="Enter the volume size:")
    args = parser.parse_args()
    
    box_name = args.box_name
    volume_name = args.volume_name
    volume_size = int(args.volume_size)
    volume_type = args.volume_type

    if not box_name:
        print('Please enter the name of the box you want to remove')
        sys.exit()
    if not volume_name:
        volume_name = box_name+'VOL'
    if not volume_size:
        print('Please enter the size of the volume')
        sys.exit()

    DB = load_database()
    create_volume(box_name, volume_name, volume_type, volume_size,  DB)
Пример #10
0
def initiate():

    home = os.path.expanduser("~")
    env_dir = os.path.join(home, '.provisionpad')
    if not os.path.isdir(env_dir):
        os.mkdir(env_dir)
    dbpath = os.path.join(env_dir, 'database.p')
    DB = load_database(dbpath)

    home = os.path.expanduser("~")
    env_dir = os.path.join(home, '.provisionpad')
    if not os.path.isdir(env_dir):
        os.mkdir(env_dir)

    env_var_path = os.path.join(env_dir, 'env_variable.json')
    input_var_path = os.path.join(env_dir, 'input_variable.json')


    if not os.path.isfile(input_var_path):
        env_vars = {}
        ask_for_credentials = True
        print ('Initiating a new propad environment')
        print ('Searching for default AWS credentials...')
        session = boto3.Session()
        credentials = session.get_credentials()
        if credentials:
            use_default_cred = input(textwrap.dedent('''\
                                        Default AWS credentials found.
                                        Do you want to use them?(y/n)
                                        '''))
            if str(use_default_cred).strip()[0] == 'y':
                env_vars['access_key'] = credentials.access_key
                env_vars['secret_key'] = credentials.secret_key
                ask_for_credentials = False
        if ask_for_credentials:
            print ('  You can find aws access keys under user tab (top third from right)')
            print ('  My security credentials for the root info or under IAM users section')
            print ('  For more information please visit: https://docs.aws.amazon.com/general/latest/gr/aws-sec-cred-types.html')
            access_key = input('Enter AWS access key ID: ')
            env_vars['access_key'] = str(access_key).strip()
            if not env_vars['access_key']:
                print ('Invalid input')
                sys.exit()
            secret_key = input('Enter AWS secret access key: ')
            env_vars['secret_key'] = str(secret_key).strip()
            if not env_vars['secret_key']:
                print ('Invalid input')
                sys.exit()
        your_name  = input('Enter your name (optional, will be added as a tag to the instance): ')
        env_vars['your_name'] = re.sub('[^a-zA-Z0-9]', '', your_name).upper()
        if not env_vars['your_name']:
            print ('Invalid input')
            sys.exit()
        # env_vars['your_email'] = input('Enter your email (): ')
        print ('\n')
        print ('Note: AMI (Image) should be in the same defined AWS region.')
        env_vars['aws_region'] = input ('Enter AWS region (us-east-2): ')
        if not env_vars['aws_region']:
            env_vars['aws_region'] = 'us-east-2'
        env_vars['aws_ami'] = input ('Enter your AWS AMI. (Ubuntu 18): ')
        if not env_vars['aws_ami']:
            env_vars['aws_ami'] = 'ami-029f8374ffdc9a057'  #'ami-00df714b389c23925'

        with open(input_var_path, 'w') as f:
            json.dump(env_vars, f, indent=4)

    else:

        with open(input_var_path, 'r') as f:
            env_vars = json.load(f)

    env_vars['db_path'] = dbpath
    env_vars['env_path'] = env_var_path
    env_vars['env_dir'] = env_dir

    key_pair_name = 'ec2_keypair_{0}_{1}.pem'.format(env_vars['your_name'], env_vars['aws_region'])
    key_pair_path = os.path.join(env_dir, key_pair_name)

    env_vars['key_pair_name'] = key_pair_name
    env_vars['key_pair_path'] = key_pair_path

    env_vars['vpc_name'] = '{0}_VPC'.format(env_vars['your_name'])

    role_name   = [env_vars['your_name'] ]
    policies = ['S3FULL']
    role_name.extend(policies)
    role_names = ''.join(role_name)

    env_vars['policy'] = policies
    env_vars['role_name'] = role_names

    env_vars['HOME'] = home

    # get the public ip address of local machine
    DB['public_ip'] = AWSsgFuncs.get_ip_address()
    save_database(DB, env_vars['db_path'])

    create_vpc(env_vars, DB)

    awsec2f = AWSec2Funcs(env_vars['aws_region'], env_vars['access_key'], env_vars['secret_key'])
    awsstsf = AWSstsFuncs(env_vars['aws_region'], env_vars['access_key'], env_vars['secret_key'])
    awsiamf = AWSiamFuncs(env_vars['aws_region'], env_vars['access_key'], env_vars['secret_key'])

    if not os.path.isfile(env_vars['key_pair_path']):
        if not awsec2f.check_key_pair(env_vars['key_pair_name']):
            try:
                print ('creating key pair')
                with open(env_vars['key_pair_path'], 'w') as f:
                    key_pair = str(awsec2f.create_key_pair(key_pair_name))
                    print (key_pair)
                    f.write(key_pair)
                os.chmod(env_vars['key_pair_path'], 0o600)
            except:
                os.remove(env_vars['key_pair_path'])
                raise Exception('You do not have access to create key-pair check your permissions')
        else:
            raise Exception('we can find the public key but pem is not available')
    else:
        print ('the key pair exists')

    account_id = awsstsf.get_account_id()
    policy_attach = []
    for policy in env_vars['policy']:
        policy_arn = 'arn:aws:iam::{0}:policy/{1}'.format(account_id, policy )
        if not awsiamf.check_policy_exists(policy_arn):
            if policy == 'S3FULL':
                awsiamf.ec2_policy_access_full(policy)
                policy_attach.append(policy_arn)
            else:
                print ('the policy {0} not implemented yet'.format(policy))
        else:
            print ('the policy {0} exists'.format(policy))
            policy_attach.append(policy_arn)

    if not awsiamf.check_role_exists(env_vars['role_name']):
        print (awsiamf.create_role_for_ec2(env_vars['role_name']) )
        awsiamf.create_instance_profile(env_vars['role_name'])

    if awsiamf.check_role_exists(env_vars['role_name'], 1, 5):
        for policy in policy_attach:
            print ('attaching policy arn: {0}'.format(policy))
            awsiamf.attach_policy_to_role(env_vars['role_name'], policy)
            print ('policy attached')
    else:
        raise Exception(' was not able to find the role')


    with open(env_var_path, 'w') as f:
        json.dump(env_vars, f, indent=4)