A comprehensive collection of production-ready AWS Systems Manager (SSM) Automation documents for streamlining AWS operations, security compliance, and cost optimization.
This repository provides battle-tested SSM Automation documents that help DevOps teams, system administrators, and cloud engineers automate common AWS management tasks. All scripts follow AWS best practices and are designed to be idempotent, secure, and easily customizable.
- 🔄 Automation First: Reduce manual operations and human error
- 🔒 Security by Default: Built-in security best practices and compliance checks
- 💰 Cost Optimization: Identify and remediate cost inefficiencies
- 🌍 Multi-Account Support: Manage resources across multiple AWS accounts
- 📊 Comprehensive Logging: Detailed execution logs and audit trails
- 🧩 Modular Design: Reusable components and shared libraries
- Quick Start
- Available Automation Scripts
- Installation
- Usage Examples
- Architecture
- Best Practices
- Development
- Contributing
- Support
# 1. Clone the repository
git clone https://github.com/thomasvincent/aws-ssm-automation-scripts.git
# 2. Register an SSM document
aws ssm create-document \
--name "EnableS3Encryption" \
--document-type "Automation" \
--content file://s3_encryption.yaml
# 3. Execute the automation
aws ssm start-automation-execution \
--document-name "EnableS3Encryption" \
--parameters '{"BucketName":["my-bucket"],"KMSMasterKey":["arn:aws:kms:us-east-1:123456789012:key/12345678-1234-1234-1234-123456789012"]}'File: cloudfront_distribution_management.yaml
Comprehensive CloudFront distribution lifecycle management including creation, updates, invalidations, and security configuration.
Key Features:
- Create and configure new distributions
- Update existing distribution settings
- Perform cache invalidations
- Configure security policies and geo-restrictions
- Manage custom headers and behaviors
View Parameters
Operation: The operation to perform (Create, Update, Invalidate, UpdateSecurityConfig)DistributionId: ID of existing distribution (required for updates)OriginDomainName: Origin domain name (required for creation)PriceClass: CloudFront price classViewerCertificateConfig: SSL/TLS certificate configurationGeoRestriction: Geographic access restrictions- [See full parameter list in script]
File: ec2_instance_patching.yaml
Automated patching solution for EC2 instances with configurable reboot options and severity filters.
Key Features:
- Selective patching based on severity levels
- Optional automatic reboot after patching
- Parallel patching support
- Detailed patch compliance reporting
View Parameters
InstanceIds: List of EC2 instance IDs to patchRebootOption: Whether to reboot after patching (NoReboot, RebootIfNeeded)PatchSeverity: Minimum severity level (Critical, Important, Medium, Low)AutomationAssumeRole: IAM role for automation execution
File: security_group_audit.yaml
Comprehensive security group auditing and automated remediation for compliance.
Key Features:
- Identify overly permissive rules (0.0.0.0/0)
- Automatic remediation of high-risk ports
- Compliance reporting
- Exclusion list support
- VPC-specific auditing
View Parameters
SecurityGroupIds: Specific security groups to audit (optional)VpcIds: VPCs to audit (optional)RemediationMode: Audit or RemediateRemediateOpenPorts: Ports to close if open to internetExcludedSecurityGroups: Security groups to exclude
File: s3_encryption.yaml
Enable KMS encryption on S3 buckets with verification.
Key Features:
- Apply KMS encryption to existing buckets
- Verify encryption status
- Support for customer-managed KMS keys
- Bucket existence validation
File: cost_optimization_recommendations.yaml
Identify and report cost optimization opportunities across your AWS infrastructure.
Key Features:
- Identify idle and underutilized resources
- Generate detailed HTML reports
- SNS notifications for findings
- Multi-resource type analysis (EC2, EBS, RDS, etc.)
- Customizable utilization thresholds
View Parameters
ResourceTypes: Resources to analyze (EC2, EBS, S3, RDS)IdleDaysThreshold: Days of inactivity to consider idleLowUtilizationThreshold: CPU threshold for underutilizationGenerateReport: Generate HTML reportReportS3Bucket: S3 bucket for reports
File: attach_policies_to_role.yaml
Streamline IAM role configuration by attaching multiple policies.
Key Features:
- Attach AWS managed policies
- Attach customer managed policies
- Bulk policy attachment
- Validation and error handling
File: lambda_function_management.yaml
Complete Lambda function lifecycle management.
Key Features:
- Create new functions from S3 packages
- Update function code and configuration
- Manage aliases and versions
- Configure environment variables
- Set reserved concurrent executions
View Parameters
Operation: Operation type (Create, Update, Delete, AddAlias)FunctionName: Lambda function nameS3Bucket: Deployment package bucketS3Key: Deployment package keyHandler: Function handlerRuntime: Lambda runtimeMemorySize: Memory allocation (MB)Timeout: Execution timeout (seconds)
File: maintenance_window_setup.yaml
Create and configure SSM Maintenance Windows for scheduled operations.
Key Features:
- Flexible scheduling with cron expressions
- Target registration (instances or tags)
- Task configuration
- Service role management
File: cross_account_resource_management.yaml
Manage resources across multiple AWS accounts from a central location.
Key Features:
- Assume role across accounts
- Parallel account processing
- Multi-region support
- Comprehensive error handling
- SNS notifications
View Parameters
Operation: Cross-account operation typeTargetAccounts: List of AWS account IDsTargetRegions: AWS regions to targetCrossAccountRoleName: Role name to assumeMaxConcurrentAccounts: Parallel execution limit
File: create_and_tag_resources.yaml
Standardized resource creation with consistent tagging strategy.
Key Features:
- Support multiple resource types
- Enforce tagging standards
- Cost center allocation
- Environment classification
- Department and project tracking
The repository includes reusable Python modules in shared/python/:
- General AWS utility functions
- Logging configuration
- Tag creation and management
- Parameter validation
- Error handling utilities
- Configuration from SSM Parameter Store
- S3-based configuration management
- Environment-specific settings
- Dynamic configuration updates
- Security group analysis
- Encryption status checks
- Compliance validation
- Security best practices enforcement
# Register all documents at once
for file in *.yaml; do
name=$(basename "$file" .yaml)
aws ssm create-document \
--name "$name" \
--document-type "Automation" \
--content "file://$file"
doneResources:
S3EncryptionDocument:
Type: AWS::SSM::Document
Properties:
Name: EnableS3Encryption
DocumentType: Automation
Content: !Sub |
${file(s3_encryption.yaml)}resource "aws_ssm_document" "s3_encryption" {
name = "EnableS3Encryption"
document_type = "Automation"
content = file("${path.module}/s3_encryption.yaml")
}aws ssm start-automation-execution \
--document-name "s3_encryption" \
--parameters '{
"BucketName": ["my-data-bucket"],
"KMSMasterKey": ["arn:aws:kms:us-east-1:123456789012:key/12345678-1234-1234-1234-123456789012"]
}'aws ssm start-automation-execution \
--document-name "ec2_instance_patching" \
--parameters '{
"InstanceIds": ["i-1234567890abcdef0", "i-0987654321fedcba0"],
"RebootOption": ["RebootIfNeeded"],
"PatchSeverity": ["Critical"]
}'aws ssm start-automation-execution \
--document-name "security_group_audit" \
--parameters '{
"RemediationMode": ["Audit"],
"RemediateOpenPorts": ["22", "3389", "3306"],
"VpcIds": ["vpc-12345678"]
}'aws ssm start-automation-execution \
--document-name "cross_account_resource_management" \
--parameters '{
"Operation": ["TagResources"],
"TargetAccounts": ["111111111111", "222222222222"],
"CrossAccountRoleName": ["SSMCrossAccountRole"],
"TagKey": ["Environment"],
"TagValue": ["Production"]
}'aws-ssm-automation-scripts/
├── *.yaml # SSM Automation documents
├── shared/ # Shared modules
│ └── python/ # Python helper modules
│ ├── aws_helpers.py
│ ├── config_manager.py
│ └── security_helpers.py
├── .github/ # GitHub Actions workflows
│ └── workflows/
│ ├── validate.yml # Document validation
│ ├── security-scan.yml # Security scanning
│ └── release.yml # Automated releases
└── tests/ # Test scripts (if applicable)
graph TD
A[User/Application] -->|Initiates| B[SSM Automation]
B --> C{Document Type}
C -->|EC2| D[Instance Operations]
C -->|S3| E[Bucket Operations]
C -->|Security| F[Compliance Checks]
C -->|Cross-Account| G[Assume Role]
G --> H[Target Account Operations]
D --> I[Logging/Reporting]
E --> I
F --> I
H --> I
I --> J[CloudWatch Logs]
I --> K[S3 Reports]
I --> L[SNS Notifications]
Always use least privilege principles:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"ssm:StartAutomationExecution",
"ssm:GetAutomationExecution"
],
"Resource": "*"
},
{
"Effect": "Allow",
"Action": "iam:PassRole",
"Resource": "arn:aws:iam::*:role/SSMAutomationRole"
}
]
}All documents include proper error handling:
onFailureactions (Abort, Continue)- Retry logic where appropriate
- Detailed error logging
Implement consistent tagging:
Tags:
Environment: Production
Department: DevOps
Project: Infrastructure
Owner: team@example.com
CostCenter: CC-12345Test in non-production first:
- Use sandbox/development accounts
- Target test resources
- Review execution logs
- Validate results
- Use the template structure:
---
description: Clear description of what this document does
schemaVersion: '0.3'
assumeRole: '{{ AutomationAssumeRole }}'
parameters:
# Define all parameters
mainSteps:
# Define automation steps-
Follow naming conventions:
- Use snake_case for file names
- Use PascalCase for parameters
- Use camelCase for step names
-
Include comprehensive documentation
# Validate YAML syntax
python -c "import yaml; yaml.safe_load(open('document.yaml'))"
# Test with dry-run (if supported)
aws ssm start-automation-execution \
--document-name "TestDocument" \
--parameters '{"DryRun":["true"]}'We welcome contributions! Please see our Contributing Guide for details.
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-automation) - Commit your changes (
git commit -m 'Add amazing automation') - Push to the branch (
git push origin feature/amazing-automation) - Open a Pull Request
- Follow existing document structure
- Include comprehensive parameter descriptions
- Add usage examples to README
- Ensure all YAML is valid
- Test thoroughly before submitting
- Validation: All YAML documents are validated on push
- Security Scanning: CodeQL scans for security issues
- Automated Testing: Integration tests in sandbox environment
- Release Management: Semantic versioning with automated releases
- Dependency Updates: Dependabot keeps dependencies current
Releases follow semantic versioning (MAJOR.MINOR.PATCH):
- MAJOR: Breaking changes to document parameters
- MINOR: New documents or features
- PATCH: Bug fixes and minor improvements
All executions are logged to CloudWatch:
/aws/ssm/automation/{document-name}/{execution-id}
- Execution success/failure rates
- Average execution duration
- Resource modification counts
- Cost optimization savings
- Issues: GitHub Issues
- Discussions: GitHub Discussions
- Security Issues: See SECURITY.md
This project is licensed under the MIT License - see the LICENSE file for details.
- AWS Systems Manager team for the automation framework
- Contributors and users of these scripts
- Open source community for inspiration and best practices
- AWS Organizations integration
- Cost optimization automation workflows
- Disaster recovery automation
- Compliance reporting dashboards
- Integration with AWS Config rules
- Slack/Teams notifications
- Terraform module wrapper
- Enhanced cross-region support
Made with ❤️ by the DevOps community
For commercial support or custom automation development, please contact Thomas Vincent.