awspice.services package

Submodules

awspice.services.acm module

class awspice.services.acm.AcmService[source]

Bases: awspice.services.base.AwsBase

Class belonging to the ACM certificate management service.

list_certificates(regions=[])[source]

List all certificates

Parameters:regions (lst) – List of regions to list certificates
Returns:List of certificates
get_certificate_by(filter_key, filter_value, regions=[])[source]

Get certificate filtering by domain

Parameters:
  • filter_key (str) – Name of the field to be searched. (Domain)
  • filter_value (str) – Value for the previous field. (i.e.: google.es)
  • regions (lst) – List of regions where the certificate can be.
Returns:

Certificate matched to the filter entered.

get_certificate(arn, regions=[])[source]

Get certificate using CertificateArn (Ceritificate Identifier)

Parameters:
  • arn (str) – ARN of the certificate
  • regions (lst) – List of regions where the certificate can be.
Returns:

Certificate matched to the ARN entered.

__init__()[source]

This constructor configures the corresponding service according to the class that calls it.

Every time the EC2Service Class is called (inherits from this class), this constructor will change the client’s service to ‘ec2’. And then, if ELBService service is called, this method is called again changing the service from ‘ec2’ to ‘elb’.

Parameters:service (str) – AWS service to uso
Returns:None

awspice.services.base module

class awspice.services.base.AwsBase(service)[source]

Bases: object

Base class from which all services inherit (ec2, s3, vpc …)

This class contains methods and properties that are common to all AWS services and should be accessible by all of them. This class is responsible for instantiating the client and processing information related to the accounts and regions.

client

Boto3 client

region

Current region used by the client

profile

Current profile used by the client

access_key

Current access key used by the client

secret_key

Current secret key used by the client

endpoints = None
region = None
profile = None
access_key = None
secret_key = None
pool = <awspice.helpers.ThreadPool object>
service_resources = ['ec2', 's3']
set_client(service)[source]

Main method to set Boto3 client

Parameters:
  • service (str) – Service to use (i.e.: ec2, s3, vpc…)
  • region (str) – Region name to use (i.e.: eu-central-1)
  • profile (str) – Profile name set in ~/.aws/credentials file
  • access_key (str) – API access key of your AWS account
  • secret_key (str) – API secret key of your AWS account
Raises:
  • ClientError – Access keys are not valid or lack of permissions for a service/region
  • ProfileNotFound – Profile name not found in credentials file
Returns:

None

classmethod set_auth_config(region, profile=None, access_key=None, secret_key=None)[source]

Set properties like service, region or auth method to be used by boto3 client

Parameters:
  • service (str) – Service to use (i.e.: ec2, s3, vpc…)
  • region (str) – Region name (i.e.: eu-central-1)
  • access_key (str) – API Access key
  • secret_key (str) – API Secret key
  • profile (str) – Profile name set in ~/.aws/credentials file
classmethod get_client_vars()[source]

Get information of the current client configuration Sometimes we need to store this variables, for example using threads, because AwsBase is constantly changing

Returns:Array with current client configuration ({‘region’: ‘eu-west-1’, ‘profile’: ‘default’})
Return type:dict
classmethod inject_client_vars(elements, client_conf=None)[source]

Insert in each item of a list, the region and the current credentials.

This function is called by all the methods of all the services that return a list of objects to identify in what region and account they have been found.

Parameters:
  • elements (list) – List of dictionaries
  • client_conf (dict) – Array with the client configuration (see get_client_vars)
Returns:

list. Returns same list with the updated elements (region and authentication included)

region_in_regions(region, regions)[source]

Check if region is in a complex list of regions

Parameters:
  • region (str | lst) – ‘eu-west-1’}
  • regions (lst) –

Examples

region_in_regions(‘eu-west-1’, [{‘RegionName’: ‘eu-west-1}])

Returns:bool
classmethod validate_filters(input_filters, accepted_filters)[source]

Transform filters into AWS filters format after validate them.

Parameters:
  • input_filters (str) – Items to validate
  • accepted_filters (list) – Pre-validated list
Returns:

None

Raises:

ValueError – Filter is not in the accepted filter list

classmethod get_profiles()[source]

Get a list of all available profiles in ~/.aws/credentials file

Returns:list. List of strings with available profiles
change_profile(profile)[source]

Change profile of the client

This method changes the account/profile used but keeps the same region and service

Parameters:profile (str) – Name of the profile set in ~/.aws/credentials file

Examples

$ aws = awspice.connect() $ aws.service.ec2.change_profile(‘my_boring_company’)

Returns:None
parse_profiles(profiles=[])[source]

Validation method which get a profile or profile list and return the expected list of them

The purpose of this method is that a user can pass different types of data as a “profile” argument and obtain a valid output for any method that works with this type of data.

Parameters:profiles (list | str) – String or list of string to parse

Examples

$ account_str = aws.service.ec2.parse_profiles(‘my_company’) $ account_lst = aws.service.ec2.parse_profiles([‘my_company’]) $ accounts_lst = aws.service.ec2.parse_profiles([‘my_company’, ‘other_company’])

Returns:list. List of a strings with profile names
get_endpoints()[source]

Get services and its regions and endpoints

Returns:Dict with services (key) and its regions and Endpoints.
Return type:dict
get_regions()[source]

Get all available regions

Returns:list. List of regions with ‘Country’ and ‘RegionName’
change_region(region)[source]

Change region of the client

This method changes the region used but keeps the same service and profile

Parameters:region (str) – Region Name (ID) of AWS (i.e.: eu-central-1)

Examples

aws.service.ec2.change_region(‘eu-west-1’)

Returns:None
parse_regions(regions=[], default_all=False)[source]

Validation method which get a region or list of regions and return the expected list of them

The purpose of this method is that a user can pass different types of data as a “region” argument and obtain a valid output for any method that works with this type of data.

Parameters:
  • regions (list | str) – String or list of string to parse
  • default_all (bool) – If the list of regions is empty and this argument is True, a list with all regions will be returned. This is useful when you do not know the data entry of type “region” and you want to search by default in all regions (if regions are empty means that the user does not know where an element is located).

Examples

AwsBase.region = aws.service.ec2.parse_regions([]) regions = aws.service.ec2.parse_regions(‘eu-west-1’) regions = aws.service.ec2.parse_regions([‘eu-west-1’]) regions = aws.service.ec2.parse_regions([‘eu-west-1’, ‘eu-west-2’])

