Skip to content

ApplicationHelper

Core helper class that provides centralized access to application configuration, environment context, and AWS resource management utilities.

This class serves as the primary interface for accessing CDK context configuration, managing environment-specific settings, and providing utilities for parameter store operations, VPC lookups, and resource naming within the MARE ecosystem.

The helper reads configuration from cdk.json and provides type-safe access to application metadata, environment-specific settings, and common configurations.

Source code in mare_aws_common_lib/helpers/application_helper.py
 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
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
class ApplicationHelper:
    """
    Core helper class that provides centralized access to application configuration,
    environment context, and AWS resource management utilities.

    This class serves as the primary interface for accessing CDK context configuration,
    managing environment-specific settings, and providing utilities for parameter store
    operations, VPC lookups, and resource naming within the MARE ecosystem.

    The helper reads configuration from cdk.json and provides type-safe access to
    application metadata, environment-specific settings, and common configurations.
    """

    def __init__(self, app: App, **kwargs: Any) -> None:
        """
        Initialize the ApplicationHelper with CDK app context and configuration.

        Reads and validates configuration from the CDK app context, including
        environment settings, application metadata, and common configurations.
        Ensures all required configuration sections are present and valid.

        Args:
            app (App): The CDK application instance containing context configuration

        Raises:
            ValueError: If required configuration is missing or invalid:
                - 'env' context parameter not provided via command line
                - Environment value not in valid Environment enum list
                - 'environments' node missing from cdk.json
                - 'common' node missing from cdk.json
                - Target environment section missing from environments configuration        
        """
        self._target_env: str = app.node.try_get_context("env").lower()
        if not self._target_env:
            raise ValueError("env must be a passed via the command line with -c env=...")

        self._app_version: str = app.node.try_get_context("app_version")
        if not self._app_version:
            self._app_version = "latest"

        env_list: List[str] = Environment.list()
        if self._target_env.upper() not in env_list:
            raise ValueError(f"env value must be in {env_list}")

        self._all_envs: Dict[str, Any] = app.node.try_get_context("environments")
        if not self._all_envs:
            raise ValueError("cdk.json must contain a 'environments' node")

        self._common_configs: Dict[str, Any] = app.node.try_get_context("common")
        if not self._common_configs:
            raise ValueError("cdk.json must contain a 'common' node")

        self._env_config: Dict[str, Any] = self._all_envs[self._target_env]
        if not self._env_config:
            raise ValueError(f"cdk.json must contain in the 'environments' node a section for {self._target_env}")

        self._application_config: Dict[str, Any] = app.node.try_get_context("application")

    def _get_parameter_name_from_key(self, param_key: str, force_devops: bool = False, 
                                     with_leading_slash: bool = False, env_name: str = None) -> str:
        """
        Generate a standardized Parameter Store parameter name from a key.

        Creates parameter names following the organizational pattern:
        {domain}/{project}/{environment}/{param_key}

        Args:
            param_key (str): The base parameter key to convert
            force_devops (bool, optional): Force use of 'devops' environment regardless
                of current target environment. Defaults to False.
            with_leading_slash (bool, optional): Include leading slash in parameter name.
                Defaults to False.
            env_name (str, optional): Override environment name. If not provided,
                uses target environment or 'devops' if force_devops is True.

        Returns:
            str: Formatted parameter name following organizational standards
        """
        target_env = "devops"
        if not force_devops:
            target_env = env_name if env_name is not None else self.get_target_env()
        param_name = f"{self.get_domain()}/{self.get_project()}/{target_env}/{param_key}".lower()

        if with_leading_slash and not param_name.startswith("/"):
            param_name = "/" + param_name

        return param_name

    def get_all_envs(self) -> Dict[str, Any]:
        """
        Get all environment configurations from cdk.json.

        Returns:
            Dict[str, Any]: Dictionary containing all environment configurations
                with environment names as keys and their configurations as values
        """
        return self._all_envs

    def get_target_env(self) -> str:
        """
        Get the current target environment name.

        This is the environment specified via the CDK command line parameter
        (-c env=<environment_name>).

        Returns:
            str: The target environment name (e.g., 'dev', 'prod', 'test')
        """
        return self._target_env

    def get_app_version(self) -> str:
        """
        Get the application version.

        Returns:
            str: The current application version string
        """
        return self._app_version

    def get_application_config(self) -> Dict[str, Any]:
        """
        Get the complete application configuration dictionary.

        Returns:
            Dict[str, Any]: The full application configuration containing
                        all parameters (domain, organization, project, ...)
        """
        return self._application_config

    def get_domain(self) -> str:
        """
        Get the application domain from configuration.

        Returns:
            str: The domain identifier for the application
        """
        return self._application_config["domain"]

    def get_organization(self) -> str:
        """
        Get the organization name from configuration.

        Returns:
            str: The organization identifier
        """
        return self._application_config["organization"]

    def get_project(self) -> str:
        """
        Get the project name from configuration.

        Returns:
            str: The project identifier
        """
        return self._application_config["project"]

    def get_owner(self) -> str:
        """
        Get the project owner from configuration.

        Returns:
            str: The owner identifier for the project
        """
        return self._application_config["owner"]

    def get_technology(self) -> str:
        """
        Get the technology stack identifier from configuration.

        Returns:
            str: The technology stack identifier
        """
        return self._application_config["technology"]

    def get_vpc_id(self) -> str:
        """
        Get the VPC ID for the current target environment.

        Returns:
            str: The AWS VPC ID for the target environment

        Raises:
            KeyError: If vpc.id is not configured for the target environment
        """
        return self._env_config["vpc"]["id"]

    def get_from_env(self, name: str) -> Any:
        """
        Retrieve a configuration value from the current environment's configuration.

        Supports both simple keys and nested keys using dot notation.
        For nested access, use dots to separate key levels (e.g., "database.host").

        Args:
            name (str): Configuration key name. Use dot notation for nested values
                (e.g., "vpc.id", "database.connection.timeout")

        Returns:
            Any: The configuration value at the specified key path

        Raises:
            KeyError: If the specified key path is not found in the environment configuration
        """
        error_message = f"Key '{name}' not found in environment configuration."

        if "." not in name:
            if name not in self._env_config:
                raise KeyError(error_message)
            return self._env_config[name]

        keys = name.split(".")
        value = self._env_config
        for key in keys:
            value = value.get(key)
            if value is None:
                raise KeyError(error_message)

        return value

    def has_env_key(self, name: str) -> bool:
        """
        Check if a configuration key exists in the current environment's configuration.

        Supports both simple keys and nested keys using dot notation.

        Args:
            name (str): Configuration key name. Use dot notation for nested values
                (e.g., "vpc.id", "database.connection.timeout")

        Returns:
            bool: True if the key exists, False otherwise
        """
        if "." not in name:
            return name in self._env_config

        keys = name.split(".")
        value = self._env_config

        for key in keys:
            if not isinstance(value, dict) or key not in value:
                return False
            value = value[key]

        return True

    def get_from_common(self, name: str) -> str:
        """
        Retrieve a configuration value from the common configuration section.

        Args:
            name (str): Configuration key name in the common section

        Returns:
            str: The configuration value from common configuration

        Raises:
            KeyError: If the key is not found in common configuration
        """
        return self._common_configs[name]

    def get_vpc(self, cfn_name: str, scope: Construct) -> ec2.Vpc:
        """
        Lookup and return the VPC for the current environment.

        Uses CDK's VPC lookup functionality to find the VPC by ID.

        Args:
            cfn_name (str): CloudFormation logical name for the VPC construct
            scope (Construct): CDK construct scope for the VPC lookup

        Returns:
            ec2.Vpc: The VPC construct for the current environment

        Raises:
            Exception: If VPC lookup fails or VPC ID is not found
        """
        return ec2.Vpc.from_lookup(scope, cfn_name, vpc_id=self.get_vpc_id())

    def debug(self) -> bool:
        """
        Check if debug mode is enabled in common configuration.

        Returns:
            bool: True if debug mode is enabled, False otherwise
        """
        return self._common_configs["debug"]

    def store_parameter(self, scope: Construct, param_key: str, param_value: str, 
                        tier: ssm.ParameterTier = ssm.ParameterTier.STANDARD) -> Tuple[ssm.StringParameter, str]:
        """
        Create and store a parameter in AWS Systems Manager Parameter Store.

        Creates a parameter with standardized naming convention and returns both
        the parameter construct and the generated parameter name for reference.

        Args:
            scope (Construct): CDK construct scope for parameter creation
            param_key (str): Base key for the parameter (will be formatted with domain/project/env)
            param_value (str): The value to store in the parameter
            tier (ssm.ParameterTier, optional): Parameter Store tier. 
                Defaults to ssm.ParameterTier.STANDARD.

        Returns:
            Tuple[ssm.StringParameter, str]: Tuple containing:
                - The created StringParameter construct
                - The formatted parameter name that was used
        """
        param_name = self._get_parameter_name_from_key(param_key)
        cfn_name = param_name.replace("/", "-").replace("_", "-")
        return (
            ssm.StringParameter(
                scope, 
                cfn_name,
                parameter_name=f"/{param_name}",
                string_value=param_value,
                tier=tier
            ),
            param_name
        )            

    # This method gets the value of a parameter in the cdk synth phase, returns a token
    def get_parameter_value(self, scope : Construct, param_key: str, force_devops: bool = False, env_name: str = None) -> Any:
        """
        Get a parameter value during CDK synthesis phase (returns a token).

        This method returns a CDK token that will be resolved during deployment.
        Use this when you need the parameter value in your CDK code but the actual
        value will be resolved at deploy time.

        Args:
            scope (Construct): CDK construct scope for parameter lookup
            param_key (str): Base parameter key (will be formatted with domain/project/env)
            force_devops (bool, optional): Force lookup in 'devops' environment.
                Defaults to False.
            env_name (str, optional): Override environment name for lookup.
                Defaults to None (uses target environment).

        Returns:
            Any: CDK token that resolves to the parameter value during deployment

        Note:
            This method is used during CDK synthesis and returns a token, not the actual value.
            For deployment-time value resolution, use get_parameter_value_deferred().
            For synthesis-time actual values, use get_parameter_value_from_lookup().
        """
        param_name = self._get_parameter_name_from_key(param_key, force_devops, True, env_name)
        value = ssm.StringParameter.value_for_string_parameter(scope, param_name)

        return value

    # This method gets the value of a parameter in the cdk deploy phase
    def get_parameter_value_deferred(self, scope: Construct, param_key: str, force_devops: bool = False, id_suffix: str = None) -> Any:
        """
        Get a parameter value during CDK deployment phase.

        This method creates a reference to an existing parameter that will be
        resolved during deployment. Use this when you need to reference parameters
        created in other stacks or external processes.

        Args:
            scope (Construct): CDK construct scope for parameter reference
            param_key (str): Base parameter key (will be formatted with domain/project/env)
            force_devops (bool, optional): Force lookup in 'devops' environment.
                Defaults to False.
            id_suffix (str, optional): Additional suffix for construct ID uniqueness.
                Defaults to None.

        Returns:
            Any: The parameter value that will be resolved during deployment

        Note:
            This creates a construct reference to an existing parameter.
            The parameter must exist before deployment for this to work.
        """
        param_name = self._get_parameter_name_from_key(param_key, force_devops, True)
        construct_id = param_key.replace("-", " ").replace("_", " ").title().replace(" ", "")
        if id_suffix is not None:
            construct_id = construct_id + id_suffix.replace("-", "").replace("_", "")
        value = ssm.StringParameter.from_string_parameter_attributes(
            scope, construct_id,
            parameter_name=param_name
        ).string_value

        return value

    # This method gets the value of a parameter during synth but returns the value itself and not the token like in get_parameter_value
    def get_parameter_value_from_lookup(self, scope : Construct, param_key: str, force_devops: bool = False) -> Any:
        """
        Get the actual parameter value during CDK synthesis phase.

        This method performs a real-time lookup and returns the actual parameter value
        (not a token) during synthesis. Use this when you need the actual value for
        synthesis-time decisions or computations.

        Args:
            scope (Construct): CDK construct scope for parameter lookup
            param_key (str): Base parameter key (will be formatted with domain/project/env)
            force_devops (bool, optional): Force lookup in 'devops' environment.
                Defaults to False.

        Returns:
            Any: The actual parameter value retrieved during synthesis

        Warning:
            This method requires AWS credentials and network access during synthesis.
            The parameter must exist in Parameter Store before running cdk synth/deploy.

        Note:
            Unlike get_parameter_value(), this returns the actual value, not a token.
            Use this for synthesis-time logic that depends on the parameter value.
        """
        param_name = self._get_parameter_name_from_key(param_key, force_devops, True)
        value = ssm.StringParameter.value_from_lookup(scope, param_name)

        return value

