Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def test_igw_attach_twice():
""" internet gateway fail to attach twice """
conn = boto.connect_vpc("the_key", "the_secret")
igw = conn.create_internet_gateway()
vpc1 = conn.create_vpc(VPC_CIDR)
vpc2 = conn.create_vpc(VPC_CIDR)
conn.attach_internet_gateway(igw.id, vpc1.id)
with assert_raises(EC2ResponseError) as cm:
conn.attach_internet_gateway(igw.id, vpc2.id)
cm.exception.code.should.equal("Resource.AlreadyAssociated")
cm.exception.status.should.equal(400)
cm.exception.request_id.should_not.be.none
def test_cancel_spot_instance_request():
conn = boto.connect_ec2()
conn.request_spot_instances(price=0.5, image_id="ami-abcd1234")
requests = conn.get_all_spot_instance_requests()
requests.should.have.length_of(1)
with assert_raises(EC2ResponseError) as ex:
conn.cancel_spot_instance_requests([requests[0].id], dry_run=True)
ex.exception.error_code.should.equal("DryRunOperation")
ex.exception.status.should.equal(400)
ex.exception.message.should.equal(
"An error occurred (DryRunOperation) when calling the CancelSpotInstance operation: Request would have succeeded, but DryRun flag is set"
)
conn.cancel_spot_instance_requests([requests[0].id])
requests = conn.get_all_spot_instance_requests()
requests.should.have.length_of(0)
def test_ami_create_and_delete():
conn = boto.connect_ec2("the_key", "the_secret")
initial_ami_count = len(AMIS)
conn.get_all_volumes().should.have.length_of(0)
conn.get_all_snapshots().should.have.length_of(initial_ami_count)
reservation = conn.run_instances("ami-1234abcd")
instance = reservation.instances[0]
with assert_raises(EC2ResponseError) as ex:
image_id = conn.create_image(
instance.id, "test-ami", "this is a test ami", dry_run=True
)
ex.exception.error_code.should.equal("DryRunOperation")
ex.exception.status.should.equal(400)
ex.exception.message.should.equal(
"An error occurred (DryRunOperation) when calling the CreateImage operation: Request would have succeeded, but DryRun flag is set"
)
image_id = conn.create_image(instance.id, "test-ami", "this is a test ami")
all_images = conn.get_all_images()
set([i.id for i in all_images]).should.contain(image_id)
retrieved_image = [i for i in all_images if i.id == image_id][0]
def prepare_delete_exception(self, error_code):
baz_interface = self.make_interface(['bar-id'])
e = EC2ResponseError('status', 'reason')
e.error_code = error_code
baz_interface.delete.side_effect = e
return baz_interface
security_groups=[security_group]
)
else:
reservation = self.conn.run_instances(
EC2Services.supported_ec2_regions[self.region],
key_name=key_pair,
instance_type='t1.micro',
security_groups=[security_group]
)
instance = reservation.instances[0]
else:
print "Launching EC2 instance from instance ID '{0}'. This may take a moment...".format(instance_id)
try:
instance = self.retrieve_ec2_instance(instance_id)
instance.start()
except boto.exception.EC2ResponseError:
print "Invalid instance ID. Are you sure you entered it in correctly?"
exit(-1)
# Make sure its actually running before we return
instance.update()
while instance.state != 'running':
time.sleep(5)
instance.update()
# Dont forget to add the alarm
self.make_instance_sleepy(instance.id)
return instance
def _credentials_expired(self, response):
if response.status != 400:
return False
error = EC2ResponseError('', '', body=response.read())
if error.errors is not None:
for code, message in error.errors:
if code == 'RequestExpired':
return True
return False
r['error'] = {'message': 'ID not found for this network interface.'}
return r
if instance_name:
try:
instance_id = get_id(name=instance_name, region=region, key=key,
keyid=keyid, profile=profile)
except boto.exception.BotoServerError as e:
log.error(e)
return False
try:
r['result'] = conn.attach_network_interface(
network_interface_id, instance_id, device_index
)
except boto.exception.EC2ResponseError as e:
r['error'] = __utils__['boto.get_error'](e)
return r
def _update(self):
try:
self._instance.update()
except EC2ResponseError, ecex:
# We allow this error to occur once. It takes ec2 some time
# to be sure of the instance id
if self._poll_error_count > self._max_id_error_count:
# if we poll too quick sometimes aws cannot find the id
cloudinitd.log(self._log, logging.ERROR, "safety error count exceeded" + str(ecex), tb=traceback)
raise
self._poll_error_count = self._poll_error_count + 1
changed = False
instance_dict_array = []
if not isinstance(instance_ids, list) or len(instance_ids) < 1:
module.fail_json(msg='instance_ids should be a list of instances, aborting')
terminated_instance_ids = []
for res in ec2.get_all_instances(instance_ids):
for inst in res.instances:
if inst.state == 'running' or inst.state == 'stopped':
terminated_instance_ids.append(inst.id)
instance_dict_array.append(get_instance_info(inst))
try:
ec2.terminate_instances([inst.id])
except EC2ResponseError, e:
module.fail_json(msg='Unable to terminate instance {0}, error: {1}'.format(inst.id, e))
changed = True
# wait here until the instances are 'terminated'
if wait:
num_terminated = 0
wait_timeout = time.time() + wait_timeout
while wait_timeout > time.time() and num_terminated < len(terminated_instance_ids):
response = ec2.get_all_instances( \
instance_ids=terminated_instance_ids, \
filters={'instance-state-name':'terminated'})
try:
num_terminated = len(response.pop().instances)
except Exception, e:
# got a bad response of some sort, possibly due to
# stale/cached data. Wait a second and then try again
def stopinstance(instanceid):
try:
conn.stop_instances(instance_ids=[instanceid])
except EC2ResponseError,e:
print e
return "error"