Returns:list. List of a strings with profile names
__init__(service)[source]

This constructor configures the corresponding service according to the class that calls it.

Every time the EC2Service Class is called (inherits from this class), this constructor will change the client’s service to ‘ec2’. And then, if ELBService service is called, this method is called again changing the service from ‘ec2’ to ‘elb’.

Parameters:service (str) – AWS service to uso
Returns:None

awspice.services.ce module

class awspice.services.ce.CostExplorerService[source]

Bases: awspice.services.base.AwsBase

Class belonging to the Cost Explorer service.

granularities = ['DAILY', 'MONTHLY']
filter_dimensions = ['AZ', 'INSTANCE_TYPE', 'LINKED_ACCOUNT', 'OPERATION', 'PURCHASE_TYPE', 'REGION', 'SERVICE', 'USAGE_TYPE', 'USAGE_TYPE_GROUP', 'RECORD_TYPE', 'OPERATING_SYSTEM', 'TENANCY', 'SCOPE', 'PLATFORM', 'SUBSCRIPTION_ID', 'LEGAL_ENTITY_NAME', 'DEPLOYMENT_OPTION', 'DATABASE_ENGINE', 'CACHE_ENGINE', 'INSTANCE_TYPE_FAMILY']
group_dimensions = ['AZ', 'INSTANCE_TYPE', 'LEGAL_ENTITY_NAME', 'LINKED_ACCOUNT', 'OPERATION', 'PLATFORM', 'PURCHASE_TYPE', 'SERVICE', 'TAG', 'TENANCY', 'USAGE_TYPE']
get_cost(from_date=None, to_date=None, interval='Monthly', group_by='', group_by_tag_value='', filter_by={}, ec2_running_hours=False)[source]

Get the cost of account or its elements.

This method obtains costs of an account/s , one or several elements (substances, balancers, addresses) between two dates and granularized in days or months. If the date is not indicated, the cost of the last month will be returned.

Parameters:
  • from_date (str) – Date from which you want to obtain data. (Format: 2018-04-24)
  • to_date (str) – Date until which you want to obtain data. (Format: 2018-04-24)
  • interval (str) – Time interval to be analyzed. [ MONTHLY | DAILY ]
  • group_by (str) – Group results by [‘AZ’, ‘INSTANCE_TYPE’, ‘LEGAL_ENTITY_NAME’, ‘LINKED_ACCOUNT’, ‘OPERATION’, ‘PLATFORM’, ‘PURCHASE_TYPE’, ‘SERVICE’, ‘TAG’, ‘TENANCY’, ‘USAGE_TYPE’]
  • group_by_tag_value (str) – TAG key in case group_by set to ‘TAG’ (i.e. Name, Project or Environment)
  • filter_by (dict) – Key of the filter and value. {‘TAG_NAME’: [‘ec2-tagname’, ‘LINKED_ACCOUNT: [‘1234’]]}

Examples

get_cost([‘machine-1’, ‘machine-2’], ‘2018-12-24’, ‘2018-12-26’, interval=’daily’) get_cost() # Get account cost

Returns:List of days or months with the requested costs
Return type:Costs (list)
__init__()[source]

This constructor configures the corresponding service according to the class that calls it.

Every time the EC2Service Class is called (inherits from this class), this constructor will change the client’s service to ‘ec2’. And then, if ELBService service is called, this method is called again changing the service from ‘ec2’ to ‘elb’.

Parameters:service (str) – AWS service to uso
Returns:None

awspice.services.ec2 module

class awspice.services.ec2.Ec2Service[source]

Bases: awspice.services.base.AwsBase

Class belonging to the EC2 Computing service.

set_tag(resource_id, tag_key, tag_value, regions=[])[source]

Set tag for an instance

Parameters:
  • elements_id (str) – Id of resources to tag. (i.e: i-01234, vol-01234)
  • tag_key (str) – Name of the element TAG (i.e: Name)
  • tag_value (str) – Value of that Tag
  • regions (lst) – Regions where to look for this element
Returns:

None

__init__()[source]

This constructor configures the corresponding service according to the class that calls it.

Every time the EC2Service Class is called (inherits from this class), this constructor will change the client’s service to ‘ec2’. And then, if ELBService service is called, this method is called again changing the service from ‘ec2’ to ‘elb’.

Parameters:service (str) – AWS service to uso
Returns:None
address_filters = {'domain': 'domain', 'instance': 'instance-id', 'privateip': 'private-ip-address', 'publicip': 'public-ip'}
ami_distributions = {'amazon': 'amzn-ami-hvm-20*.*.*-x86_64-*', 'ubuntu': 'ubuntu/images/hvm-ssd/ubuntu-*-*{version}*-amd64-server-*', 'windows': 'Windows_Server-*{version}*-English-*-Base-20*.*.*'}
ami_filters = {'architecture': 'architecture', 'id': 'image-id', 'name': 'name', 'owner': 'owner-id', 'platform': 'platform', 'public': 'is-public', 'state': 'state'}
create_instances(name, key_name, allowed_range, ami=None, distribution=None, version=None, instance_type='t2.micro', region=None, vpc=None, count=1)

Create a new instance

Parameters:
  • name (str) – TagName of the instance
  • key_name (str) – The name of the key pair (i.e: it_user)
  • allowed_range (str) – Network range with access to instance (i.e: 10.0.0.0/32)
  • ami (str) – Id of the ami (i.e: ami-12345)
  • instance_type (str) – Type of hardware of the instance (i.e: t2.medium)
  • distribution (str) – Instead of ami, select an OS: (i.e: ubuntu)
  • region (str) – Name of the region where instance will be displayed
  • vpc (str) – VPC identifier where the instance will be deployed.
  • count (int) – Number of instances to launch
Returns:

List of launched instances

Return type:

Instances (lst)

create_security_group(name, allowed_range, vpc_id=None)

Create a new Security Group

Parameters:
  • name (str) – Name of the Security Group
  • allowed_range (str) – Network range with permissions (i.e: 10.0.0.0/32)
  • vpc_id (str) – Id of assigned VPC
Returns:

Identifier of the security group created.

Return type:

str

delete_security_group(identifier)

Delete an existing Security Group

