def disassociate_elasticip(**_):
    """ Disassocates an Elastic IP created by Cloudify from an EC2 Instance
    that was also created by Cloudify.
    """
    ec2_client = connection.EC2ConnectionClient().client()

    elasticip = \
        utils.get_external_resource_id_or_raise(
                'disassociate elasticip', ctx.target.instance)

    elasticip_object = _get_address_object_by_id(elasticip)

    if not elasticip_object:
        raise NonRecoverableError(
                'no matching elastic ip in account: {0}'.format(elasticip))

    disassociate_args = dict(
            public_ip=elasticip_object.public_ip,
            association_id=elasticip_object.association_id
    )

    ctx.logger.debug('Disassociating Elastic IP {0}'.format(elasticip))

    try:
        ec2_client.disassociate_address(**disassociate_args)
    except (boto.exception.EC2ResponseError,
            boto.exception.BotoServerError) as e:
        raise NonRecoverableError('{0}'.format(str(e)))

    utils.unassign_runtime_property_from_resource(
            'public_ip_address', ctx.source.instance)
    utils.unassign_runtime_property_from_resource(
            'instance_id', ctx.target.instance)
    def test_get_address_object_by_id(self):

        ctx = self.mock_relationship_context('test_get_address_object_by_id')
        current_ctx.set(ctx=ctx)

        client = self._get_ec2_client()
        address = client.allocate_address()
        address_object = \
            elasticip._get_address_object_by_id(address.public_ip)
        self.addCleanup(address_object.delete)
        self.assertEqual(address.public_ip, address_object.public_ip)
    def test_get_address_object_by_id(self):

        ctx = self.mock_relationship_context(
            'test_get_address_object_by_id')
        current_ctx.set(ctx=ctx)

        client = self._get_ec2_client()
        address = client.allocate_address()
        address_object = \
            elasticip._get_address_object_by_id(address.public_ip)
        self.addCleanup(address_object.delete)
        self.assertEqual(
            address.public_ip, address_object.public_ip)