Reputation: 3209
i need a small help to put the content returned from dictionary to 2 different list.
The code is :
for region in regions:
instance_information = {}
ip_dict = {}
client = boto3.client('ec2',aws_access_key_id=ACCESS_KEY,aws_secret_access_key=SECRET_KEY,region_name=region,)
addresses_dict = client.describe_addresses().get('Addresses')
for address in addresses_dict:
if address.get('InstanceId'):
instance_information[address['InstanceId']] = [address.get('PublicIp')]
dex_dict = client.describe_tags().get('Tags')
for dex in dex_dict:
if instance_information.get(dex['ResourceId']):
instance_information[dex['ResourceId']].append(dex.get('Value'))
print (json.dumps(instance_information,indent=4))
This returns :
{
"i-c581ea32": [
"52.113.42.171",
"SDL Exclusive LB",
"pdx01-ms-pdl-lb01"
],
"i-b8601217": [
"52.26.21.83",
"pdx-LBi-b8609671",
"HAProxy Server",
"us-west-2",
"pdx02-cloud-trial01",
"subnet-d86be1af",
"us-west-2b"
],
"i-3c2b02ca": [
"52.13.84.44",
"pdx01-lb02"
],
"i-986fc140": [
"52.3.173.116",
"pdx-hprod-LBi-316fc340",
"HAProxy Server",
"us-west-2",
"pdx02-he-prod",
"subnet-bcdcd6cb",
"us-west-2b"
],
"i-035a2c4": [
"5.33.81.148",
"pdx-ece-prod-LBi-022c4",
"HAProxy Server",
"us-west-2",
"pdx02-emsce-prod
I just need to extract the IP and put it in a dict . I need to pass this IP to another def
, How can this be done?
Upvotes: 0
Views: 73
Reputation: 42678
List comprehension is your tool:
iplist = [v[0] for v in instance_information.values()]
EDIT: As you need, make a function that returns you the ips
def getIpFromRegions(regions):
for region in regions:
instance_information = {}
ip_dict = {}
client = boto3.client('ec2',aws_access_key_id=ACCESS_KEY,aws_secret_access_key=SECRET_KEY,region_name=region,)
addresses_dict = client.describe_addresses().get('Addresses')
for address in addresses_dict:
if address.get('InstanceId'):
instance_information[address['InstanceId']] = [address.get('PublicIp')]
dex_dict = client.describe_tags().get('Tags')
for dex in dex_dict:
if instance_information.get(dex['ResourceId']):
instance_information[dex['ResourceId']].append(dex.get('Value'))
yield [v[0] for v in instance_information.values()]
EDIT2:
For all combined ip of region make a comprehension over your new function:
allip = [ip for ip in ips for ips in getIpFromRegions(regions)]
Upvotes: 3
Reputation: 22954
You may simple iterate over all the values in the given dictionary and select the first element as the IP to append it in a new list.
ip_list = [i[0]for i in instance_information.values()]
>> ['52.113.42.171', '52.26.21.83', '52.13.84.44', '5.33.81.148', '52.3.173.116']
Or if you need a dictionary like structure then you may try:
instance_information_ip = {i:instance_information[i][0] for i in instance_information}
>>> {'i-c581ea32': '52.113.42.171', 'i-b8601217': '52.26.21.83', 'i-3c2b02ca': '52.13.84.44', 'i-986fc140': '52.3.173.116', 'i-035a2c4': '5.33.81.148'}
Upvotes: 1