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:
objectManages 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
- 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).
Configuration¶
Configuration Loader¶
- class sg_provisioner.config.loader.AppConfig(config_dict)¶
Bases:
objectApplication configuration with embedded defaults.
Loads configuration from YAML files and provides convenient access to configuration values with automatic path resolution.
- get(key_path, default=None)¶
Gets a config value using dot notation.
- 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:
- 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:
FileNotFoundError – If custom config specified but not found
ValueError – If config file is invalid YAML
- Parameters:
custom_config_path (str | None)
- Return type:
Utilities¶
HTML Generator¶
HTML documentation generator for SG provisioning.
Provides post-deployment reporting:
generate_deployment_documentation()— CONFIDENTIAL stack report with live resource IDs
- 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:
- Returns:
Path to generated HTML file.
- Return type:
Review Report¶
Pre-deployment review report generator for SG provisioning.
Produces two artifacts after overrides are applied and validation passes:
generate_review_yaml()— final merged scenario as YAML (diffable against original)generate_review_html()— readable HTML report with override highlighting
- sg_provisioner.utils.review_report.generate_review_yaml(scenario, output_path)¶
Serialize the final merged Scenario to YAML for diffing against the original.
- 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:
- Returns:
Path to the generated HTML file.
- Return type:
CloudFormation Generator¶
- class sg_provisioner.generators.cfn_generator.CfnGenerator(scenario, config, sg_name_override=None)¶
Bases:
objectGenerates 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.
- __init__(scenario, config, sg_name_override=None)¶
Scenario Loader¶
- class sg_provisioner.scenarios.loader.ScenarioLoader¶
Bases:
objectLoads scenario definitions from YAML files and applies customer-specific overrides.
- list_scenarios(schemas_dir)¶
Scans the directory for YAML scenarios and returns their metadata.
- 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.mdfor 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¶
Data Models¶
- exception sg_provisioner.models.security_group.SecurityRuleError
Bases:
ValueErrorCustom exception for Security Group validation errors.
- exception sg_provisioner.models.security_group.SecurityGroupNameError
Bases:
ValueErrorCustom 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:
objectThis 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
The protocol to allow (e.g., ‘tcp’, ‘udp’, ‘icmp’).
- Type:
- 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:
- 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:
- to_port
The ending port of the rule (computed).
- Type:
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
- description: str = ''
- 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)
- class sg_provisioner.models.security_group.SecurityGroup(name_suffix, description, ingress=<factory>, egress=<factory>, tags=<factory>)
Bases:
objectData class representing a Security Group configuration.
- Parameters:
- name_suffix
Suffix to append to the VPC name for the SG name.
- Type:
- description
Description of the security group’s purpose.
- Type:
- ingress
List of ingress rules.
- Type:
List[SecurityGroupRule]
- egress
List of egress rules.
- Type:
List[SecurityGroupRule]
- name_suffix: str
- description: str
- ingress: List[SecurityGroupRule]
- egress: List[SecurityGroupRule]
- get_full_name(vpc_stem)
Constructs the full security group name based on VPC stem and suffix.
- 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.
License¶
License Validator¶
- class sg_provisioner.license.validator.LicenseValidator¶
Bases:
objectValidates 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.
- 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.
- cache_duration¶
Duration for which the cache is considered valid (hours).
- Type:
timedelta
- Integration Workflow:
Checks cache for active, unexpired validation result.
If missing/expired, calls CheckoutLicense API.
Validates product SKU and entitlement status.
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’)
CLI Interface¶
- class sg_provisioner.cli.SgProvisionerCLI¶
Bases:
BaseCLICLI for SG Provisioner Tool.
Extends
BaseCLIto 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:
- get_actions()¶
Return the list of valid actions for the SG Provisioner CLI.
- get_actions_help()¶
Return help text describing all available actions.
- Returns:
Formatted help text for all SG actions
- Return type:
- get_manager_class()¶
Return the manager class for this CLI.
- get_example_usage()¶
Return example usage instructions.
Detects Docker environment via
/.dockerenvor/proc/1/cgroupand adjusts command examples accordingly.- Returns:
Example usage string with Docker or native CLI commands
- Return type:
- 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
SgManagerinstance.- Parameters:
args (argparse.Namespace) – Parsed command-line arguments.
- Returns:
Instance initialized with CLI arguments and app config.
- Return type:
- 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.