Attributes

_all_envs = app.node.try_get_context('environments') instance-attribute

_app_version = app.node.try_get_context('app_version') instance-attribute

_application_config = app.node.try_get_context('application') instance-attribute

_common_configs = app.node.try_get_context('common') instance-attribute

_env_config = self._all_envs[self._target_env] instance-attribute

_target_env = app.node.try_get_context('env').lower() instance-attribute

Functions

__init__(app, **kwargs)

Initialize the ApplicationHelper with CDK app context and configuration.

Reads and validates configuration from the CDK app context, including environment settings, application metadata, and common configurations. Ensures all required configuration sections are present and valid.

Parameters:

Name Type Description Default
app App

The CDK application instance containing context configuration

required

Raises:

Type Description
ValueError

If required configuration is missing or invalid: - 'env' context parameter not provided via command line - Environment value not in valid Environment enum list - 'environments' node missing from cdk.json - 'common' node missing from cdk.json - Target environment section missing from environments configuration

Source code in mare_aws_common_lib/helpers/application_helper.py
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
def __init__(self, app: App, **kwargs: Any) -> None:
    """
    Initialize the ApplicationHelper with CDK app context and configuration.

    Reads and validates configuration from the CDK app context, including
    environment settings, application metadata, and common configurations.
    Ensures all required configuration sections are present and valid.

    Args:
        app (App): The CDK application instance containing context configuration

    Raises:
        ValueError: If required configuration is missing or invalid:
            - 'env' context parameter not provided via command line
            - Environment value not in valid Environment enum list
            - 'environments' node missing from cdk.json
            - 'common' node missing from cdk.json
            - Target environment section missing from environments configuration        
    """
    self._target_env: str = app.node.try_get_context("env").lower()
    if not self._target_env:
        raise ValueError("env must be a passed via the command line with -c env=...")

    self._app_version: str = app.node.try_get_context("app_version")
    if not self._app_version:
        self._app_version = "latest"

    env_list: List[str] = Environment.list()
    if self._target_env.upper() not in env_list:
        raise ValueError(f"env value must be in {env_list}")

    self._all_envs: Dict[str, Any] = app.node.try_get_context("environments")
    if not self._all_envs:
        raise ValueError("cdk.json must contain a 'environments' node")

    self._common_configs: Dict[str, Any] = app.node.try_get_context("common")
    if not self._common_configs:
        raise ValueError("cdk.json must contain a 'common' node")

    self._env_config: Dict[str, Any] = self._all_envs[self._target_env]
    if not self._env_config:
        raise ValueError(f"cdk.json must contain in the 'environments' node a section for {self._target_env}")

    self._application_config: Dict[str, Any] = app.node.try_get_context("application")

