API Reference

This section contains the complete API documentation auto-generated from source code docstrings.

Core Modules

SG Manager

class sg_provisioner.core.sg_manager.SgManager(config_file_name, action, dry_run=False, log_level='INFO', force=False, app_config=None)

Bases: object

Manages AWS Security Group provisioning and lifecycle operations using CloudFormation.

This class provides scenario-based security group management for enterprise workloads. It loads pre-built scenario templates, applies customer overrides, validates security rules, generates CloudFormation templates, and manages the complete security group lifecycle from creation to deletion.

Key Features:
  • Scenario-based security group generation (3-tier-web, 2-tier-web, etc.)

  • Customer overrides for ports, additional ingress/egress rules

  • Security validation (blocks dangerous patterns like open DB ports)

  • CloudFormation template generation with cross-tier SG references

  • Parameter Store integration for SG ID storage and VPC ID resolution

  • IAM policy generation for least-privilege access

  • Dry-run mode for safe testing

  • Force flag for mutating operations

Parameters:
sg_name

Name of the security group set being managed

Type:

str

region

AWS region for deployment

Type:

str

action

Current action being performed

Type:

str

dry_run

If True, simulates operations without making changes

Type:

bool

force

If True, forces mutating AWS operations without confirmation

Type:

bool

sg_stack_name

CloudFormation stack name

Type:

str

scenario

Selected scenario template name

Type:

str

vpc_source

How to resolve VPC ID (‘parameter-store’ or ‘direct’)

Type:

str

ec2_client

Boto3 EC2 client

cf_client

Boto3 CloudFormation client

ssm_client

Boto3 Systems Manager client

logger

Configured logger instance

Class Constants:

STACK_CREATE_WAITER_DELAY (int): Delay between stack creation checks (seconds) STACK_CREATE_WAITER_MAX_ATTEMPTS (int): Maximum stack creation wait attempts STACK_DELETE_WAITER_DELAY (int): Delay between stack deletion checks (seconds) STACK_DELETE_WAITER_MAX_ATTEMPTS (int): Maximum stack deletion wait attempts

DRIFT_POLL_INTERVAL (int): Seconds between drift status checks DRIFT_POLL_TIMEOUT (int): Total timeout for drift detection (10 minutes) CHANGESET_POLL_INTERVAL (int): Seconds between changeset status checks CHANGESET_MAX_ATTEMPTS (int): Maximum attempts for changeset creation

Example

>>> from sg_provisioner.core import SgManager
>>> manager = SgManager(
...     config_file_name='globalbank-prod-c001-us-west-2-sg.yaml',
...     action='create-prov-template',
...     dry_run=False
... )
>>> exit_code = manager.execute()

Note

  • Requires valid AWS credentials with appropriate IAM permissions

  • Configuration file must pass validation schema

  • Target VPC must exist before security group creation

  • Use dry_run=True to preview changes before execution

STACK_CREATE_WAITER_DELAY = 10
STACK_CREATE_WAITER_MAX_ATTEMPTS = 60
STACK_DELETE_WAITER_DELAY = 10
STACK_DELETE_WAITER_MAX_ATTEMPTS = 60
DRIFT_POLL_INTERVAL = 10
DRIFT_POLL_TIMEOUT = 600
CHANGESET_POLL_INTERVAL = 5
CHANGESET_MAX_ATTEMPTS = 60
__init__(config_file_name, action, dry_run=False, log_level='INFO', force=False, app_config=None)

Initializes class members from config file and parameters.

Parameters:
  • config_file_name (str) – Name of the configuration file.

  • action (str) – Action to be performed.

  • dry_run (bool) – Dry run flag, if True no changes are made.

  • log_level (str) – Logging level for the operation.

  • force (bool) – If True, forces mutating AWS operations without confirmation.

  • app_config (AppConfig) – Application configuration object (AppConfig instance).

execute()

Executes the specified action on the SG.

Returns:

0 for success, 1 for failure

Return type:

int

Configuration

Configuration Loader

class sg_provisioner.config.loader.AppConfig(config_dict)

Bases: object

Application configuration with embedded defaults.

Loads configuration from YAML files and provides convenient access to configuration values with automatic path resolution.

Parameters:

config_dict (Dict[str, Any])

__init__(config_dict)
Parameters:

config_dict (Dict[str, Any])

get(key_path, default=None)

Gets a config value using dot notation.

Parameters:
  • key_path (str) – Dot-separated path (e.g., ‘directories.configs_dir’)

  • default (Any) – Default value if key not found

Return type:

Any

get_directory(dir_name)

Gets a directory path as a Path object.

Parameters:

dir_name (str) – Directory name (configs_dir, reports_dir, etc.)

