Esempio n. 1
0
def get_instance_by_id(ec2,
                       instance_id,
                       fail_nonexisting_id=False,
                       fail_terminated=False):
    instance = ec2.Instance(instance_id)
    try:
        instance.load()
    except boto.ClientError as e:
        if (fail_nonexisting_id
                and 'InvalidInstanceID' in e.response['Error']['Code']):
            # InvalidInstanceID.Malformed
            # InvalidInstanceID.NotFound
            raise errors.ObjectDoesNotExist(
                'Instance with id {0} does not exist'.format(instance_id))
        return None
    # We may have successfully retrieved a terminated instance.
    # We treat terminated instances as not present anymore, but again give
    # the caller a choice on how to proceed.
    if instance.state['Name'] == 'terminated':
        # Optionally fail for callers that need non-terminated instances
        if fail_terminated:
            raise errors.UnexpectedStateError(
                "Instance with id {0} is terminated".format(instance_id))
        return None

    return instance
def validate_security_group(ec2, secgroup_id, vpc_id):
    if not security_group_exists(ec2, secgroup_id):
        raise errors.ObjectDoesNotExist(
            "Security group does not exist: {0}".format(secgroup_id))

    if not security_group_in_vpc(ec2, secgroup_id, vpc_id):
        raise errors.ValidationError(
            "Security group {0} is not in VPC {1}.".format(
                secgroup_id, vpc_id))
Esempio n. 3
0
def validate_instance_type_reference(ec2, instance_type):
    try:
        ec2.meta.client.describe_instance_types(InstanceTypes=[instance_type
                                                               ], )
    except boto.ClientError as e:
        if e.response['Error']['Code'] == 'InvalidInstanceType':
            raise errors.ObjectDoesNotExist(
                'Instance type {0} does not exist in your region'.format(
                    instance_type))
        raise
Esempio n. 4
0
def validate_az_id(ec2, availability_zone_id):
    try:
        ec2.meta.client.describe_availability_zones(
            ZoneIds=[availability_zone_id])
    except boto.ClientError as e:
        code = e.response["Error"]["Code"]
        if code in ("InvalidAvailabilityZone", "InvalidParameterValue"):
            raise errors.ObjectDoesNotExist(
                "Availability zone with id {0} does not "
                "exist in your region".format(availability_zone_id))
        raise
Esempio n. 5
0
def _identify_vpc(ec2, params, fail_nonexisting_id=False):
    if params["id"]:
        vpc = ec2_vpc_utils.get_vpc_by_id(ec2, params["id"],
                                          fail_nonexisting_id)
        # currently we do not fallback to (name, cidr) identification
        # if identification by ID fails.
        if not vpc and fail_nonexisting_id:
            raise errors.ObjectDoesNotExist(
                "VPC with id {0} does not exist".format(params["id"]))
        return vpc
    return _get_vpc_by_primary_cidr_and_name(ec2, params["name"],
                                             params["cidr"])
Esempio n. 6
0
def validate_security_group_references(ec2, security_groups, vpc_id):
    groups = ec2.security_groups.filter(
        Filters=ec2_filters.from_dict({
            'group-id': security_groups,
            'vpc-id': vpc_id,
        }))
    present_groups = {group.id for group in groups}
    invalid_refs = set(security_groups) - present_groups
    if invalid_refs:
        raise errors.ObjectDoesNotExist(
            "Security groups ({0}) do not exist in {1}".format(
                ", ".join(sorted(invalid_refs)), vpc_id))
Esempio n. 7
0
def validate_ami_reference(ec2, ami_id):
    ami = ec2.Image(ami_id)
    try:
        ami.load()
    except boto.ClientError as e:
        if 'InvalidAMIID' in e.response['Error']['Code']:
            # InvalidAMIID.Malformed
            # InvalidAMIID.NotFound
            # InvalidAMIID.Unavailable
            raise errors.ObjectDoesNotExist(
                'AMI with id {0} does not exist in your region'.format(ami_id))
        raise
Esempio n. 8
0
def get_subnet_by_id(ec2, subnet_id, fail_nonexisting_id=False):
    subnet = ec2.Subnet(subnet_id)
    if subnet not in ec2.subnets.filter(
            Filters=ec2_filters.from_dict({
                'subnet-id': subnet_id,
            })):
        if fail_nonexisting_id:
            raise errors.ObjectDoesNotExist(
                'Subnet with id {0} does not exist'.format(subnet_id))
        return None

    subnet.load()

    return subnet