_get_parameter_name_from_key(param_key, force_devops=False, with_leading_slash=False, env_name=None)

Generate a standardized Parameter Store parameter name from a key.

Creates parameter names following the organizational pattern: {domain}/{project}/{environment}/{param_key}

Parameters:

Name Type Description Default
param_key str

The base parameter key to convert

required
force_devops bool

Force use of 'devops' environment regardless of current target environment. Defaults to False.

False
with_leading_slash bool

Include leading slash in parameter name. Defaults to False.

False
env_name str

Override environment name. If not provided, uses target environment or 'devops' if force_devops is True.

None

Returns:

Name Type Description
str str

Formatted parameter name following organizational standards

Source code in mare_aws_common_lib/helpers/application_helper.py
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
def _get_parameter_name_from_key(self, param_key: str, force_devops: bool = False, 
                                 with_leading_slash: bool = False, env_name: str = None) -> str:
    """
    Generate a standardized Parameter Store parameter name from a key.

    Creates parameter names following the organizational pattern:
    {domain}/{project}/{environment}/{param_key}

    Args:
        param_key (str): The base parameter key to convert
        force_devops (bool, optional): Force use of 'devops' environment regardless
            of current target environment. Defaults to False.
        with_leading_slash (bool, optional): Include leading slash in parameter name.
            Defaults to False.
        env_name (str, optional): Override environment name. If not provided,
            uses target environment or 'devops' if force_devops is True.

    Returns:
        str: Formatted parameter name following organizational standards
    """
    target_env = "devops"
    if not force_devops:
        target_env = env_name if env_name is not None else self.get_target_env()
    param_name = f"{self.get_domain()}/{self.get_project()}/{target_env}/{param_key}".lower()

    if with_leading_slash and not param_name.startswith("/"):
        param_name = "/" + param_name

    return param_name

