Example #1
0
def _cleanup_table_backups(backup_name):
    session = boto3.session.Session(profile_name=parameters.get_profile_name())
    client = session.client('dynamodb')
    res = client.list_backups(TableName=parameters.get_table_name())
    for bkp in res['BackupSummaries']:
        if bkp['BackupName'] == backup_name:
            client.delete_backup(BackupArn=bkp['BackupArn'])
Example #2
0
def test_parameters_overrides():
    data_overrides = {
        'profile': 'my profile',
        'pre_salt': 'my salt',
        'table_name': 'my table'
    }
    parameters.set_data(data_overrides)
    assert data_overrides['profile'] == parameters.get_profile_name()
    assert data_overrides['pre_salt'] == parameters.get_pre_salt()
    assert data_overrides['table_name'] == parameters.get_table_name()
Example #3
0
def has_table(table_name):
    "Checks if the table exists"
    #TODO: manage Session in a better way. The table resource should be stored in the Session
    try:
        session = boto3.session.Session(profile_name=parameters.get_profile_name())
        dynamodb = session.resource('dynamodb')
        names = [x.table_name for x in dynamodb.tables.all()]
        return table_name in names
    except Exception as e:
        print(e)
        logger.error(e)
        sys.exit(1)
Example #4
0
def get_credentials(config_file=CREDENTIALS_FILE):
    """Retrieves AWS credentials
    input:
    config_file       a path to the AWS configuration file
    output:
    a dictionary with the AWS credentials
    """
    parser = configparser.ConfigParser()
    ret = {}
    if has_credentials(config_file):
        parser.read(config_file)
        ret = parser[parameters.get_profile_name()]
    return ret
Example #5
0
def create_table(table_name=parameters.get_table_name()):
    "Creates a table if it does not exist"
    if has_table(table_name):
        return
    session = boto3.session.Session(profile_name=parameters.get_profile_name())
    dynamodb = session.resource('dynamodb')
    try:
        dynamodb.create_table(
            TableName=f"{table_name}",
            # Declare your Primary Key in the KeySchema argument
            KeySchema=[
                {
                    "KeyType": "HASH",
                    "AttributeName": "domain"
                },
                {
                    "KeyType": "RANGE",
                    "AttributeName": "access"
                }
            ],

            # Any attributes used in KeySchema or Indexes must be declared in AttributeDefinitions
            AttributeDefinitions=[
                {
                    "AttributeName": "access",
                    "AttributeType": "S"
                },
                {
                    "AttributeName": "domain",
                    "AttributeType": "S"
                }
            ],
            # ProvisionedThroughput controls the amount of data you can read or write to DynamoDB per second.
            # You can control read and write capacity independently.
            ProvisionedThroughput={
                "ReadCapacityUnits": 5,
                "WriteCapacityUnits": 5
            },
        )
    except Exception as e:
        logger.error(e)
    if has_table(table_name):
        logger.info(f"Table {table_name} has been created")
        print(f"Table {table_name} has been created")
Example #6
0
def set_credentials(config_file, access_key, secret_access_key, region):
    """make or update credentials
    input:
    config_file       a path to the AWS configuration file
    access_key        the AWS access key
    secret_access_key the secret access key
    region            the AWS region
    """
    parser = configparser.ConfigParser()
    if has_credentials(config_file):
        parser.read(config_file)
    else:
        touch(config_file)
    parser[parameters.get_profile_name()] = {
        'aws_access_key_id': access_key,
        'aws_secret_access_key': secret_access_key,
        'region': region
    }

    with open(config_file, 'w') as f:
        parser.write(f)
Example #7
0
def test_parameters_configure(set_up):
    conf_file = set_up
    parameters.configure(conf_file)
    assert 'my profile' == parameters.get_profile_name()
    assert 'my salt' == parameters.get_pre_salt()
    assert 'my table' == parameters.get_table_name()
Example #8
0
def test_parameters_singleton():
    assert parameters is not None
    assert AWS_PROFILE == parameters.get_profile_name()
    assert SECRET_ACCESS_TABLE == parameters.get_table_name()
    assert parameters is Parameters()  #singleton test
Example #9
0
def _drop_table(table_name):
    #TODO: manage Session in a better way. The table resource should be stored in the Session
    session = boto3.session.Session(profile_name=parameters.get_profile_name())
    dynamodb = session.resource('dynamodb')
    dynamodb.Table(table_name).delete()
Example #10
0
def _backup_table(backup_name):
    session = boto3.session.Session(profile_name=parameters.get_profile_name())
    client = session.client('dynamodb')
    res = client.create_backup(TableName = parameters.get_table_name(), BackupName = backup_name)
    return res['BackupDetails']['BackupArn']
Example #11
0
def make_configurations():
    "Main configuration script"
    print("\nMain configuration script for your secret wallet.")
    print(
        "Please press return to accept the pre-set values in square brackets, or type a new value:\n"
    )

    answ = input("\nDo you want to configure the AWS credentials? (yes|skip) ")
    if answ.lower().startswith('y'):
        profile = input('{0:30}[{1:>30}] = '.format(
            'AWS profile name', parameters.get_profile_name()))
        if len(profile) == 0:
            profile = parameters.get_profile_name()
        if has_credentials() and profile in get_credentials_sections():
            print(
                'The AWS profile {0} is already in use. Choose another or reconfigure'
                .format(profile))
            exit(1)
        parameters.set_profile_name(profile)
        access_key = input('{0:30}[{1:>30}] = '.format('AWS access key id',
                                                       ''))
        secret_access_key = input('{0:30}[{1:>30}] = '.format(
            'AWS secret access key', ''))
        region = input('{0:30}[{1:>30}] = '.format('AWS region', ''))
        cred = {
            'aws access key id': access_key,
            'aws seceret access key': secret_access_key,
            'aws region': region
        }

        display_configuration(CREDENTIALS_FILE, 'AWS credentials are located',
                              cred)
        answ = input("\nDo you want to set the credentials? (yes|skip|exit) ")
        if answ.lower().startswith('y'):
            set_credentials(CREDENTIALS_FILE, access_key, secret_access_key,
                            region)
        elif answ.lower().startswith('s'):
            pass
        else:
            exit(1)

    answ = input(
        "\nDo you want to configure the the secret-wallet parameters? (yes|skip) "
    )
    if answ.lower().startswith('y'):
        profile = input('{0:30}[{1:>30}] = '.format(
            'AWS profile name', parameters.get_profile_name()))
        if len(profile) == 0:
            profile = parameters.get_profile_name()
        table = input('{0:30}[{1:>30}] = '.format('DynameDB table name',
                                                  parameters.get_table_name()))
        if len(table) == 0:
            table = parameters.get_table_name()
        if has_configuration() and has_table(table):

            print(
                'The secret-wallet has been configured previously for the same table.\nTo protect secrets, you need to call a reconfigure procedure'
            )
            exit(1)
        conf_pwd = get_password('Configuration password', 6)
        conf_key = encrypt_key(conf_pwd)

        conf = {
            'configuration key': conf_key,
            'profile': profile,
            'table': table
        }
        parameters.set_profile_name(profile)
        parameters.set_table_name(table)
        display_configuration(CONFIG_FILE,
                              'secret wallet configuration is located', conf)
        answ = input(
            "\nDo you want to set the configuration parameters? (yes|exit) ")
        if answ.lower().startswith('y'):
            try:
                set_configuration(conf_key, profile, table, None, CONFIG_FILE)
                create_table(table)
            except Exception as e:
                print(e)
                print(
                    "Could not write the configuration file. Make sure you have AWS connection and try again"
                )
        else:
            exit(1)