Parameters:identifier (str) – Id of the Security Group
Returns:none
distrib_amis = {'redhat': 'ami-c86c3f23', 'ubuntu': 'ami-f90a4880', 'windows': 'ami-b5530b5e'}
get_address_by(filters, regions=[])

Get IP Addresses for a region that matches with filters

Parameters:regions (lst) – Regions where to look for this element
Returns:Dictionary with the address requested
Return type:Address (dict)
get_addresses(regions=[])

Get all IP Addresses for a region

Parameters:regions (lst) – Regions where to look for this element
Returns:List of dictionaries with the addresses requested
Return type:Addresses (dict)
get_addresses_by(filters, regions=[])

Get all IP Addresses for a region

Parameters:regions (lst) – Regions where to look for this element
Returns:List of dictionaries with the addresses requested
Return type:Addresses (dict)
get_ami_by(filters, regions=[])

Get an ami for one or more regions that matches with filter

Parameters:
  • filter_key (str) – Name of the filter
  • filter_value (str) – Value of the filter
  • regions (lst) – Regions where to look for this element
Returns:

Image requested

Return type:

Image (dict)

get_amis(regions=[])

Get all images

Parameters:regions (lst) – Regions where to look for this element
Returns:List of all images
Return type:Images (lst)
get_amis_by(filters, regions=[], return_first=False)

Get list of amis for one or more regions that matches with filter

Parameters:
  • filter_key (str) – Name of the filter
  • filter_value (str) – Value of the filter
  • regions (lst) – Regions where to look for this element
  • return_first (bool) – True if return first result
Returns:

List of requested images

Return type:

Images (lst)

get_amis_by_distribution(distrib, version='*', latest=False, regions=[])

Get one or more Images filtering by distribution

Parameters:
  • distrib (str) – Distribution of the image (i.e.: ubuntu)
  • version (str) – Version of the system
  • latest (bool) – True if only returns the newest item.
  • regions (lst) – Regions where to look for this element
Returns:

List with the images requested.

Return type:

Image (lst)

get_default_vpc()

Get default Security Group

Returns:Default security group resource
Return type:SecurityGroup (dict)
get_instance_by(filters, regions=[])

Get an instance for one or more regions that matches with filter

Parameters:
  • filter_key (str) – Name of the filter
  • filter_value (str) – Value of the filter
  • regions (lst) – Regions where to look for this element
Returns:

Dictionary with the instance requested

Return type:

Instance (dict)

get_instance_status_by(filters, regions=[])
get_instances(regions=[])

Get all instances for one or more regions.

Parameters:regions (lst) – Regions where to look for this element
Returns:List of dictionaries with the instances requested
Return type:Instances (lst)
get_instances_by(filters, regions=[], return_first=False)

Get an instance for one or more regions that matches with filter

Parameters:
  • filter_key (str) – Name of the filter
  • filter_value (str) – Value of the filter
  • regions (lst) – Regions where to look for this element
  • return_first (bool) – Select to return the first match
Returns:

List of dictionaries with the instances requested

Return type:

Instances (lst)

get_instances_status(regions=[])
get_instances_status_by(filters, regions=[], return_first=False)
get_secgroup_by(filters, regions=[])

Get security group for a region that matches with filters

Parameters:
  • filter_key (str) – Name of the filter
  • filter_value (str) – Value of the filter
Returns:

Dictionaries with the security group requested

Return type:

SecurityGroup (dict)

get_secgroups(regions=[])

Get all security groups for the current region

Returns:List of dictionaries with the security groups requested
Return type:SecurityGroups (lst)
get_secgroups_by(filters, regions=[])

Get all security groups for a region that matches with filters

Parameters:
  • filter_key (str) – Name of the filter
  • filter_value (str) – Value of the filter
Returns:

List of dictionaries with the security groups requested

Return type:

SecurityGroups (lst)

get_snapshot_by(filters)

Get a snapshot for a region tha matches with filters

Parameters:
  • filter_key (str) – Name of the filter
  • filter_value (str) – Value of the filter
Returns:

Dictionary with the snapshot requested

Return type:

Snapshot (dict)

get_snapshots()

Get all snapshots owned by self for the current region

Returns:List of dictionaries with the snapshots requested
Return type:Snapshots (lst)
get_snapshots_by(filters)

Get all snapshots for the current region that matches with filters

Parameters:
  • filter_key (str) – Name of the filter
  • filter_value (str) – Value of the filter
Returns:

List of dictionaries with the snapshots requested

Return type:

Snapshots (lst)

get_volume_by(filters, regions=[])

Get a volume for one or more regions that matches with filters

Parameters:
  • filter_key (str) – Name of the filter
  • filter_value (str) – Value of the filter
  • regions (lst) – Regions where to look for this element
Returns:

Dictionary with the volume requested

Return type:

Volume (dict)

get_volumes(regions=[])

Get all volumes for one or more regions

Parameters:regions (lst) – Regions where to look for this element
Returns:List of dictionaries with the volumes requested
Return type:Volumes (lst)
get_volumes_by(filters, regions=[], return_first=False)

Get volumes for one or more regions that matches with filters

Parameters:
  • filter_key (str) – Name of the filter
  • filter_value (str) – Value of the filter
  • regions (lst) – Regions where to look for this element
Returns:

Dictionary with the volume requested

Return type:

Volume (dict)

get_vpcs(regions=[])

Get all VPCs for a region

Returns:List of dictionaries with the vpcs requested
Return type:VPCs (lst)
instance_filters = {'dnsname': 'dns-name', 'id': 'instance-id', 'name': 'tag:Name', 'privateip': 'private-ip-address', 'publicip': 'network-interface.association.public-ip', 'status': 'instance-state-name', 'tagname': 'tag:Name', 'user': 'key-name'}
instance_status_filters = {'event': 'event.code', 'instance-check': 'instance-status.status', 'status': 'instance-state-name', 'system-check': 'system-status.status'}
secgroup_filters = {'description': 'description', 'fromport': 'ip-permission.from-port', 'id': 'group-id', 'name': 'group-name', 'protocol': 'ip-permission.protocol', 'range': 'ip-permission.cidr', 'toport': 'ip-permission.to-port'}
snapshot_filters = {'id': 'snapshot-id', 'owner': 'owner-id', 'status': 'status', 'volume': 'volume-id'}
start_instances(instance_ids, regions=[])

