Skip to content

Instantly share code, notes, and snippets.

View atheiman's full-sized avatar
😬

Austin Heiman atheiman

😬
View GitHub Profile
@atheiman
atheiman / config_evaluation.py
Last active December 4, 2024 01:19
AWS Config custom rule for resource tag compliance evaluation. Deployed as CloudFormation stacks.
# See documented events sent by Config here: https://docs.aws.amazon.com/config/latest/developerguide/evaluate-config_develop-rules_example-events.html
#
# It is much easier to write evaluations for rules using ConfigurationItemChangeNotification and
# OversizedConfigurationItemChangeNotification. These notifications include the resource as recorded
# by Config. The Lambda function can review the resource config json and submit an evaluation for
# the resource.
#
# ScheduledNotification events are not specific to a resource, the event only includes
# the account id and rule name. Lambda functions must list all the resources in the account using
# service apis, call the appropriate apis to evaluate the resources config, and then submit
@atheiman
atheiman / docker-image-share.sh
Created May 21, 2024 01:55
Package and share docker image
# Package docker image to .tar.gz to share to another machine
docker pull alpine
docker save alpine | gzip > alpine.tar.gz
# Load docker image from .tar.gz
docker load < alpine.tar.gz
# Show loaded image
docker image ls alpine
# REPOSITORY TAG IMAGE ID CREATED SIZE
@atheiman
atheiman / boto3_all_accounts.py
Last active August 16, 2024 21:15
Run boto3 in a loop across all organization member AWS accounts
import json
import boto3
import os
import traceback as tb
if boto3.session.Session().region_name.startswith("us-gov-"):
partition = "aws-us-gov"
regions = ["us-gov-west-1", "us-gov-east-1"]
else:
partition = "aws"
@atheiman
atheiman / aws_switch_role_bookmark_generator.py
Last active June 30, 2025 21:03
AWS organization switch role (assume role) bookmark generator - outputs html to stdout that can be saved to a .html file and imported into browser bookmarks.
#!/usr/bin/env python3
import boto3
import os
# Example usage from a bash shell:
# PREFIX='AWS COMM' AWS_PROFILE=comm-mgmt ROLE_NAME=AWSControlTowerExecution python ./aws_switch_role_bookmark_generator.py > "./aws-switch-role-bookmarks.html"
# Environment variables for configuration
role_name = os.environ.get("ROLE_NAME", "OrganizationAccountAccessRole")
@atheiman
atheiman / tag_dedicated_hosts.py
Last active February 16, 2024 01:38
Tag AWS EC2 dedicated hosts allocated by a License Manager host resource group. This code can be run as a Lambda function or directly as a Python script.
#!/usr/bin/env python
import json
import boto3
default_region = boto3.Session().region_name
if default_region.startswith("us-gov-"):
partition = "aws-us-gov"
regions = ["us-gov-west-1", "us-gov-east-1"]
else:
@atheiman
atheiman / security_hub_findings_query.py
Last active May 21, 2024 12:00
Security Hub findings querying and batch updating with boto3. Suppress sample findings (i.e. from GuardDuty "CreateSampleFindings").
#!/usr/bin/env python
import boto3
import json
sechub = boto3.client("securityhub")
sts = boto3.client("sts")
caller_arn = sts.get_caller_identity()["Arn"]
print(caller_arn)
@atheiman
atheiman / template.yml
Last active June 18, 2024 18:32
AWS Config custom rule to evaluate AWS account tags
# aws cloudformation deploy \
# --profile mgmt \
# --template-file ./template.yml \
# --stack-name ConfigRuleAccountTags \
# --capabilities CAPABILITY_IAM
Resources:
ConfigRule:
Type: AWS::Config::ConfigRule
DependsOn: EvaluationFunctionConfigPermission
@atheiman
atheiman / external_cidrs_calculator.py
Last active January 19, 2024 13:20
Terraform to deploy a prefix list representing all CIDRs outside a given list of CIDRs. The use case for this is to create a security group that allows all traffic to/from CIDRs outside a VPC.
from ipaddress import IPv4Network, IPv4Address, summarize_address_range
import json
import os
def lambda_handler(event, context):
print(json.dumps(event))
# Basic event validation
if "cidrs" not in event or not isinstance(event["cidrs"], list) or len(event["cidrs"]) < 1:
@atheiman
atheiman / cloudformation-security-hub-update-findings-lambda.yml
Created November 13, 2023 21:11
Lambda Function to update Security Hub Findings attributes "UserDefinedFields" and "Note" to include AWS account and OrganizationalUnit metadata
Resources:
SecurityHubFindingUpdateFunction:
Type: AWS::Lambda::Function
Properties:
Description: Applies metadata to Security Hub findings
Role: !Sub '${SecurityHubFindingUpdateFunctionRole.Arn}'
# ReservedConcurrentExecutions can be used to throttle the function if invocations get too
# high. However, all findings may not be updated.
#ReservedConcurrentExecutions: 3
Environment:
@atheiman
atheiman / script.py
Last active October 14, 2024 21:01
Convert python dictionary of many levels to single level dictionary with dot notation keys. This can be useful when writing to a format that requires a flat object/dictionary, such as CSV.
def dict_dot_notation(d, path=[]):
d2 = {}
for k, v in d.items():
k_path = path + [str(k)]
k_formatted = ".".join(k_path)
if isinstance(v, dict):
# merge in dict with recursive call
d2 = {**d2, **dict_dot_notation(v, path=k_path)}
elif isinstance(v, list) or isinstance(v, tuple):