Raises:

ValueError – If directory not configured

Return type:

Path

sg_provisioner.config.loader.load_app_config(custom_config_path=None)

Loads and returns application configuration.

Resolution order: 1. Custom config file (if provided via –app-config) 2. Embedded default config (always available)

Raises:
Parameters:

custom_config_path (str | None)

Return type:

AppConfig

Utilities

HTML Generator

HTML documentation generator for SG provisioning.

Provides post-deployment reporting:

sg_provisioner.utils.html_generator.generate_deployment_documentation(config_file, stack_name, region, stack_info, output_path)

Generate CONFIDENTIAL HTML report for SG deployment with live resource IDs.

Parameters:
  • config_file (str) – Path to configuration YAML file.

  • stack_name (str) – CloudFormation stack name.

  • region (str) – AWS region.

  • stack_info (Dict[str, Any]) – Stack information from describe_stacks.

  • output_path (str) – Path where HTML file should be saved.

Returns:

Path to generated HTML file.

Return type:

str

Review Report

Pre-deployment review report generator for SG provisioning.

Produces two artifacts after overrides are applied and validation passes:

sg_provisioner.utils.review_report.generate_review_yaml(scenario, output_path)

Serialize the final merged Scenario to YAML for diffing against the original.

Parameters:
  • scenario (Scenario) – Scenario object after overrides have been applied.

  • output_path (str) – Filesystem path where the YAML file should be saved.

Returns:

Path to the generated YAML file.

Return type:

str

sg_provisioner.utils.review_report.generate_review_html(scenario, overrides, sg_name, output_path)

Generate an HTML pre-deployment review report with override highlighting.

Parameters:
  • scenario (Scenario) – Scenario object after overrides have been applied.

  • overrides (Optional[Dict[str, Any]]) – Original overrides dict (used to detect what changed).

  • sg_name (str) – Security group base name.

  • output_path (str) – Filesystem path where the HTML file should be saved.

Returns:

Path to the generated HTML file.

Return type:

str

CloudFormation Generator

class sg_provisioner.generators.cfn_generator.CfnGenerator(scenario, config, sg_name_override=None)

Bases: object

Generates CloudFormation templates from a validated Scenario object and customer configuration.

Produces a template containing:
  • One AWS::EC2::SecurityGroup per tier

  • One AWS::SSM::Parameter per tier (stores SG ID for downstream consumers)

  • Outputs exporting each SG ID

Expects a Scenario with overrides already applied (via ScenarioLoader.apply_overrides). Cross-tier references (source_tier/destination_tier) are resolved to CloudFormation !Ref expressions. Rules with multiple CIDRs are expanded to individual CFN entries.

Parameters:
  • scenario (Scenario)

  • config (Dict[str, Any])

  • sg_name_override (str)

__init__(scenario, config, sg_name_override=None)
Parameters:
  • scenario (Scenario) – Final Scenario object (overrides already applied).

  • config (Dict[str, Any]) – Customer configuration dict (client, environment, security_groups, tags).

  • sg_name_override (str) – Optional override for SG name used in SSM paths (e.g., for test-deploy).

generate()

Orchestrates template generation. Returns the complete CloudFormation template as a dict ready for YAML serialization.

Return type:

Dict[str, Any]

Scenario Loader

class sg_provisioner.scenarios.loader.ScenarioLoader

Bases: object

Loads scenario definitions from YAML files and applies customer-specific overrides.

list_scenarios(schemas_dir)

Scans the directory for YAML scenarios and returns their metadata.

Parameters:

schemas_dir (Path) – Path to the directory containing scenario YAML files.

Returns:

List of dictionaries with ‘name’ and ‘description’ keys.

Return type:

List[Dict[str, str]]

load_scenario(name, schemas_dir)

Loads a YAML file and maps it into Scenario/Tier/SecurityGroup dataclasses.

Parameters:
  • name (str) – Name of the scenario (without .yaml extension).

  • schemas_dir (Path) – Directory where scenario YAML files are stored.

Returns:

Fully constructed Scenario object.

Return type:

Scenario

apply_overrides(scenario, overrides)

Applies customer overrides using immutable replace pattern. - Replaces port on matching ingress/egress rules via dataclasses.replace(). - Appends additional_ingress/additional_egress rules if specified.

Parameters:
  • scenario (Scenario) – Original scenario object.

  • overrides (Dict[str, Any]) – Nested dictionary of overrides per tier.

Returns:

Updated scenario with overrides applied.

Return type:

Scenario

See docs/OVERRIDE_CONTRACT.md for the full override dict structure. All three keys (port_overrides, additional_ingress, additional_egress) are optional per tier. Tiers not present in the dict are left unchanged.