Stops an Amazon EC2 instance

Parameters:instance_ids (lst) – List of identifiers of instances to be started.

Examples

$ aws.service.ec2.start_instances(instances=[‘i-001’]) $ aws.service.ec2.start_instances(instances=[‘i-001’, ‘i-033’], regions=[‘eu-west-1’, ‘eu-central-1’])

Returns:List of instances to be started, with their previous and current status.
Return type:lst
stop_instances(instance_ids, regions=[], force=False)

Stops an Amazon EC2 instance

Parameters:instance_ids (lst) – List of identifiers of instances to be stopped.

Examples

$ aws.service.ec2.stop_instances(instances=[‘i-001’]) $ aws.service.ec2.stop_instances(instances=[‘i-001’, ‘i-033’], regions=[‘eu-west-1’, ‘eu-central-1’])

Returns:List of instances to be stopped, with their previous and current status.
Return type:lst
volume_filters = {'autodelete': 'attachment.delete-on-termination', 'encrypted': 'encrypted', 'id': 'volume-id', 'instance': 'attachment.instance-id', 'status': 'status', 'tagname': 'tag:Name'}

awspice.services.elb module

class awspice.services.elb.ElbService[source]

Bases: awspice.services.base.AwsBase

Class belonging to the Load Balancers service.

loadbalancer_filters = {'cname': '', 'domain': '', 'tagname': ''}
get_loadbalancers(regions=[])[source]

Get all Elastic Load Balancers for a region

Parameters:regions (list) – Regions where to look for this element
Returns:List of dictionaries with the load balancers requested
Return type:LoadBalancers (list)
get_loadbalancers_by(filter_key, filter_value, regions=[])[source]

Get loadbalancers which match with the filters

Parameters:
  • filter_key (str) – [description]
  • filter_value (str) – [description]
  • regions (list, optional) – Defaults to []. List of regions to search in
Returns:

List of load balancers requested

Return type:

list

get_loadbalancer_by(filter_key, filter_value, regions=[])[source]

Get a load balancer for a region that matches with filter

Parameters:
  • filter_key (str) – Name of the filter
  • filter_value (str) – Value of the filter
  • regions (list) – Regions where to look for this element
Raises:
  • dns.resolver.NXDOMAIN – DNS Name not registered.
  • dns.resolver.NoAnswer – DNS Name not found.
Returns:

Dictionary with the load balancer requested

Return type:

LoadBalancer (dict)

__init__()[source]

This constructor configures the corresponding service according to the class that calls it.

Every time the EC2Service Class is called (inherits from this class), this constructor will change the client’s service to ‘ec2’. And then, if ELBService service is called, this method is called again changing the service from ‘ec2’ to ‘elb’.

Parameters:service (str) – AWS service to uso
Returns:None

awspice.services.iam module

class awspice.services.iam.IamService[source]

Bases: awspice.services.base.AwsBase

Class belonging to the IAM Identity & Access management service.

get_inactive_users()[source]

Get users who have not logged in AWS since 1 year. This method returns users who haven’t used their password and one of their keys in less than 9 months.

Returns:List of inactive users
Return type:list
get_users()[source]

List all users for an AWS account

Returns:List of all users
get_access_keys(user)[source]
get_access_key_last_used(accesskey)[source]
__init__()[source]

This constructor configures the corresponding service according to the class that calls it.

Every time the EC2Service Class is called (inherits from this class), this constructor will change the client’s service to ‘ec2’. And then, if ELBService service is called, this method is called again changing the service from ‘ec2’ to ‘elb’.

Parameters:service (str) – AWS service to uso
Returns:None

awspice.services.rds module

class awspice.services.rds.RdsService[source]

Bases: awspice.services.base.AwsBase

Class belonging to the Remote Database System service.

database_filters = {'cluster': 'db-cluster-id', 'id': 'db-instance-id'}
get_database_by(filters, regions=[])[source]
get_databases(regions=[])[source]

Get RDS instances in regions

Parameters:regions (list) – Regions where you want to look for
Returns:List of RDS dicts
Return type:(list)
get_snapshots(regions=[])[source]

Get RDS snapshots in regions

Parameters:regions (list) – Regions where you want to look for
Returns:List of RDS dicts
Return type:(list)
__init__()[source]

This constructor configures the corresponding service according to the class that calls it.

Every time the EC2Service Class is called (inherits from this class), this constructor will change the client’s service to ‘ec2’. And then, if ELBService service is called, this method is called again changing the service from ‘ec2’ to ‘elb’.

Parameters:service (str) – AWS service to uso
Returns:None

awspice.services.s3 module

class awspice.services.s3.S3Service[source]

Bases: awspice.services.base.AwsBase

Class belonging to the S3 Storage service.

upload_string_as_file(bucket_name, filepath, content)[source]

Upload string as a file to S3 bucket

Parameters:
  • bucket_name (str) – Name of the S3 bucket
  • filepath (str) – File path which will be created. (i.e. ‘folder1/folder2/filename.txt’)
  • content (str) – File content in string format.
Returns:

None

get_buckets()[source]

Get all buckets in S3

Returns:List of dictionaries with the buckets requested
Return type:Buckets (list)
get_bucket_acl(bucketname)[source]
get_public_buckets()[source]

Get all public buckets and its permissions

This method returns all buckets in an AWS Account which have public permissions to read, write, read acl, write acl or even full control.

Returns:List of dictionaries with the buckets requested
Return type:Buckets-ACL (list)
list_bucket_objects(bucket)[source]

List objects stored in a bucket

Parameters:bucket (str) – Name of the bucket
Returns:List of bucket objects
Return type:list
__init__()[source]

This constructor configures the corresponding service according to the class that calls it.

Every time the EC2Service Class is called (inherits from this class), this constructor will change the client’s service to ‘ec2’. And then, if ELBService service is called, this method is called again changing the service from ‘ec2’ to ‘elb’.

Parameters:service (str) – AWS service to uso
Returns:None

Module contents

class awspice.services.AwsBase(service)[source]

Bases: object

Base class from which all services inherit (ec2, s3, vpc …)

This class contains methods and properties that are common to all AWS services and should be accessible by all of them. This class is responsible for instantiating the client and processing information related to the accounts and regions.

client

Boto3 client

region

Current region used by the client

profile

Current profile used by the client

access_key

Current access key used by the client