debug()

Check if debug mode is enabled in common configuration.

Returns:

Name Type Description
bool bool

True if debug mode is enabled, False otherwise

Source code in mare_aws_common_lib/helpers/application_helper.py
288
289
290
291
292
293
294
295
def debug(self) -> bool:
    """
    Check if debug mode is enabled in common configuration.

    Returns:
        bool: True if debug mode is enabled, False otherwise
    """
    return self._common_configs["debug"]

get_all_envs()

Get all environment configurations from cdk.json.

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: Dictionary containing all environment configurations with environment names as keys and their configurations as values

Source code in mare_aws_common_lib/helpers/application_helper.py
 98
 99
100
101
102
103
104
105
106
def get_all_envs(self) -> Dict[str, Any]:
    """
    Get all environment configurations from cdk.json.

    Returns:
        Dict[str, Any]: Dictionary containing all environment configurations
            with environment names as keys and their configurations as values
    """
    return self._all_envs

get_app_version()

Get the application version.

Returns:

Name Type Description
str str

The current application version string

Source code in mare_aws_common_lib/helpers/application_helper.py
120
121
122
123
124
125
126
127
def get_app_version(self) -> str:
    """
    Get the application version.

    Returns:
        str: The current application version string
    """
    return self._app_version

get_application_config()

