aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorbinary <me@rgoncalves.se>2021-02-14 12:14:01 +0100
committerbinary <me@rgoncalves.se>2021-02-14 12:14:01 +0100
commit3b003c10fc6aa3a2a60eac27cbef94c3c8c284e7 (patch)
treeb15bf6dac9d28548b29e8e13e9ad68ee4815c21b
parent68e20f54eda6de055adb9bda5969bedf20cf928b (diff)
downloadinfrastructure-3b003c10fc6aa3a2a60eac27cbef94c3c8c284e7.tar.gz
Add groups assignement based on hostname regexp
-rwxr-xr-xdynamic.py32
-rw-r--r--group_vars/servers.yml0
2 files changed, 29 insertions, 3 deletions
diff --git a/dynamic.py b/dynamic.py
index 908e4d3..5354474 100755
--- a/dynamic.py
+++ b/dynamic.py
@@ -12,16 +12,29 @@
# host/group/node is individually track on version control.
import os
-import yaml
import logging
import json
+import re
+import yaml
-from typing import Final
from optparse import OptionParser
+from typing import Final
HOST_DIR: Final = "./host_vars"
GROUP_DIR: Final = "./group_vars"
+GROUP_PATTERNS: Final = {
+ "servers": [
+ "^dc[0-9]*",
+ "^rt[0-9]*",
+ "^st[0-9]*",
+ "^stack[0-9]*",
+ "^emb[0-9]*"
+ ],
+ "workstation": [
+ "^ws*"
+ ]
+}
class AnsibleInput:
@@ -63,6 +76,16 @@ def create_nodes(directory):
return nodes
+def group_regexp(hostname, hostgroups):
+ for groupname, group in GROUP_PATTERNS.items():
+ for pattern in group:
+ regexp = re.compile(pattern)
+ if regexp.search(hostname):
+ logging.info(f"hostname { hostname } matched with"
+ f"{ pattern } for group { groupname }")
+ hostgroups.append(groupname)
+
+
def get_hostvars(host):
"""
Retrieve and build dynamic variables for a specific host.
@@ -79,7 +102,7 @@ def get_subgroups(groups, og):
Get and return all children of a specific group, in a given subset.
"""
- # specific return for group "all"
+ # specific return for group "all"
if og.name in "all":
groups = list(groups.keys())
groups.remove("all")
@@ -130,6 +153,9 @@ def get_list(hosts, groups):
# retrieve _groups variables and force conversion to list
cleangr = host.data["_groups"]
cleangr = [cleangr] if isinstance(cleangr, str) else cleangr
+ # group assignement based on regexp
+ group_regexp(hostname, cleangr)
+ # final assignement with correct groupname
for group in cleangr:
if group not in groups:
logging.error(f"group { group } does not exist!")
diff --git a/group_vars/servers.yml b/group_vars/servers.yml
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/group_vars/servers.yml
remember that computers suck.