Add script in to see if it just works as an inventory source
This commit is contained in:
80
inventory/linode.py
Normal file
80
inventory/linode.py
Normal file
@@ -0,0 +1,80 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
import json
|
||||
import sys
|
||||
import os
|
||||
import urllib.request
|
||||
from argparse import ArgumentParser
|
||||
|
||||
def main():
|
||||
parser = ArgumentParser()
|
||||
parser.add_argument('--list', action='store_true')
|
||||
parser.add_argument('--host')
|
||||
args = parser.parse_args()
|
||||
|
||||
if args.host:
|
||||
print('{}')
|
||||
return
|
||||
|
||||
token = os.environ.get('LINODE_API_TOKEN')
|
||||
if not token:
|
||||
print('{"_meta": {"hostvars": {}}}')
|
||||
return
|
||||
|
||||
try:
|
||||
req = urllib.request.Request('https://api.linode.com/v4/linode/instances')
|
||||
req.add_header('Authorization', f'Bearer {token}')
|
||||
|
||||
with urllib.request.urlopen(req, timeout=30) as response:
|
||||
data = json.loads(response.read().decode('utf-8'))
|
||||
|
||||
inventory = {"_meta": {"hostvars": {}}, "all": {"children": []}}
|
||||
groups = {}
|
||||
|
||||
for instance in data.get('data', []):
|
||||
if instance['status'] != 'running':
|
||||
continue
|
||||
|
||||
hostname = instance['label']
|
||||
ip = instance['ipv4'][0] if instance.get('ipv4') else None
|
||||
if not ip:
|
||||
continue
|
||||
|
||||
# Host vars
|
||||
tags = instance.get('tags', [])
|
||||
inventory['_meta']['hostvars'][hostname] = {
|
||||
'ansible_host': ip,
|
||||
'ansible_user': 'phlux',
|
||||
'linode_region': instance['region'],
|
||||
'linode_type': instance['type'],
|
||||
'linode_tags': tags,
|
||||
'is_k3s': 'k3s' in tags,
|
||||
'is_control_plane': 'control-plane' in tags,
|
||||
'is_worker_node': 'worker-node' in tags
|
||||
}
|
||||
|
||||
# Create groups
|
||||
for tag in tags:
|
||||
group = f"tag_{tag.replace('-', '_')}"
|
||||
if group not in groups:
|
||||
groups[group] = []
|
||||
groups[group].append(hostname)
|
||||
|
||||
region_group = f"region_{instance['region'].replace('-', '_')}"
|
||||
if region_group not in groups:
|
||||
groups[region_group] = []
|
||||
groups[region_group].append(hostname)
|
||||
|
||||
# Add groups to inventory
|
||||
for group, hosts in groups.items():
|
||||
inventory[group] = {"hosts": hosts}
|
||||
inventory['all']['children'].append(group)
|
||||
|
||||
print(json.dumps(inventory, indent=2))
|
||||
|
||||
except Exception as e:
|
||||
print(f'{{"error": "{e}"}}', file=sys.stderr)
|
||||
print('{"_meta": {"hostvars": {}}}')
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
Reference in New Issue
Block a user