Get the complete application configuration dictionary.

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: The full application configuration containing all parameters (domain, organization, project, ...)

Source code in mare_aws_common_lib/helpers/application_helper.py
129
130
131
132
133
134
135
136
137
def get_application_config(self) -> Dict[str, Any]:
    """
    Get the complete application configuration dictionary.

    Returns:
        Dict[str, Any]: The full application configuration containing
                    all parameters (domain, organization, project, ...)
    """
    return self._application_config

get_domain()

Get the application domain from configuration.

Returns:

Name Type Description
str str

The domain identifier for the application

Source code in mare_aws_common_lib/helpers/application_helper.py
139
140
141
142
143
144
145
146
def get_domain(self) -> str:
    """
    Get the application domain from configuration.

    Returns:
        str: The domain identifier for the application
    """
    return self._application_config["domain"]

get_from_common(name)

Retrieve a configuration value from the common configuration section.

Parameters:

Name Type Description Default
name str

Configuration key name in the common section

required

Returns:

Name Type Description
str str

The configuration value from common configuration

Raises:

Type Description
KeyError

If the key is not found in common configuration

Source code in mare_aws_common_lib/helpers/application_helper.py
255
256
257
258
259
260
261
262
263
264
265
266
267
268
def get_from_common(self, name: str) -> str:
    """
    Retrieve a configuration value from the common configuration section.

    Args:
        name (str): Configuration key name in the common section

    Returns:
        str: The configuration value from common configuration

    Raises:
        KeyError: If the key is not found in common configuration
    """
    return self._common_configs[name]

get_from_env(name)

Retrieve a configuration value from the current environment's configuration.

Supports both simple keys and nested keys using dot notation. For nested access, use dots to separate key levels (e.g., "database.host").

Parameters:

Name Type Description Default
name str

Configuration key name. Use dot notation for nested values (e.g., "vpc.id", "database.connection.timeout")

required

Returns:

Name Type Description
Any Any

The configuration value at the specified key path

Raises:

Type Description
KeyError

If the specified key path is not found in the environment configuration

Source code in mare_aws_common_lib/helpers/application_helper.py
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
def get_from_env(self, name: str) -> Any:
    """
    Retrieve a configuration value from the current environment's configuration.

    Supports both simple keys and nested keys using dot notation.
    For nested access, use dots to separate key levels (e.g., "database.host").

    Args:
        name (str): Configuration key name. Use dot notation for nested values
            (e.g., "vpc.id", "database.connection.timeout")

    Returns:
        Any: The configuration value at the specified key path

    Raises:
        KeyError: If the specified key path is not found in the environment configuration
    """
    error_message = f"Key '{name}' not found in environment configuration."

    if "." not in name:
        if name not in self._env_config:
            raise KeyError(error_message)
        return self._env_config[name]

    keys = name.split(".")
    value = self._env_config
    for key in keys:
        value = value.get(key)
        if value is None:
            raise KeyError(error_message)

    return value