Scenario Validator

class sg_provisioner.scenarios.validator.ValidationIssue(level, message)

Bases: tuple

level

Alias for field number 0

message

Alias for field number 1

class sg_provisioner.scenarios.validator.ScenarioValidator

Bases: object

WARNING = 'WARNING'
ERROR = 'ERROR'
DB_PORTS = {1433, 1521, 3306, 5432, 5439, 27017}
ANY_IPV4 = '0.0.0.0/0'
ANY_IPV6 = '::/0'
validate(scenario)
Parameters:

scenario (Scenario)

Return type:

List[ValidationIssue]

Data Models

exception sg_provisioner.models.security_group.SecurityRuleError

Bases: ValueError

Custom exception for Security Group validation errors.

exception sg_provisioner.models.security_group.SecurityGroupNameError

Bases: ValueError

Custom exception for Security Group naming violations.

class sg_provisioner.models.security_group.SecurityGroupRule(protocol, ipv4_cidrs=<factory>, ipv6_cidrs=<factory>, description='', port=None, port_range=None, source=None, source_tier=None, destination=None, destination_tier=None)

Bases: object

This class is a data container used to define the specific traffic parameters for a Network Security Group rule. A security group acts as a virtual firewall for your instances to control inbound and outbound traffic. It specifies what type of traffic is allowed or denied based on port ranges and source/destination IP addresses.

Parameters:
  • protocol (str)

  • ipv4_cidrs (List[str])

  • ipv6_cidrs (List[str])

  • description (str)

  • port (int | None)

  • port_range (str | None)

  • source (str | None)

  • source_tier (str | None)

  • destination (str | None)

  • destination_tier (str | None)

protocol

The protocol to allow (e.g., ‘tcp’, ‘udp’, ‘icmp’).

Type:

str

ipv4_cidrs

List of IPv4 CIDR blocks (e.g., ‘10.0.0.0/16’).

Type:

List[str]

ipv6_cidrs

List of IPv6 CIDR blocks (e.g., ‘2001:db8::/32’). Schema-ready for v1.0, implementation in v2.0.

Type:

List[str]

description

Description of the rule.

Type:

str

port

Single port number to allow.

Type:

Optional[int]

port_range

Port range in ‘start-end’ format (e.g., ‘1024-65535’).

Type:

Optional[str]

source

Specific source CIDR block (alternative to ipv4_cidrs/ipv6_cidrs).

Type:

Optional[str]

source_tier

Tier name reference (e.g., ‘web’, ‘app’) resolved at generation time.

Type:

Optional[str]

destination

Specific destination CIDR block (alternative to ipv4_cidrs/ipv6_cidrs).

Type:

Optional[str]

destination_tier

Tier name reference (e.g., ‘web’, ‘app’) resolved at generation time.

Type:

Optional[str]

from_port

The starting port of the rule (computed).

Type:

int

to_port

The ending port of the rule (computed).

Type:

int

Example

>>> from sg_provisioner.models.security_group import SecurityGroupRule
>>> rule = SecurityGroupRule(
...     protocol='tcp',
...     port=80,
...     ipv4_cidrs=['0.0.0.0/0'],
...     description='Allow HTTP from anywhere'
... )
protocol: str
ipv4_cidrs: List[str]
ipv6_cidrs: List[str]
description: str = ''
port: int | None = None
port_range: str | None = None
source: str | None = None
source_tier: str | None = None
destination: str | None = None
destination_tier: str | None = None
from_port: int
to_port: int
__init__(protocol, ipv4_cidrs=<factory>, ipv6_cidrs=<factory>, description='', port=None, port_range=None, source=None, source_tier=None, destination=None, destination_tier=None)
Parameters:
  • protocol (str)

  • ipv4_cidrs (List[str])

  • ipv6_cidrs (List[str])

  • description (str)

  • port (int | None)

  • port_range (str | None)

  • source (str | None)

  • source_tier (str | None)

  • destination (str | None)

  • destination_tier (str | None)

Return type:

None

class sg_provisioner.models.security_group.SecurityGroup(name_suffix, description, ingress=<factory>, egress=<factory>, tags=<factory>)

Bases: object

Data class representing a Security Group configuration.

Parameters:
  • name_suffix (str)

  • description (str)

  • ingress (List[SecurityGroupRule])

  • egress (List[SecurityGroupRule])

  • tags (dict[str, str])

name_suffix

Suffix to append to the VPC name for the SG name.

Type:

str

description

Description of the security group’s purpose.

Type:

str

ingress

List of ingress rules.

Type:

List[SecurityGroupRule]

egress

List of egress rules.

Type:

List[SecurityGroupRule]

tags