Esempio n. 9
0
def get_network_interface_by_id(ec2, eni_id, fail_nonexisting_id=False):
    eni = ec2.NetworkInterface(eni_id)
    try:
        eni.load()
    except boto.ClientError as e:
        if e.response["Error"]["Code"] in (
                "InvalidNetworkInterfaceId.Malformed",
                "InvalidNetworkInterfaceID.NotFound"):
            if fail_nonexisting_id:
                raise errors.ObjectDoesNotExist(
                    "A network interface with id {0} does not exist".format(
                        eni_id))
            return None
        raise
    return eni
def get_internet_gateway_by_id(ec2, gateway_id, fail_nonexisting_id=False):
    gateway = ec2.InternetGateway(gateway_id)
    if gateway not in ec2.internet_gateways.filter(
            Filters=ec2_filters.from_dict({
                'internet-gateway-id': gateway_id,
            })):
        if fail_nonexisting_id:
            raise errors.ObjectDoesNotExist(
                'Internet gateway with id {0} does not exist.'.format(
                    gateway_id))
        return None

    gateway.load()

    return gateway
Esempio n. 11
0
def get_vpc_by_id(ec2, vpc_id, fail_nonexisting_id=False):
    """
    Retrieves a VPC with an ID of vpc_id or optionally fails when it does not exist.

    :raises errors.ObjectDoesNotExist: when a VPC with id vpc_id does not exist.
    """
    vpc = ec2.Vpc(vpc_id)
    try:
        vpc.load()
    except boto.ClientError as e:
        if e.response['Error']['Code'] == 'InvalidVpcID.NotFound':
            if fail_nonexisting_id:
                raise errors.ObjectDoesNotExist(
                    'VPC with id {0} does not exist'.format(vpc_id))
            return None
        raise
    return vpc
Esempio n. 12
0
def get_default_vpc(ec2):
    """
    Retrieves the default VPC.

    :raises errors.ObjectDoesNotExist: when the default VPC does not exist.
    """
    vpc_collection = ec2.vpcs.filter(
        Filters=ec2_filters.from_dict(dict(isDefault='true', )))
    vpcs = list(vpc_collection)
    if not vpcs:  # we don't have a default VPC
        raise errors.ObjectDoesNotExist(
            "Default VPC does not exist. Create one or pass "
            "the VPC id via 'vpc' parameter.")
    # we cannot have more than one default VPC per region
    vpc = vpcs[0]
    vpc.load()

    return vpc
Esempio n. 13
0
def get_default_subnet_for_az(ec2, availability_zone_id):
    subnet_collection = ec2.subnets.filter(
        Filters=ec2_filters.from_dict({
            'availability-zone-id': availability_zone_id,
            'default-for-az': 'true',
        }))
    subnets = list(subnet_collection)

    if not subnets:
        raise errors.ObjectDoesNotExist(
            'Availability zone with id {0} does not'
            ' have a default subnet'.format(availability_zone_id))

    # there can't be more than 1 default subnet per AZ
    subnet = subnets[0]
    subnet.load()

    return subnet
def _get_or_create(ec2, module_params, check_mode):
    vpc_id = module_params["vpc"]
    changed = False
    if module_params["id"]:
        sg = _get_existing_secgroup_by_id(ec2, module_params["id"])
        if sg is None:
            raise errors.ObjectDoesNotExist(
                "The security group with id '{0}' does not exist.".format(
                    module_params["id"]))
    else:
        # for non-id identification or not-found creation, we default to the default vpc
        if vpc_id is None:
            default_vpc = ec2_vpc_utils.get_default_vpc(ec2)
            vpc_id = default_vpc.id

        sg = _get_existing_secgroup_by_name_and_vpc(ec2, module_params["name"],
                                                    vpc_id)
        if sg is None:
            changed = True

            if module_params["description"] is None:
                raise errors.ValidationError("When creating a security group, "
                                             "a description is required.")

            if check_mode:
                # we stop here, because we don't want to simulate all operations
                # on a virtual security group if we know the result already
                return changed, dict(GroupId="generated-by-aws",
                                     VpcId=vpc_id,
                                     GroupName=module_params["name"],
                                     Description=module_params["description"],
                                     Tags=[],
                                     IpPermissions=[],
                                     IpPermissionsEgress=[
                                         SimpleSecurityGroupRule.
                                         default_egress().to_boto_dict()
                                     ])
            sg = ec2.create_security_group(
                VpcId=vpc_id,
                GroupName=module_params["name"],
                Description=module_params["description"])
            waiter = ec2.meta.client.get_waiter("security_group_exists")
            waiter.wait(GroupIds=[sg.id])
    return changed, sg