secret_key

Current secret key used by the client

endpoints = None
region = None
profile = None
access_key = None
secret_key = None
pool = <awspice.helpers.ThreadPool object>
service_resources = ['ec2', 's3']
set_client(service)[source]

Main method to set Boto3 client

Parameters:
  • service (str) – Service to use (i.e.: ec2, s3, vpc…)
  • region (str) – Region name to use (i.e.: eu-central-1)
  • profile (str) – Profile name set in ~/.aws/credentials file
  • access_key (str) – API access key of your AWS account
  • secret_key (str) – API secret key of your AWS account
Raises:
  • ClientError – Access keys are not valid or lack of permissions for a service/region
  • ProfileNotFound – Profile name not found in credentials file
Returns:

None

classmethod set_auth_config(region, profile=None, access_key=None, secret_key=None)[source]

Set properties like service, region or auth method to be used by boto3 client

Parameters:
  • service (str) – Service to use (i.e.: ec2, s3, vpc…)
  • region (str) – Region name (i.e.: eu-central-1)
  • access_key (str) – API Access key
  • secret_key (str) – API Secret key
  • profile (str) – Profile name set in ~/.aws/credentials file
classmethod get_client_vars()[source]

Get information of the current client configuration Sometimes we need to store this variables, for example using threads, because AwsBase is constantly changing

Returns:Array with current client configuration ({‘region’: ‘eu-west-1’, ‘profile’: ‘default’})
Return type:dict
classmethod inject_client_vars(elements, client_conf=None)[source]

Insert in each item of a list, the region and the current credentials.

This function is called by all the methods of all the services that return a list of objects to identify in what region and account they have been found.

Parameters:
  • elements (list) – List of dictionaries
  • client_conf (dict) – Array with the client configuration (see get_client_vars)
Returns:

list. Returns same list with the updated elements (region and authentication included)

region_in_regions(region, regions)[source]

Check if region is in a complex list of regions

Parameters:
  • region (str | lst) – ‘eu-west-1’}
  • regions (lst) –

Examples

region_in_regions(‘eu-west-1’, [{‘RegionName’: ‘eu-west-1}])

Returns:bool
classmethod validate_filters(input_filters, accepted_filters)[source]

Transform filters into AWS filters format after validate them.

Parameters:
  • input_filters (str) – Items to validate
  • accepted_filters (list) – Pre-validated list
Returns:

None

Raises:

ValueError – Filter is not in the accepted filter list

classmethod get_profiles()[source]

Get a list of all available profiles in ~/.aws/credentials file

Returns:list. List of strings with available profiles
change_profile(profile)[source]

Change profile of the client

This method changes the account/profile used but keeps the same region and service

Parameters:profile (str) – Name of the profile set in ~/.aws/credentials file

Examples

$ aws = awspice.connect() $ aws.service.ec2.change_profile(‘my_boring_company’)

Returns:None
parse_profiles(profiles=[])[source]

Validation method which get a profile or profile list and return the expected list of them

The purpose of this method is that a user can pass different types of data as a “profile” argument and obtain a valid output for any method that works with this type of data.

Parameters:profiles (list | str) – String or list of string to parse

Examples

$ account_str = aws.service.ec2.parse_profiles(‘my_company’) $ account_lst = aws.service.ec2.parse_profiles([‘my_company’]) $ accounts_lst = aws.service.ec2.parse_profiles([‘my_company’, ‘other_company’])

Returns:list. List of a strings with profile names
get_endpoints()[source]

Get services and its regions and endpoints

Returns:Dict with services (key) and its regions and Endpoints.
Return type:dict
get_regions()[source]

Get all available regions

Returns:list. List of regions with ‘Country’ and ‘RegionName’
change_region(region)[source]

Change region of the client

This method changes the region used but keeps the same service and profile

Parameters:region (str) – Region Name (ID) of AWS (i.e.: eu-central-1)

Examples

aws.service.ec2.change_region(‘eu-west-1’)

Returns:None
parse_regions(regions=[], default_all=False)[source]

Validation method which get a region or list of regions and return the expected list of them

The purpose of this method is that a user can pass different types of data as a “region” argument and obtain a valid output for any method that works with this type of data.

Parameters:
  • regions (list | str) – String or list of string to parse
  • default_all (bool) – If the list of regions is empty and this argument is True, a list with all regions will be returned. This is useful when you do not know the data entry of type “region” and you want to search by default in all regions (if regions are empty means that the user does not know where an element is located).

Examples

AwsBase.region = aws.service.ec2.parse_regions([]) regions = aws.service.ec2.parse_regions(‘eu-west-1’) regions = aws.service.ec2.parse_regions([‘eu-west-1’]) regions = aws.service.ec2.parse_regions([‘eu-west-1’, ‘eu-west-2’])

Returns:list. List of a strings with profile names
__init__(service)[source]

This constructor configures the corresponding service according to the class that calls it.

Every time the EC2Service Class is called (inherits from this class), this constructor will change the client’s service to ‘ec2’. And then, if ELBService service is called, this method is called again changing the service from ‘ec2’ to ‘elb’.

Parameters:service (str) – AWS service to uso
Returns:None
class awspice.services.Ec2Service[source]

Bases: awspice.services.base.AwsBase

Class belonging to the EC2 Computing service.

set_tag(resource_id, tag_key, tag_value, regions=[])[source]

Set tag for an instance

Parameters:
  • elements_id (str) – Id of resources to tag. (i.e: i-01234, vol-01234)
  • tag_key (str) – Name of the element TAG (i.e: Name)
  • tag_value (str) – Value of that Tag
  • regions (lst) – Regions where to look for this element
Returns:

None

__init__()[source]

This constructor configures the corresponding service according to the class that calls it.

Every time the EC2Service Class is called (inherits from this class), this constructor will change the client’s service to ‘ec2’. And then, if ELBService service is called, this method is called again changing the service from ‘ec2’ to ‘elb’.

