Skip to content

Instantly share code, notes, and snippets.

View atheiman's full-sized avatar
😬

Austin Heiman atheiman

😬
View GitHub Profile
@atheiman
atheiman / boto3_all_accounts.py
Created March 1, 2024 03:35
Run boto3 in a loop across all organization member AWS accounts
import boto3
region = boto3.Session().region_name
if region.startswith("us-gov-"):
partition = "aws-us-gov"
else:
partition = "aws"
orgs = boto3.client("organizations")
sts = boto3.client("sts")
@atheiman
atheiman / aws_switch_role_bookmark_generator.py
Last active February 26, 2024 14:11
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.
import boto3
import os
# Environment variables for configuration
role_name = os.environ.get("ROLE_NAME", "OrganizationAccountAccessRole")
include_mgmt = os.environ.get("INCLUDE_MGMT", "true").lower() == "true"
sts = boto3.client("sts")
caller_arn = sts.get_caller_identity()["Arn"]
partition = caller_arn.split(":")[1]
@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 January 19, 2024 13:20
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
Created November 21, 2023 19:05
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
Created November 9, 2023 21:51
Convert python dictionary of many levels to single level dictionary with dot notation keys
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):
@atheiman
atheiman / README.md
Last active December 8, 2023 03:28
AWS CloudShell setup
curl -Ls https://gist.githubusercontent.com/atheiman/45e45ada59e558b21f951d8e81faf345/raw/cloudshell-setup.sh?$RANDOM | bash
@atheiman
atheiman / boto3_cross_account_actions.py
Created October 27, 2023 19:37
boto3 run api calls in multiple regions of multiple accounts
#!/usr/bin/env python3
import boto3
import botocore
partition = 'aws'
regions = ['us-east-1', 'us-west-2']
skip_master_acct = True
organizations = boto3.client('organizations')