get_organization()

Get the organization name from configuration.

Returns:

Name Type Description
str str

The organization identifier

Source code in mare_aws_common_lib/helpers/application_helper.py
148
149
150
151
152
153
154
155
def get_organization(self) -> str:
    """
    Get the organization name from configuration.

    Returns:
        str: The organization identifier
    """
    return self._application_config["organization"]

get_owner()

Get the project owner from configuration.

Returns:

Name Type Description
str str

The owner identifier for the project

Source code in mare_aws_common_lib/helpers/application_helper.py
166
167
168
169
170
171
172
173
def get_owner(self) -> str:
    """
    Get the project owner from configuration.

    Returns:
        str: The owner identifier for the project
    """
    return self._application_config["owner"]

get_parameter_value(scope, param_key, force_devops=False, env_name=None)

Get a parameter value during CDK synthesis phase (returns a token).

This method returns a CDK token that will be resolved during deployment. Use this when you need the parameter value in your CDK code but the actual value will be resolved at deploy time.

Parameters:

Name Type Description Default
scope Construct

CDK construct scope for parameter lookup

required
param_key str

Base parameter key (will be formatted with domain/project/env)

required
force_devops bool

Force lookup in 'devops' environment. Defaults to False.

False
env_name str

Override environment name for lookup. Defaults to None (uses target environment).

None

Returns:

Name Type Description
Any Any

CDK token that resolves to the parameter value during deployment

Note

This method is used during CDK synthesis and returns a token, not the actual value. For deployment-time value resolution, use get_parameter_value_deferred(). For synthesis-time actual values, use get_parameter_value_from_lookup().

Source code in mare_aws_common_lib/helpers/application_helper.py
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
def get_parameter_value(self, scope : Construct, param_key: str, force_devops: bool = False, env_name: str = None) -> Any:
    """
    Get a parameter value during CDK synthesis phase (returns a token).

    This method returns a CDK token that will be resolved during deployment.
    Use this when you need the parameter value in your CDK code but the actual
    value will be resolved at deploy time.

    Args:
        scope (Construct): CDK construct scope for parameter lookup
        param_key (str): Base parameter key (will be formatted with domain/project/env)
        force_devops (bool, optional): Force lookup in 'devops' environment.
            Defaults to False.
        env_name (str, optional): Override environment name for lookup.
            Defaults to None (uses target environment).

    Returns:
        Any: CDK token that resolves to the parameter value during deployment

    Note:
        This method is used during CDK synthesis and returns a token, not the actual value.
        For deployment-time value resolution, use get_parameter_value_deferred().
        For synthesis-time actual values, use get_parameter_value_from_lookup().
    """
    param_name = self._get_parameter_name_from_key(param_key, force_devops, True, env_name)
    value = ssm.StringParameter.value_for_string_parameter(scope, param_name)

    return value

get_parameter_value_deferred(scope, param_key, force_devops=False, id_suffix=None)

Get a parameter value during CDK deployment phase.

This method creates a reference to an existing parameter that will be resolved during deployment. Use this when you need to reference parameters created in other stacks or external processes.

Parameters:

Name Type Description Default
scope Construct

CDK construct scope for parameter reference

required
param_key str

Base parameter key (will be formatted with domain/project/env)

required
force_devops bool

Force lookup in 'devops' environment. Defaults to False.

False
id_suffix str

Additional suffix for construct ID uniqueness. Defaults to None.

None

Returns:

Name Type Description
Any Any

The parameter value that will be resolved during deployment

Note

This creates a construct reference to an existing parameter. The parameter must exist before deployment for this to work.

Source code in mare_aws_common_lib/helpers/application_helper.py
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
def get_parameter_value_deferred(self, scope: Construct, param_key: str, force_devops: bool = False, id_suffix: str = None) -> Any:
    """
    Get a parameter value during CDK deployment phase.

    This method creates a reference to an existing parameter that will be
    resolved during deployment. Use this when you need to reference parameters
    created in other stacks or external processes.

    Args:
        scope (Construct): CDK construct scope for parameter reference
        param_key (str): Base parameter key (will be formatted with domain/project/env)
        force_devops (bool, optional): Force lookup in 'devops' environment.
            Defaults to False.
        id_suffix (str, optional): Additional suffix for construct ID uniqueness.
            Defaults to None.

    Returns:
        Any: The parameter value that will be resolved during deployment

    Note:
        This creates a construct reference to an existing parameter.
        The parameter must exist before deployment for this to work.
    """
    param_name = self._get_parameter_name_from_key(param_key, force_devops, True)
    construct_id = param_key.replace("-", " ").replace("_", " ").title().replace(" ", "")
    if id_suffix is not None:
        construct_id = construct_id + id_suffix.replace("-", "").replace("_", "")
    value = ssm.StringParameter.from_string_parameter_attributes(
        scope, construct_id,
        parameter_name=param_name
    ).string_value

    return value