Parameters:service (str) – AWS service to uso
Returns:None
address_filters = {'domain': 'domain', 'instance': 'instance-id', 'privateip': 'private-ip-address', 'publicip': 'public-ip'}
ami_distributions = {'amazon': 'amzn-ami-hvm-20*.*.*-x86_64-*', 'ubuntu': 'ubuntu/images/hvm-ssd/ubuntu-*-*{version}*-amd64-server-*', 'windows': 'Windows_Server-*{version}*-English-*-Base-20*.*.*'}
ami_filters = {'architecture': 'architecture', 'id': 'image-id', 'name': 'name', 'owner': 'owner-id', 'platform': 'platform', 'public': 'is-public', 'state': 'state'}
create_instances(name, key_name, allowed_range, ami=None, distribution=None, version=None, instance_type='t2.micro', region=None, vpc=None, count=1)

Create a new instance

Parameters:
  • name (str) – TagName of the instance
  • key_name (str) – The name of the key pair (i.e: it_user)
  • allowed_range (str) – Network range with access to instance (i.e: 10.0.0.0/32)
  • ami (str) – Id of the ami (i.e: ami-12345)
  • instance_type (str) – Type of hardware of the instance (i.e: t2.medium)
  • distribution (str) – Instead of ami, select an OS: (i.e: ubuntu)
  • region (str) – Name of the region where instance will be displayed
  • vpc (str) – VPC identifier where the instance will be deployed.
  • count (int) – Number of instances to launch
Returns:

List of launched instances

Return type:

Instances (lst)

create_security_group(name, allowed_range, vpc_id=None)

Create a new Security Group

Parameters:
  • name (str) – Name of the Security Group
  • allowed_range (str) – Network range with permissions (i.e: 10.0.0.0/32)
  • vpc_id (str) – Id of assigned VPC
Returns:

Identifier of the security group created.

Return type:

str

delete_security_group(identifier)

Delete an existing Security Group

Parameters:identifier (str) – Id of the Security Group
Returns:none
distrib_amis = {'redhat': 'ami-c86c3f23', 'ubuntu': 'ami-f90a4880', 'windows': 'ami-b5530b5e'}
get_address_by(filters, regions=[])

Get IP Addresses for a region that matches with filters

Parameters:regions (lst) – Regions where to look for this element
Returns:Dictionary with the address requested
Return type:Address (dict)
get_addresses(regions=[])

Get all IP Addresses for a region

Parameters:regions (lst) – Regions where to look for this element
Returns:List of dictionaries with the addresses requested
Return type:Addresses (dict)
get_addresses_by(filters, regions=[])

Get all IP Addresses for a region

Parameters:regions (lst) – Regions where to look for this element
Returns:List of dictionaries with the addresses requested
Return type:Addresses (dict)
get_ami_by(filters, regions=[])

Get an ami for one or more regions that matches with filter

Parameters:
  • filter_key (str) – Name of the filter
  • filter_value (str) – Value of the filter
  • regions (lst) – Regions where to look for this element
Returns:

Image requested

Return type:

Image (dict)

get_amis(regions=[])

Get all images

Parameters:regions (lst) – Regions where to look for this element
Returns:List of all images
Return type:Images (lst)
get_amis_by(filters, regions=[], return_first=False)

Get list of amis for one or more regions that matches with filter

Parameters:
  • filter_key (str) – Name of the filter
  • filter_value (str) – Value of the filter
  • regions (lst) – Regions where to look for this element
  • return_first (bool) – True if return first result
Returns:

List of requested images

Return type:

Images (lst)

get_amis_by_distribution(distrib, version='*', latest=False, regions=[])

Get one or more Images filtering by distribution

Parameters:
  • distrib (str) – Distribution of the image (i.e.: ubuntu)
  • version (str) – Version of the system
  • latest (bool) – True if only returns the newest item.
  • regions (lst) – Regions where to look for this element
Returns:

List with the images requested.

Return type:

Image (lst)

get_default_vpc()

Get default Security Group

Returns:Default security group resource
Return type:SecurityGroup (dict)
get_instance_by(filters, regions=[])

Get an instance for one or more regions that matches with filter

Parameters:
  • filter_key (str) – Name of the filter
  • filter_value (str) – Value of the filter
  • regions (lst) – Regions where to look for this element
Returns:

Dictionary with the instance requested

Return type:

Instance (dict)

get_instance_status_by(filters, regions=[])
get_instances(regions=[])

Get all instances for one or more regions.

Parameters:regions (lst) – Regions where to look for this element
Returns:List of dictionaries with the instances requested
Return type:Instances (lst)
get_instances_by(filters, regions=[], return_first=False)

Get an instance for one or more regions that matches with filter

Parameters:
  • filter_key (str) – Name of the filter
  • filter_value (str) – Value of the filter
  • regions (lst) – Regions where to look for this element
  • return_first (bool) – Select to return the first match
Returns:

List of dictionaries with the instances requested

Return type:

Instances (lst)

get_instances_status(regions=[])
get_instances_status_by(filters, regions=[], return_first=False)
get_secgroup_by(filters, regions=[])

Get security group for a region that matches with filters

Parameters:
  • filter_key (str) – Name of the filter
  • filter_value (str) – Value of the filter
Returns:

Dictionaries with the security group requested

Return type:

SecurityGroup (dict)

get_secgroups(regions=[])

Get all security groups for the current region

Returns:List of dictionaries with the security groups requested
Return type:SecurityGroups (lst)
get_secgroups_by(filters, regions=[])

Get all security groups for a region that matches with filters

Parameters:
  • filter_key (str) – Name of the filter
  • filter_value (str) – Value of the filter
Returns:

List of dictionaries with the security groups requested

Return type:

SecurityGroups (lst)

get_snapshot_by(filters)

Get a snapshot for a region tha matches with filters

Parameters:
  • filter_key (str) – Name of the filter
  • filter_value (str) – Value of the filter
Returns:

Dictionary with the snapshot requested

Return type:

Snapshot (dict)

get_snapshots()

Get all snapshots owned by self for the current region

Returns:List of dictionaries with the snapshots requested
Return type:Snapshots (lst)
get_snapshots_by(filters)

Get all snapshots for the current region that matches with filters

Parameters:
  • filter_key (str) – Name of the filter
  • filter_value (str) – Value of the filter
Returns:

List of dictionaries with the snapshots requested

Return type:

Snapshots (lst)

get_volume_by(filters, regions=[])

Get a volume for one or more regions that matches with filters

Parameters:
  • filter_key (str) – Name of the filter
  • filter_value (str) – Value of the filter
  • regions (lst) – Regions where to look for this element
Returns:

Dictionary with the volume requested

Return type:

Volume (dict)

get_volumes(regions=[])

