I am trying to list the unused load balancers(elb).. I am trying the below code and it throws an error
'Attribute Error': 'str' object has no attribute 'describe_instance_health()'
import boto3
elb = boto3.client('elb')
allElbs = elb.describe_load_balancers()
print (allElbs)
for lb in allElbs:
instances = lb.describe_instance_health()
if len(instances)==0:
print (lb)
for instanceState in instances:
if instanceState.state == 'OutOfService':
print (lb)
Please help me solve this..
Thanks
enter image description here
Updated Code:
import boto3
elb = boto3.client('elb')
allElbs = elb.describe_load_balancers()
#print (allElbs)
for lb in allElbs['LoadBalancerDescriptions']:
#instances = elb.describe_instance_health(lb['LoadBalancerName'])
#instances = elb.describe_instance_health(['LoadBalancerName'])
instances = elb.describe_instance_health(LoadBalancerName=lb['LoadBalancerName'])
if len(instances)==0:
print (lb)
for instanceState in instances:
if instanceState == 'OutOfService':
print (lb)
Below. The call to describe_load_balancers() return a dict. Inside the dict you can find the list of the lb's. See here and here.
import boto3
def filter_lbs():
""" return a list of lb's that has no instances or in state OutOfService"""
result = []
elb = boto3.client('elb')
lbs = elb.describe_load_balancers()
for lb in lbs['LoadBalancerDescriptions']:
instances = elb.describe_instance_health(LoadBalancerName=lb['LoadBalancerName'])['InstanceStates']
if not instances:
result.append(lb['LoadBalancerName'])
continue
for instance in instances:
if instance['State'] == 'OutOfService':
result.append(lb['LoadBalancerName'])
continue
return result
Related
I am using Azure Confidential Ledger, and I am trying to query it. But when I want to print a variable that contain value I encounter following line as an output:
bound method ConfidentialLedgerClientOperationsMixin.list_ledger_entries of <azure.confidentialledger._patch.ConfidentialLedgerClient object at 0x000001BAD31ED048>>
My code is as follow:
from azure.confidentialledger import ConfidentialLedgerClient
from azure.confidentialledger.certificate import ConfidentialLedgerCertificateClient
from azure.identity import DefaultAzureCredential
identity_client = ConfidentialLedgerCertificateClient()
network_identity = identity_client.get_ledger_identity(
ledger_id="MyLedger"
)
ledger_tls_cert_file_name = "ledger_certificate.pem"
with open(ledger_tls_cert_file_name, "w") as cert_file:
cert_file.write(network_identity["ledgerTlsCertificate"])
credential = DefaultAzureCredential()
ledger_client = ConfidentialLedgerClient(
endpoint="https://MyLedger.confidential-ledger.azure.com",
credential=credential,
ledger_certificate_path=ledger_tls_cert_file_name
)
d = ledger_client.list_ledger_entries
print(d)
In addition, I have read following questions:
How to print the value of the object?
Is there a built-in function to print all the current properties and values of an object?
Try this:
d = ledger_client.list_ledger_entries()
instead of this
d = ledger_client.list_ledger_entries
in your code, you did not assign the the result of the method call to the var d but instead assigned the method list_ledger_entries's object of ledger_client to d
I have two issues
level list does not contain name or other parameter why this error is comming to every element I am collecting
Urinals.Symbol.FamilyName("Type Comments").AsString() == "Urinal"): is not working
from pyrevit.output import charts
from pyrevit import script
from pyrevit import revit, DB
from Autodesk.Revit.DB import FilteredElementCollector, BuiltInCategory
__context__ = 'zerodoc'
from System.Collections.Generic import List
doc = __revit__.ActiveUIDocument.Document
uidoc = __revit__.ActiveUIDocument
from rpw import db, ui, doc
from pyrevit.framework import List
from pyrevit import revit, DB
room_filter = "WORK"
import rpw
from rpw import doc, uidoc, DB
# GET ALL ROOMS IN MODEL
rooms = DB.FilteredElementCollector(doc).OfCategory(DB.BuiltInCategory.OST_Rooms)
Urinals = DB.FilteredElementCollector(doc).OfCategory(DB.BuiltInCategory.OST_PlumbingFixtures).WhereElementIsNotElementType().ToElements()
ub_count = 0
MRest_rooms = []
WRest_rooms = []
ADARest_rooms = []
Urinal_count = 0
#for u in Urinals:
# if (Urinals.Symbol.FamilyName("Type Comments").AsString() == "Urinal"):
# Urinal_count +=1
for r in rooms:
if (r.Level.Name != 'CONTAINER LEVEL') and (r.LookupParameter("Name").AsString() == "M RESTROOM"):
MRest_rooms.append(r)
if (r.Level.Name != 'CONTAINER LEVEL') and (r.LookupParameter("Name").AsString() == "W RESTROOM"):
WRest_rooms.append(r)
print "Number of Male Rest Room =",len(MRest_rooms)
print "Number of Female Rest Room =", len(WRest_rooms)
Level = DB.FilteredElementCollector(doc).OfCategory(DB.BuiltInCategory.OST_Levels).WhereElementIsNotElementType().ToElements()
print "Number of Level =",len(Level)
for i in Level:
a = Level.Name
print a
Your error is this line:
Level = DB.FilteredElementCollector(doc).OfCategory(DB.BuiltInCategory.OST_Levels).WhereElementIsNotElementType().ToElements()
print "Number of Level =",len(Level)
for i in Level:
a = Level.Name
print a
It should be:
Level = DB.FilteredElementCollector(doc).OfCategory(DB.BuiltInCategory.OST_Levels).WhereElementIsNotElementType().ToElements()
print "Number of Level =",len(Level)
for i in Level:
a = i.Name
print a
Inside of the for loop you called Level.Name where Level is actually a list of levels. Hence the exception.
Same issue with the commented out code:
for u in Urinals:
if (Urinals.Symbol.FamilyName("Type Comments").AsString() == "Urinal"):
Urinal_count +=1
Replace with:
for u in Urinals:
if (u.Symbol.FamilyName("Type Comments").AsString() == "Urinal"):
Urinal_count +=1
Look at it in the debugger and you will see for yourself.
The code below is giving me the result for one specified region, can anyone help me how to get all untagged ec2 instances information across all regions in one aws account?
#!/usr/bin/env python
import boto3
import json, ast
instances = [i for i in boto3.resource('ec2', region_name='us-east-2').instances.all()]
for i in instances:
d = (i.tags[0])
d2 = ast.literal_eval(json.dumps(d))
if ( d2['Value'] == "" ):
print i.instance_id
Get list of all regions. Loop through each region and execute your code. Something like this:
def do_tags(region):
instances = [i for i in boto3.resource('ec2', region_name=region).instances.all()]
for i in instances:
d = (i.tags[0])
d2 = ast.literal_eval(json.dumps(d))
if ( d2['Value'] == "" ):
print i.instance_id
regions = boto3.session.Session().get_available_regions('ec2')
for region in regions:
print 'Checking region:', region
do_tags(region)
I need to extract all the RUNNING PUBLIC Ip's from AWS and i am using the following code:
def gather_public_ip():
regions = ['us-west-2', 'eu-central-1', 'ap-southeast-1']
combined_list = [] ##This needs to be returned
for region in regions:
instance_information = [] # I assume this is a list, not dict
ip_dict = {}
client = boto3.client('ec2', aws_access_key_id=ACCESS_KEY, aws_secret_access_key=SECRET_KEY,
region_name=region, )
instance_dict = client.describe_instances().get('Reservations')
for reservation in instance_dict:
for instance in reservation['Instances']: # This is rather not obvious
if instance[unicode('State')][unicode('Name')] == 'running' and instance[unicode('PublicIpAddress')] != None:
ipaddress = instance[unicode('PublicIpAddress')]
tagValue = instance[unicode('Tags')][0][unicode('Value')] # 'Tags' is a list, took the first element, you might wanna switch this
zone = instance[unicode('Placement')][unicode('AvailabilityZone')]
info = ipaddress, tagValue, zone
instance_information.append(info)
combined_list.append(instance_information)
return combined_list
This is not working out for me , and it gives me the error :
ipaddress = instance[unicode('PublicIpAddress')]
KeyError: u'PublicIpAddress'
The reason being PublicIpAddress doesn't exists in this dict.. Can someone please help me out ?
Use get() instead of dict[key]. get() will not raise a KeyError. Here are some examples which will explain.
>>> test = {'xxx':123}
>>> test['xxx']
123
>>> test['yyy']
KeyError: 'yyy'
>>> test.get('yyy')
>>> test.get('yyy') is None
True
And you can check if 'PublicIpAddress' is absent as follows.
ipaddress = instance.get(u'PublicIpAddress')
if ipaddress is None:
# Do Something
EDIT
if instance[u'State'][u'Name'] == 'running' and instance.get(u'PublicIpAddress') is not None:
print instance.get(u'PublicIpAddress')
I want to append a list of array in dynamodb using python. I am using boto for the same. I am able to append the list in python and saving it in a variable. Now just wanted to append that value in an item (list of array) which is empty right now and don't know how to do it. So it would be great if anyone can help me with that.
result = self.User_Connection.scan(main_user__eq=self.username)
for connection_details in result:
main_user = connection_details['main_user']
connection_list = connection_details['connections']
connection_list.append(frnd_user_id)
I want to add this connection_list.append(frnd_user_id) as an item.
I've tried doing like this:-
if user_connections['connections'] == None:
self.User_Connection.put_item(data={'connections' : set(frnd_user_id)})
else:
self.User_Connection.update_item(Key = {user_connections['id']}, UpdateExpression="SET connections = list_append(connections, :i)",
ExpressionAttributeValues={':i': [frnd_user_id],})
but it is not working. Giving error:-
'Table' has no attribute 'update_item'
I've tried doing like this too:-
result = self.User_Connection.scan(main_user__eq=self.username)
for connection_details in result:
main_user = connection_details['main_user']
main_userid = connection_details['id']
connection_list = connection_details['connections']
print connection_list
if connection_details['connections'] == None:
self.User_Connection.put_item(data={'id' : main_userid,
'main_user':self.username,
'connections[]' : frnd_user_id})
else:
item = self.User_Connection.get_item(id = connection_details['id'])
for i in frnd_user_id:
item[connection_list].append(i)
item.save(overwrite=True)
this is showing error too.
unhashable type: 'list'