]> Frank Brehm's Git Trees - pixelpark/create-terraform.git/commitdiff
Adding deletion of Key/Value in Consul
authorFrank Brehm <frank.brehm@pixelpark.com>
Mon, 27 May 2024 11:23:58 +0000 (13:23 +0200)
committerFrank Brehm <frank.brehm@pixelpark.com>
Mon, 27 May 2024 11:23:58 +0000 (13:23 +0200)
lib/create_terraform/app.py
lib/create_terraform/handler/__init__.py

index 40721c8e09cc8fb3873f10abcc4fa07d08407f17..dac63174923eefb83548ede500f2315fa4070b46 100644 (file)
@@ -42,7 +42,7 @@ from .xlate import __base_dir__ as __xlate_base_dir__
 from .xlate import __mo_file__ as __xlate_mo_file__
 from .xlate import XLATOR, LOCALE_DIR, DOMAIN
 
-__version__ = '1.3.6'
+__version__ = '1.4.0'
 LOG = logging.getLogger(__name__)
 
 SIGNAL_NAMES = {
@@ -156,6 +156,7 @@ class CrTfApplication(BaseApplication):
     """
 
     show_simulate_option = True
+    show_assume_options = True
 
     re_prefix = re.compile(r'^[a-z0-9][a-z0-9_]*$', re.IGNORECASE)
     re_anum = re.compile(r'[^A-Z0-9_]+', re.IGNORECASE)
@@ -332,9 +333,12 @@ class CrTfApplication(BaseApplication):
 #                 "but this is currently not used.").format(self.fake_root_passwd))
 #             self.config.vm_root_password = self.fake_root_passwd
 
+        project_name = getattr(self.args, 'project', None)
+
         self.handler = CreateTerraformHandler(
             appname=self.appname, verbose=self.verbose, base_dir=self.base_dir,
             simulate=self.simulate, force=self.force, config=self.config,
+            project_name=project_name, assumed_answer=self.assumed_answer,
             terminal_has_colors=self.terminal_has_colors)
 
         if self.args.stop_after:
@@ -397,9 +401,17 @@ class CrTfApplication(BaseApplication):
         default_cfg_file = self.base_dir.joinpath('etc').joinpath(self.appname + '.ini')
         default_cfg_file_rel = Path(os.path.relpath(str(default_cfg_file), str(cur_dir)))
 
+        cr_tf_group =  self.arg_parser.add_argument_group(_('Special options for {}').format(
+            self.appname))
+
+        cr_tf_group.add_argument(
+            '-P', '--project', metavar=_('PROJECT'), dest='project',
+            help=_('Name of the project in the Consul Key/Value data store.')
+        )
+
         steps = list(CreateTerraformHandler.steps[:]) + ['?']
 
-        self.arg_parser.add_argument(
+        cr_tf_group.add_argument(
             '-S', '--stop-after', metavar=_('STEP'), dest='stop_after', choices=steps,
             action=StopStepOptionAction,
             help=_(
@@ -407,7 +419,7 @@ class CrTfApplication(BaseApplication):
                 "Use {!r} to show a list of all avaliable steps.").format('--stop-after ?')
         )
 
-        self.arg_parser.add_argument(
+        cr_tf_group.add_argument(
             '-c', '--config', '--config-file', dest='cfg_file', metavar=_('FILE'),
             action=CfgFileOptionAction,
             help=_("Configuration file (default: {!r})").format(str(default_cfg_file_rel))
index 0e23688297cb5983a38afd621859be6669029beb..755247b386b9cab8431b8399086a3d993c43d93e 100644 (file)
@@ -9,11 +9,12 @@
 from __future__ import absolute_import, print_function
 
 # Standard module
+import copy
 import os
 import logging
 import re
 import stat
-import copy
+import sys
 
 from pathlib import Path
 
@@ -48,7 +49,7 @@ from ..errors import AbortExecution
 
 from ..xlate import XLATOR
 
-__version__ = '4.2.1'
+__version__ = '4.3.0'
 LOG = logging.getLogger(__name__)
 
 _ = XLATOR.gettext
@@ -118,9 +119,9 @@ class CreateTerraformHandler(
 
     # -------------------------------------------------------------------------
     def __init__(
-        self, appname=None, verbose=0, version=__version__, base_dir=None,
+        self, appname=None, verbose=0, version=__version__, base_dir=None, project_name=None,
             config=None, simulate=False, force=False, ignore_existing_dns=False,
-            terminal_has_colors=False, initialized=False):
+            terminal_has_colors=False, assumed_answer=None, initialized=False):
 
         self.pdns = None
         self.vsphere = {}
@@ -153,7 +154,12 @@ class CreateTerraformHandler(
         self.used_dc_clusters = {}
         self.used_datastores = {}
         self.project_dir = None
+
         self.project_name = None
+        if project_name:
+            project = str(project_name).strip()
+            if project:
+                self.project_name = project
 
         self._terraform_root_dir = None
 
@@ -201,7 +207,7 @@ class CreateTerraformHandler(
         super(CreateTerraformHandler, self).__init__(
             appname=appname, verbose=verbose, version=version, base_dir=base_dir,
             simulate=simulate, force=force, terminal_has_colors=terminal_has_colors,
-            initialized=False,
+            assumed_answer=assumed_answer, initialized=False,
         )
 
         if config:
@@ -299,7 +305,7 @@ class CreateTerraformHandler(
         if not self.project_name:
             return None
         if not self.project_dir:
-            return None
+            return self.project_name
         if not self.terraform_root_dir:
             return self.project_name
         return os.path.relpath(str(self.project_dir), self.terraform_root_dir)
@@ -478,17 +484,44 @@ class CreateTerraformHandler(
         else:
             msg = _('Found data for project {!r} on Consul database.').format(key)
             LOG.warn(msg)
-            if self.verbose > 2:
+            if self.verbose > 3:
                 msg = _('Found data:') + '\n' + pp(project_data)
                 LOG.debug(msg)
+            self.remove_consul_project(key)
 
         LOG.info(_("Finished step {!r}.").format('consul'))
         if self.stop_at_step == 'consul':
             raise AbortExecution('consul')
 
+    # -------------------------------------------------------------------------·
+    def remove_consul_project(self, key):
+        """Ask for removing the project in consul and remove it, if the answer is yes."""
+        print()
+        msg = _(
+            "Should the project with key '{key}' be removed from Consul server '{srv}' "
+            "[Y/n]?").format(
+            key=self.colored(key, 'YELLOW'),
+            srv=self.colored(self.consul.server_url, 'YELLOW')) + ' '
+
+        answer = self.ask_for_yes_or_no(msg, default_on_empty=True)
+        print()
+
+        if not answer:
+            return
+
+        try:
+            self.consul.remove_key(key)
+        except ConsulApiNotFoundError as e:
+            msg = _('Key is subtle vanished') + ' - ' + str(e)
+            LOG.warn(msg)
+
     # -------------------------------------------------------------------------·
     def set_project(self, yaml_file):
         """Set project name and directory."""
+        if self.project_name:
+            LOG.debug(_('Project name {!r} already set.').format(self.full_project_name))
+            return
+
         LOG.debug(_('Setting project name and directory based on file {!r} ...').format(
             str(yaml_file)))
 
@@ -575,6 +608,26 @@ class CreateTerraformHandler(
         print(_("and enter: {}").format(self.colored('terraform apply', 'GREEN')))
         print()
 
+    # -------------------------------------------------------------------------
+    def exit(self, retval=-1, msg=None):
+        """Exit the current application."""
+        retval = int(retval)
+        root_logger = logging.getLogger()
+
+        if msg:
+            if root_logger.handlers:
+               if retval:
+                    LOG.error(msg)
+               else:
+                    LOG.info(msg)
+            if not has_handlers:
+                if hasattr(sys.stderr, 'buffer'):
+                    sys.stderr.buffer.write(str(msg) + '\n')
+                else:
+                    sys.stderr.write(str(msg) + '\n')
+
+        sys.exit(retval)
+
 
 # =============================================================================