Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
"Fn::If": [
"EnvEqualsPrd",
"ami-00000000",
"ami-ffffffff"
]
},
},
"Type": "AWS::EC2::Instance"
},
}
}
dummy_template_json = json.dumps(dummy_template)
conn = boto.cloudformation.connect_to_region("us-west-1")
conn.create_stack('test_stack1', template_body=dummy_template_json)
ec2_conn = boto.ec2.connect_to_region("us-west-1")
reservation = ec2_conn.get_all_instances()[0]
ec2_instance = reservation.instances[0]
ec2_instance.image_id.should.equal("ami-ffffffff")
ec2_instance.terminate()
conn = boto.cloudformation.connect_to_region("us-west-2")
conn.create_stack(
'test_stack1', template_body=dummy_template_json, parameters=[("ENV", "prd")])
ec2_conn = boto.ec2.connect_to_region("us-west-2")
reservation = ec2_conn.get_all_instances()[0]
ec2_instance = reservation.instances[0]
ec2_instance.image_id.should.equal("ami-00000000")
eventType = message_attrs['Event']
except KeyError:
log.warn("Unable to read message. Deleting.")
q.delete_message(result)
break
log.info("eventType=%s" % eventType)
if eventType == 'autoscaling:TEST_NOTIFICATION':
q.delete_message(result)
if eventType != 'autoscaling:TEST_NOTIFICATION':
instanceId = message_attrs['EC2InstanceId']
log.info("instanceId=%s" % instanceId)
if eventType == 'cfncluster:COMPUTE_READY':
ec2 = boto.connect_ec2()
ec2 = boto.ec2.connect_to_region(region,proxy=boto.config.get('Boto', 'proxy'),
proxy_port=boto.config.get('Boto', 'proxy_port'))
retry = 0
wait = 15
while retry < 3:
try:
hostname = ec2.get_all_instances(instance_ids=instanceId)
if not hostname:
log.warning("Unable to find running instance %s." % instanceId)
else:
log.info("Adding Hostname: %s" % hostname)
hostname = hostname[0].instances[0].private_dns_name.split('.')[:1][0]
s.addHost(hostname,cluster_user)
t.put_item(data={
def get_instances_by_region(self, region):
''' Makes an AWS EC2 API call to the list of instances in a particular
region '''
try:
if self.eucalyptus:
conn = boto.connect_euca(host=self.eucalyptus_host)
conn.APIVersion = '2010-08-31'
else:
conn = ec2.connect_to_region(region)
# connect_to_region will fail "silently" by returning None if the region name is wrong or not supported
if conn is None:
print("region name: %s likely not supported, or AWS is down. connection to region failed." % region)
sys.exit(1)
reservations = []
if self.ec2_instance_filters:
for filter_key, filter_values in self.ec2_instance_filters.iteritems():
reservations.extend(conn.get_all_instances(filters = { filter_key : filter_values }))
else:
reservations = conn.get_all_instances()
for reservation in reservations:
for instance in reservation.instances:
self.add_instance(instance, region)
def ec2_get_image(accesskey, secretkey,imgname, zone):
EC2_IMAGE_TO_AMI = {
"ubuntu" : "ami-ad184ac4",
"debian" : "ami-3428ba5d",
"suse" : "ami-e8084981",
"redhat" : "ami-a25415cb",
"centos" : "ami-07b73c6e",
"windows" : "ami-7527031c",
}
imgos = ec2_get_os(imgname)
conn = boto.ec2.connect_to_region(zone,aws_access_key_id=accesskey,aws_secret_access_key=secretkey)
image = conn.get_all_images(filters={'name' : imgname})
if (image):
if (image[0]):
imagestr = str(image[0]).split(":")
ec2imageid = imagestr[1]
return ec2imageid
else:
images = conn.get_all_images()
for myimage in images:
if(myimage.name):
if imgname in myimage.name:
imagestr = str(myimage).split(":")
ec2imageid = imagestr[1]
return ec2imageid
if(EC2_IMAGE_TO_AMI.has_key(imgos)):
return EC2_IMAGE_TO_AMI[imgos]
"""
Hosts generator for running a task on all instances matching `*args` and `**kwargs`
`*args` and `**kwargs` are passed-through to the underlying boto.ec2.get_all_instances() function
:param region: AWS region
:type region: str
:param hostname_attribute: `boto.ec2.instance.Instance` attribute to use as hostname for fabric connection
:type hostname_attribute: str
:param *args: pass-through arguments to the underlying boto.ec2.get_all_instances() function
:param *kwargs: pass-through keyword arguments to the underlying boto.ec2.get_all_instances() function
:return: Generates a list of hosts
:rtype: list[str]
"""
hostname_attribute = kwargs.pop('hostname_attribute', 'public_dns_name')
ec2_connection = boto.ec2.connect_to_region(region)
reservations = ec2_connection.get_all_instances(*args, **kwargs)
hosts = [getattr(instance, hostname_attribute)
for reservation in reservations
for instance in reservation.instances]
# this will make our function lazy
for host in hosts:
yield host
# Pull all the egress destinations attached to an egress rule
from MaltegoTransform import *
import boto.ec2
import sys
from init import load_credentials
creds = load_credentials()
REGION = creds[2]
m = MaltegoTransform()
m.parseArguments(sys.argv)
egress_dst = m.getVar("GroupID")
try:
conn = boto.ec2.connect_to_region(REGION, aws_access_key_id=creds[0], aws_secret_access_key=creds[1])
reservations = conn.get_all_instances()
for i in reservations:
group_nums = len(i.instances[0].groups)
for z in range(group_nums):
group_id = i.instances[0].groups[z].id
if str(group_id) == str(egress_dst):
egress_rules = conn.get_all_security_groups(group_ids=group_id)[0].rules_egress
number_of_egress = len(egress_rules)
for g in range(number_of_egress):
ent = m.addEntity('matterasmus.AmazonEC2IngressSource', str(conn.get_all_security_groups(group_ids=group_id)[0].rules[g].grants))
ent.addAdditionalFields("Source", "Source", "strict", str(conn.get_all_security_groups(group_ids=group_id)[0].rules[g].grants))
ent.addAdditionalFields("GroupID", "Group ID", "strict", str(group_id))
m.addUIMessage("Completed.")
def stop_instances(location, placement_group='*'):
ec2 = boto.ec2.connect_to_region(location)
instances = ec2.get_only_instances(
filters={"placement-group-name":placement_group})
for inst in instances:
ec2.stop_instances(instance_ids=[inst.id])
def _create_ec2_instance():
"""
Creates EC2 Instance
"""
print(_yellow("Creating instance"))
conn = boto.ec2.connect_to_region(ec2_region, aws_access_key_id=fabconf['AWS_ACCESS_KEY'], aws_secret_access_key=fabconf['AWS_SECRET_KEY'])
image = conn.get_all_images(ec2_amis)
reservation = image[0].run(1, 1, ec2_keypair, ec2_secgroups,
instance_type=ec2_instancetype)
instance = reservation.instances[0]
conn.create_tags([instance.id], {"Name":fabconf['INSTANCE_NAME_TAG']})
while instance.state == u'pending':
print(_yellow("Instance state: %s" % instance.state))
time.sleep(10)
instance.update()
print(_green("Instance state: %s" % instance.state))
print(_green("Public dns: %s" % instance.public_dns_name))
def get_subnet_list(vpc_conn, vpc_id):
raw_subnet_list = vpc_conn.get_all_subnets(filters={'vpc_id': vpc_id})
subnet_list = []
ec2_conn = boto.ec2.connect_to_region('ap-southeast-2',
aws_access_key_id=AWS_ACCESS_KEY_ID,
aws_secret_access_key=AWS_SECRET_ACCESS_KEY)
for s in raw_subnet_list:
id = s.id
cidr_block = s.cidr_block
name = s.tags['Name']
#print "\t", name, cidr_block
if SHOW_IP:
childern_list = get_network_interfaces(ec2_conn, filters={'subnet_id': id})
else:
childern_list = get_ec2_list(ec2_conn, filters={'subnet_id': id})
so = Subnet(id, name, cidr_block, child=childern_list)
#print so.dot()