Additional tags for the security group.

Type:

dict[str, str]

name_suffix: str
description: str
ingress: List[SecurityGroupRule]
egress: List[SecurityGroupRule]
tags: dict[str, str]
get_full_name(vpc_stem)

Constructs the full security group name based on VPC stem and suffix.

Parameters:

vpc_stem (str) – The base name of the VPC.

Returns:

The full security group name.

Return type:

str

get_combined_tags(global_tags)

Merges global metadata with this specific SG’s tags. Global tags are applied first, then specific tags are added or overridden. Specific SG tags will override global tags if keys collide.

Parameters:

global_tags (dict[str, str]) – Global tags to merge.

Returns:

Combined tags dictionary.

Return type:

dict[str, str]

__init__(name_suffix, description, ingress=<factory>, egress=<factory>, tags=<factory>)
Parameters:
  • name_suffix (str)

  • description (str)

  • ingress (List[SecurityGroupRule])

  • egress (List[SecurityGroupRule])

  • tags (dict[str, str])

Return type:

None

License

License Validator

class sg_provisioner.license.validator.LicenseValidator

Bases: object

Validates product licenses against the AWS Marketplace License Manager.

This class handles the end-to-end license verification workflow, including secure communication with AWS APIs to confirm customer entitlements. To optimize performance and minimize latency, it employs an in-memory caching mechanism, reducing API calls for frequently validated tokens or customers.

product_sku

AWS Marketplace product sku to validate against.

Type:

str

region

AWS region for the Marketplace API.

Type:

str

license_client

Boto3 client for AWS Marketplace License Manager.

key_fingerprint

The fingerprint of the public key used for license validation.

entitlement_name

The name of the entitlement to check for in the AWS License Manager.

license_cache_file

Path to the local cache file.

Type:

str

cache_duration

Duration for which the cache is considered valid (hours).

Type:

timedelta

Integration Workflow:
  1. Checks cache for active, unexpired validation result.

  2. If missing/expired, calls CheckoutLicense API.

  3. Validates product SKU and entitlement status.

  4. Updates cache and returns validation status.

__init__()

Initialize the LicenseValidator with AWS Marketplace configuration.

Reads configuration from environment variables and sets up the AWS License Manager Client for license validation.

Environment Variables:

MARKETPLACE_PRODUCT_SKU: AWS Marketplace product SKU (required for validation) AWS_REGION: AWS region for Marketplace API (default: ‘us-east-1’)

verify_aws_marketplace_subscription()

Validate AWS Marketplace subscription via License Manager CheckoutLicense API.

Returns:

True if valid license, False otherwise

Return type:

bool

CLI Interface

class sg_provisioner.cli.SgProvisionerCLI

Bases: BaseCLI

CLI for SG Provisioner Tool.

Extends BaseCLI to implement SG-specific actions and arguments. Supports 12 actions grouped by safety level:

  • Local: validate-config, create-policy, create-prov-template, validate-prov-template, create-review-report, list-scenarios, show-scenario

  • Read-only: show-changes, check-drift

  • Mutating: test-deploy, create-security-groups, delete-security-groups

Includes AWS Marketplace license validation before executing any actions.

__init__()

Initialize the SG Provisioner CLI.

is_action_required()

Determine if an action argument is required for this CLI.

Returns:

Always True for this CLI

Return type:

bool

get_actions()

Return the list of valid actions for the SG Provisioner CLI.

Returns:

List of action strings

Return type:

List[str]

get_actions_help()

Return help text describing all available actions.

Returns:

Formatted help text for all SG actions

Return type:

str

get_manager_class()

Return the manager class for this CLI.

Returns:

SgManager class reference

Return type:

Type[Any]

get_example_usage()

Return example usage instructions.

Detects Docker environment via /.dockerenv or /proc/1/cgroup and adjusts command examples accordingly.

Returns:

Example usage string with Docker or native CLI commands

Return type:

str

add_custom_arguments(parser)

Add SG Provisioner-specific CLI arguments.

Parameters:

parser (argparse.ArgumentParser) – The argparse parser to add arguments to.

Return type:

None

create_manager_instance(args)

Create a new SgManager instance.

Parameters:

args (argparse.Namespace) – Parsed command-line arguments.

Returns:

Instance initialized with CLI arguments and app config.

Return type:

SgManager

requires_force(action)

Determine if an action requires the --force flag.

Parameters:

action (str) – The action being performed.

Returns:

True for mutating AWS operations (create-security-groups, delete-security-groups).

Return type:

bool

sg_provisioner.cli.main()

Entry point for SG Provisioner CLI.

Validates AWS Marketplace license before running the CLI. Exits with code 1 if license validation fails.