Get all volumes for one or more regions

Parameters:regions (lst) – Regions where to look for this element
Returns:List of dictionaries with the volumes requested
Return type:Volumes (lst)
get_volumes_by(filters, regions=[], return_first=False)

Get volumes for one or more regions that matches with filters

Parameters:
  • filter_key (str) – Name of the filter
  • filter_value (str) – Value of the filter
  • regions (lst) – Regions where to look for this element
Returns:

Dictionary with the volume requested

Return type:

Volume (dict)

get_vpcs(regions=[])

Get all VPCs for a region

Returns:List of dictionaries with the vpcs requested
Return type:VPCs (lst)
instance_filters = {'dnsname': 'dns-name', 'id': 'instance-id', 'name': 'tag:Name', 'privateip': 'private-ip-address', 'publicip': 'network-interface.association.public-ip', 'status': 'instance-state-name', 'tagname': 'tag:Name', 'user': 'key-name'}
instance_status_filters = {'event': 'event.code', 'instance-check': 'instance-status.status', 'status': 'instance-state-name', 'system-check': 'system-status.status'}
secgroup_filters = {'description': 'description', 'fromport': 'ip-permission.from-port', 'id': 'group-id', 'name': 'group-name', 'protocol': 'ip-permission.protocol', 'range': 'ip-permission.cidr', 'toport': 'ip-permission.to-port'}
snapshot_filters = {'id': 'snapshot-id', 'owner': 'owner-id', 'status': 'status', 'volume': 'volume-id'}
start_instances(instance_ids, regions=[])

Stops an Amazon EC2 instance

Parameters:instance_ids (lst) – List of identifiers of instances to be started.

Examples

$ aws.service.ec2.start_instances(instances=[‘i-001’]) $ aws.service.ec2.start_instances(instances=[‘i-001’, ‘i-033’], regions=[‘eu-west-1’, ‘eu-central-1’])

Returns:List of instances to be started, with their previous and current status.
Return type:lst
stop_instances(instance_ids, regions=[], force=False)

Stops an Amazon EC2 instance

Parameters:instance_ids (lst) – List of identifiers of instances to be stopped.

Examples

$ aws.service.ec2.stop_instances(instances=[‘i-001’]) $ aws.service.ec2.stop_instances(instances=[‘i-001’, ‘i-033’], regions=[‘eu-west-1’, ‘eu-central-1’])

Returns:List of instances to be stopped, with their previous and current status.
Return type:lst
volume_filters = {'autodelete': 'attachment.delete-on-termination', 'encrypted': 'encrypted', 'id': 'volume-id', 'instance': 'attachment.instance-id', 'status': 'status', 'tagname': 'tag:Name'}
class awspice.services.ElbService[source]

Bases: awspice.services.base.AwsBase

Class belonging to the Load Balancers service.

loadbalancer_filters = {'cname': '', 'domain': '', 'tagname': ''}
get_loadbalancers(regions=[])[source]

Get all Elastic Load Balancers for a region

Parameters:regions (list) – Regions where to look for this element
Returns:List of dictionaries with the load balancers requested
Return type:LoadBalancers (list)
get_loadbalancers_by(filter_key, filter_value, regions=[])[source]

Get loadbalancers which match with the filters

Parameters:
  • filter_key (str) – [description]
  • filter_value (str) – [description]
  • regions (list, optional) – Defaults to []. List of regions to search in
Returns:

List of load balancers requested

Return type:

list

get_loadbalancer_by(filter_key, filter_value, regions=[])[source]

Get a load balancer for a region that matches with filter

Parameters:
  • filter_key (str) – Name of the filter
  • filter_value (str) – Value of the filter
  • regions (list) – Regions where to look for this element
Raises:
  • dns.resolver.NXDOMAIN – DNS Name not registered.
  • dns.resolver.NoAnswer – DNS Name not found.
Returns:

Dictionary with the load balancer requested

Return type:

LoadBalancer (dict)

__init__()[source]

This constructor configures the corresponding service according to the class that calls it.

Every time the EC2Service Class is called (inherits from this class), this constructor will change the client’s service to ‘ec2’. And then, if ELBService service is called, this method is called again changing the service from ‘ec2’ to ‘elb’.

Parameters:service (str) – AWS service to uso
Returns:None
class awspice.services.IamService[source]

Bases: awspice.services.base.AwsBase

Class belonging to the IAM Identity & Access management service.

get_inactive_users()[source]

Get users who have not logged in AWS since 1 year. This method returns users who haven’t used their password and one of their keys in less than 9 months.

Returns:List of inactive users
Return type:list
get_users()[source]

List all users for an AWS account

Returns:List of all users
get_access_keys(user)[source]
get_access_key_last_used(accesskey)[source]
__init__()[source]

This constructor configures the corresponding service according to the class that calls it.

Every time the EC2Service Class is called (inherits from this class), this constructor will change the client’s service to ‘ec2’. And then, if ELBService service is called, this method is called again changing the service from ‘ec2’ to ‘elb’.

Parameters:service (str) – AWS service to uso
Returns:None
class awspice.services.RdsService[source]

Bases: awspice.services.base.AwsBase

Class belonging to the Remote Database System service.

database_filters = {'cluster': 'db-cluster-id', 'id': 'db-instance-id'}
get_database_by(filters, regions=[])[source]
get_databases(regions=[])[source]

Get RDS instances in regions

Parameters:regions (list) – Regions where you want to look for
Returns:List of RDS dicts
Return type:(list)
get_snapshots(regions=[])[source]

Get RDS snapshots in regions

Parameters:regions (list) – Regions where you want to look for
Returns:List of RDS dicts
Return type:(list)
__init__()[source]

This constructor configures the corresponding service according to the class that calls it.

Every time the EC2Service Class is called (inherits from this class), this constructor will change the client’s service to ‘ec2’. And then, if ELBService service is called, this method is called again changing the service from ‘ec2’ to ‘elb’.

Parameters:service (str) – AWS service to uso
Returns:None
class awspice.services.S3Service[source]

Bases: awspice.services.base.AwsBase

Class belonging to the S3 Storage service.

upload_string_as_file(bucket_name, filepath, content)[source]

Upload string as a file to S3 bucket

Parameters:
  • bucket_name (str) – Name of the S3 bucket
  • filepath (str) – File path which will be created. (i.e. ‘folder1/folder2/filename.txt’)
  • content (str) – File content in string format.