get_parameter_value_from_lookup(scope, param_key, force_devops=False)

Get the actual parameter value during CDK synthesis phase.

This method performs a real-time lookup and returns the actual parameter value (not a token) during synthesis. Use this when you need the actual value for synthesis-time decisions or computations.

Parameters:

Name Type Description Default
scope Construct

CDK construct scope for parameter lookup

required
param_key str

Base parameter key (will be formatted with domain/project/env)

required
force_devops bool

Force lookup in 'devops' environment. Defaults to False.

False

Returns:

Name Type Description
Any Any

The actual parameter value retrieved during synthesis

Warning

This method requires AWS credentials and network access during synthesis. The parameter must exist in Parameter Store before running cdk synth/deploy.

Note

Unlike get_parameter_value(), this returns the actual value, not a token. Use this for synthesis-time logic that depends on the parameter value.

Source code in mare_aws_common_lib/helpers/application_helper.py
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
def get_parameter_value_from_lookup(self, scope : Construct, param_key: str, force_devops: bool = False) -> Any:
    """
    Get the actual parameter value during CDK synthesis phase.

    This method performs a real-time lookup and returns the actual parameter value
    (not a token) during synthesis. Use this when you need the actual value for
    synthesis-time decisions or computations.

    Args:
        scope (Construct): CDK construct scope for parameter lookup
        param_key (str): Base parameter key (will be formatted with domain/project/env)
        force_devops (bool, optional): Force lookup in 'devops' environment.
            Defaults to False.

    Returns:
        Any: The actual parameter value retrieved during synthesis

    Warning:
        This method requires AWS credentials and network access during synthesis.
        The parameter must exist in Parameter Store before running cdk synth/deploy.

    Note:
        Unlike get_parameter_value(), this returns the actual value, not a token.
        Use this for synthesis-time logic that depends on the parameter value.
    """
    param_name = self._get_parameter_name_from_key(param_key, force_devops, True)
    value = ssm.StringParameter.value_from_lookup(scope, param_name)

    return value

get_project()

Get the project name from configuration.

Returns:

Name Type Description
str str

The project identifier

Source code in mare_aws_common_lib/helpers/application_helper.py
157
158
159
160
161
162
163
164
def get_project(self) -> str:
    """
    Get the project name from configuration.

    Returns:
        str: The project identifier
    """
    return self._application_config["project"]

get_target_env()

Get the current target environment name.

This is the environment specified via the CDK command line parameter (-c env=).

Returns:

Name Type Description
str str

The target environment name (e.g., 'dev', 'prod', 'test')

Source code in mare_aws_common_lib/helpers/application_helper.py
108
109
110
111
112
113
114
115
116
117
118
def get_target_env(self) -> str:
    """
    Get the current target environment name.

    This is the environment specified via the CDK command line parameter
    (-c env=<environment_name>).

    Returns:
        str: The target environment name (e.g., 'dev', 'prod', 'test')
    """
    return self._target_env

get_technology()

Get the technology stack identifier from configuration.

Returns:

Name Type Description
str str

The technology stack identifier

Source code in mare_aws_common_lib/helpers/application_helper.py
175
176
177
178
179
180
181
182
def get_technology(self) -> str:
    """
    Get the technology stack identifier from configuration.

    Returns:
        str: The technology stack identifier
    """
    return self._application_config["technology"]

get_vpc(cfn_name, scope)

Lookup and return the VPC for the current environment.

Uses CDK's VPC lookup functionality to find the VPC by ID.

Parameters:

Name Type Description Default
cfn_name str

CloudFormation logical name for the VPC construct

required
scope Construct

CDK construct scope for the VPC lookup

required

Returns:

Type Description
Vpc

ec2.Vpc: The VPC construct for the current environment

Raises:

Type Description
Exception

