-
Notifications
You must be signed in to change notification settings - Fork 333
/
Copy pathDynamicInventory.py
48 lines (39 loc) · 1.32 KB
/
DynamicInventory.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#!/bin/python
# Shebang Line Should Point Python Installation Path
"""
Author Landmark Technologies
Fetech List of Servers from AWS and group based on EC2
instance tag name and value.
"""
import pprint
import boto3
import json
def getgroupofhosts(ec2):
allgroups = {}
for each_in in ec2.instances.filter(Filters=[{'Name': 'instance-state-name', 'Values': ['running']}]):
for tag in each_in.tags:
if tag["Key"] in allgroups:
hosts = allgroups.get(tag["Key"])
hosts.append(each_in.public_ip_address)
allgroups[tag["Key"]] = hosts
else:
hosts = [each_in.public_ip_address]
allgroups[tag["Key"]] = hosts
if tag["Value"] in allgroups:
hosts = allgroups.get(tag["Value"])
hosts.append(each_in.public_ip_address)
allgroups[tag["Value"]] = hosts
else:
hosts = [each_in.public_ip_address]
allgroups[tag["Value"]] = hosts
return allgroups
def main():
ec2 = boto3.resource("ec2")
all_groups = getgroupofhosts(ec2)
inventory = {}
for key, value in all_groups.items():
hostsobj = {'hosts': value}
inventory[key] = hostsobj
print(json.dumps(inventory))
if __name__ == "__main__":
main()