Returns:

None

get_buckets()[source]

Get all buckets in S3

Returns:List of dictionaries with the buckets requested
Return type:Buckets (list)
get_bucket_acl(bucketname)[source]
get_public_buckets()[source]

Get all public buckets and its permissions

This method returns all buckets in an AWS Account which have public permissions to read, write, read acl, write acl or even full control.

Returns:List of dictionaries with the buckets requested
Return type:Buckets-ACL (list)
list_bucket_objects(bucket)[source]

List objects stored in a bucket

Parameters:bucket (str) – Name of the bucket
Returns:List of bucket objects
Return type:list
__init__()[source]

This constructor configures the corresponding service according to the class that calls it.

Every time the EC2Service Class is called (inherits from this class), this constructor will change the client’s service to ‘ec2’. And then, if ELBService service is called, this method is called again changing the service from ‘ec2’ to ‘elb’.

Parameters:service (str) – AWS service to uso
Returns:None
class awspice.services.AcmService[source]

Bases: awspice.services.base.AwsBase

Class belonging to the ACM certificate management service.

list_certificates(regions=[])[source]

List all certificates

Parameters:regions (lst) – List of regions to list certificates
Returns:List of certificates
get_certificate_by(filter_key, filter_value, regions=[])[source]

Get certificate filtering by domain

Parameters:
  • filter_key (str) – Name of the field to be searched. (Domain)
  • filter_value (str) – Value for the previous field. (i.e.: google.es)
  • regions (lst) – List of regions where the certificate can be.
Returns:

Certificate matched to the filter entered.

get_certificate(arn, regions=[])[source]

Get certificate using CertificateArn (Ceritificate Identifier)

Parameters:
  • arn (str) – ARN of the certificate
  • regions (lst) – List of regions where the certificate can be.
Returns:

Certificate matched to the ARN entered.

__init__()[source]

This constructor configures the corresponding service according to the class that calls it.

Every time the EC2Service Class is called (inherits from this class), this constructor will change the client’s service to ‘ec2’. And then, if ELBService service is called, this method is called again changing the service from ‘ec2’ to ‘elb’.

Parameters:service (str) – AWS service to uso
Returns:None
class awspice.services.CostExplorerService[source]

Bases: awspice.services.base.AwsBase

Class belonging to the Cost Explorer service.

granularities = ['DAILY', 'MONTHLY']
filter_dimensions = ['AZ', 'INSTANCE_TYPE', 'LINKED_ACCOUNT', 'OPERATION', 'PURCHASE_TYPE', 'REGION', 'SERVICE', 'USAGE_TYPE', 'USAGE_TYPE_GROUP', 'RECORD_TYPE', 'OPERATING_SYSTEM', 'TENANCY', 'SCOPE', 'PLATFORM', 'SUBSCRIPTION_ID', 'LEGAL_ENTITY_NAME', 'DEPLOYMENT_OPTION', 'DATABASE_ENGINE', 'CACHE_ENGINE', 'INSTANCE_TYPE_FAMILY']
group_dimensions = ['AZ', 'INSTANCE_TYPE', 'LEGAL_ENTITY_NAME', 'LINKED_ACCOUNT', 'OPERATION', 'PLATFORM', 'PURCHASE_TYPE', 'SERVICE', 'TAG', 'TENANCY', 'USAGE_TYPE']
get_cost(from_date=None, to_date=None, interval='Monthly', group_by='', group_by_tag_value='', filter_by={}, ec2_running_hours=False)[source]

Get the cost of account or its elements.

This method obtains costs of an account/s , one or several elements (substances, balancers, addresses) between two dates and granularized in days or months. If the date is not indicated, the cost of the last month will be returned.

Parameters:
  • from_date (str) – Date from which you want to obtain data. (Format: 2018-04-24)
  • to_date (str) – Date until which you want to obtain data. (Format: 2018-04-24)
  • interval (str) – Time interval to be analyzed. [ MONTHLY | DAILY ]
  • group_by (str) – Group results by [‘AZ’, ‘INSTANCE_TYPE’, ‘LEGAL_ENTITY_NAME’, ‘LINKED_ACCOUNT’, ‘OPERATION’, ‘PLATFORM’, ‘PURCHASE_TYPE’, ‘SERVICE’, ‘TAG’, ‘TENANCY’, ‘USAGE_TYPE’]
  • group_by_tag_value (str) – TAG key in case group_by set to ‘TAG’ (i.e. Name, Project or Environment)
  • filter_by (dict) – Key of the filter and value. {‘TAG_NAME’: [‘ec2-tagname’, ‘LINKED_ACCOUNT: [‘1234’]]}

Examples

get_cost([‘machine-1’, ‘machine-2’], ‘2018-12-24’, ‘2018-12-26’, interval=’daily’) get_cost() # Get account cost

Returns:List of days or months with the requested costs
Return type:Costs (list)
__init__()[source]

This constructor configures the corresponding service according to the class that calls it.

Every time the EC2Service Class is called (inherits from this class), this constructor will change the client’s service to ‘ec2’. And then, if ELBService service is called, this method is called again changing the service from ‘ec2’ to ‘elb’.

Parameters:service (str) – AWS service to uso
Returns:None
class awspice.services.Route53Service[source]

Bases: awspice.services.base.AwsBase

Class belonging to the Route 53 DNS Service

get_domains()[source]

Get hosted zones and its records

Returns:List of Hosted Zones with Records
Return type:(lst)
list_hosted_zones()[source]

List all hosted zones

Returns:List of hosted zones
list_records(hosted_zone_id)[source]

List all records for a hosted zone

Parameters:zone (hosted) – The ID of the hosted zone that contains the resource record sets that you want to list
Returns:List of DNS records
list_records_by_domain(domain)[source]

List all records of a hosted-zone domain

Parameters:domain (str) – The DOMAIN name of the hosted zone that contains the resource record sets that you want to list
Returns:List of DNS records
__init__()[source]

This constructor configures the corresponding service according to the class that calls it.

Every time the EC2Service Class is called (inherits from this class), this constructor will change the client’s service to ‘ec2’. And then, if ELBService service is called, this method is called again changing the service from ‘ec2’ to ‘elb’.

Parameters:service (str) – AWS service to uso
Returns:None