If VPC lookup fails or VPC ID is not found

Source code in mare_aws_common_lib/helpers/application_helper.py
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
def get_vpc(self, cfn_name: str, scope: Construct) -> ec2.Vpc:
    """
    Lookup and return the VPC for the current environment.

    Uses CDK's VPC lookup functionality to find the VPC by ID.

    Args:
        cfn_name (str): CloudFormation logical name for the VPC construct
        scope (Construct): CDK construct scope for the VPC lookup

    Returns:
        ec2.Vpc: The VPC construct for the current environment

    Raises:
        Exception: If VPC lookup fails or VPC ID is not found
    """
    return ec2.Vpc.from_lookup(scope, cfn_name, vpc_id=self.get_vpc_id())

get_vpc_id()

Get the VPC ID for the current target environment.

Returns:

Name Type Description
str str

The AWS VPC ID for the target environment

Raises:

Type Description
KeyError

If vpc.id is not configured for the target environment

Source code in mare_aws_common_lib/helpers/application_helper.py
184
185
186
187
188
189
190
191
192
193
194
def get_vpc_id(self) -> str:
    """
    Get the VPC ID for the current target environment.

    Returns:
        str: The AWS VPC ID for the target environment

    Raises:
        KeyError: If vpc.id is not configured for the target environment
    """
    return self._env_config["vpc"]["id"]

has_env_key(name)

Check if a configuration key exists in the current environment's configuration.

Supports both simple keys and nested keys using dot notation.

Parameters:

Name Type Description Default
name str

Configuration key name. Use dot notation for nested values (e.g., "vpc.id", "database.connection.timeout")

required

Returns:

Name Type Description
bool bool

True if the key exists, False otherwise

Source code in mare_aws_common_lib/helpers/application_helper.py
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
def has_env_key(self, name: str) -> bool:
    """
    Check if a configuration key exists in the current environment's configuration.

    Supports both simple keys and nested keys using dot notation.

    Args:
        name (str): Configuration key name. Use dot notation for nested values
            (e.g., "vpc.id", "database.connection.timeout")

    Returns:
        bool: True if the key exists, False otherwise
    """
    if "." not in name:
        return name in self._env_config

    keys = name.split(".")
    value = self._env_config

    for key in keys:
        if not isinstance(value, dict) or key not in value:
            return False
        value = value[key]

    return True

store_parameter(scope, param_key, param_value, tier=ssm.ParameterTier.STANDARD)

Create and store a parameter in AWS Systems Manager Parameter Store.

Creates a parameter with standardized naming convention and returns both the parameter construct and the generated parameter name for reference.

Parameters:

Name Type Description Default
scope Construct

CDK construct scope for parameter creation

required
param_key str

Base key for the parameter (will be formatted with domain/project/env)

required
param_value str

The value to store in the parameter

required
tier ParameterTier

Parameter Store tier. Defaults to ssm.ParameterTier.STANDARD.

STANDARD

Returns:

Type Description
Tuple[StringParameter, str]

Tuple[ssm.StringParameter, str]: Tuple containing: - The created StringParameter construct - The formatted parameter name that was used

Source code in mare_aws_common_lib/helpers/application_helper.py
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
def store_parameter(self, scope: Construct, param_key: str, param_value: str, 
                    tier: ssm.ParameterTier = ssm.ParameterTier.STANDARD) -> Tuple[ssm.StringParameter, str]:
    """
    Create and store a parameter in AWS Systems Manager Parameter Store.

    Creates a parameter with standardized naming convention and returns both
    the parameter construct and the generated parameter name for reference.

    Args:
        scope (Construct): CDK construct scope for parameter creation
        param_key (str): Base key for the parameter (will be formatted with domain/project/env)
        param_value (str): The value to store in the parameter
        tier (ssm.ParameterTier, optional): Parameter Store tier. 
            Defaults to ssm.ParameterTier.STANDARD.

    Returns:
        Tuple[ssm.StringParameter, str]: Tuple containing:
            - The created StringParameter construct
            - The formatted parameter name that was used
    """
    param_name = self._get_parameter_name_from_key(param_key)
    cfn_name = param_name.replace("/", "-").replace("_", "-")
    return (
        ssm.StringParameter(
            scope, 
            cfn_name,
            parameter_name=f"/{param_name}",
            string_value=param_value,
            tier=tier
        ),
        param_name
    )