|
1 | 1 | # SPDX-License-Identifier: Apache-2.0 |
2 | 2 |
|
| 3 | +import os |
| 4 | +import subprocess |
| 5 | + |
3 | 6 | from cliff.command import Command |
4 | 7 | from loguru import logger |
| 8 | +import yaml |
5 | 9 |
|
6 | 10 | from osism.tasks import conductor, netbox, handle_task |
7 | 11 |
|
@@ -133,3 +137,65 @@ def take_action(self, parsed_args): |
133 | 137 | task.wait(timeout=None, interval=0.5) |
134 | 138 | result = task.get() |
135 | 139 | print(result) |
| 140 | + |
| 141 | + |
| 142 | +class Console(Command): |
| 143 | + def get_parser(self, prog_name): |
| 144 | + parser = super(Console, self).get_parser(prog_name) |
| 145 | + parser.add_argument( |
| 146 | + "type", |
| 147 | + nargs=1, |
| 148 | + choices=["info", "search", "filter", "shell"], |
| 149 | + help="Type of the console (default: %(default)s)", |
| 150 | + ) |
| 151 | + parser.add_argument( |
| 152 | + "arguments", nargs="*", type=str, default="", help="Additional arguments" |
| 153 | + ) |
| 154 | + |
| 155 | + return parser |
| 156 | + |
| 157 | + def take_action(self, parsed_args): |
| 158 | + type_console = parsed_args.type[0] |
| 159 | + arguments = " ".join( |
| 160 | + [f"'{item}'" if " " in item else item for item in parsed_args.arguments] |
| 161 | + ) |
| 162 | + |
| 163 | + home_dir = os.path.expanduser("~") |
| 164 | + nbcli_dir = os.path.join(home_dir, ".nbcli") |
| 165 | + if not os.path.exists(nbcli_dir): |
| 166 | + os.mkdir(nbcli_dir) |
| 167 | + |
| 168 | + nbcli_file = os.path.join(nbcli_dir, "user_config.yml") |
| 169 | + if not os.path.exists(nbcli_file): |
| 170 | + try: |
| 171 | + with open("/run/secrets/NETBOX_TOKEN", "r") as fp: |
| 172 | + token = fp.read().strip() |
| 173 | + except FileNotFoundError: |
| 174 | + token = None |
| 175 | + |
| 176 | + url = os.environ.get("NETBOX_API", None) |
| 177 | + |
| 178 | + if not token or not url: |
| 179 | + logger.error("Netbox integration not configured.") |
| 180 | + return |
| 181 | + |
| 182 | + subprocess.call( |
| 183 | + ["/usr/local/bin/nbcli", "init"], |
| 184 | + stdout=subprocess.DEVNULL, |
| 185 | + stderr=subprocess.DEVNULL, |
| 186 | + ) |
| 187 | + os.remove(nbcli_file) |
| 188 | + |
| 189 | + nbcli_config = { |
| 190 | + "pynetbox": { |
| 191 | + "url": url, |
| 192 | + "token": token, |
| 193 | + }, |
| 194 | + "requests": {"verify": False}, |
| 195 | + "nbcli": {"filter_limit": 50}, |
| 196 | + "user": {}, |
| 197 | + } |
| 198 | + with open(nbcli_file, "w") as fp: |
| 199 | + yaml.dump(nbcli_config, fp, default_flow_style=False) |
| 200 | + |
| 201 | + subprocess.call(f"/usr/local/bin/nbcli {type_console} {arguments}", shell=True) |
0 commit comments