Skip to content

Instantly share code, notes, and snippets.

View atheiman's full-sized avatar
😬

Austin Heiman atheiman

😬
View GitHub Profile
@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):
@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')
@atheiman
atheiman / identity-center-list-all-assignments.sh
Created October 27, 2023 17:06
AWS Identity Center (SSO) list all assignments
IDENTITY_CENTER_INSTANCE_ARN="$(aws sso-admin list-instances --output text --query 'Instances[0].InstanceArn')"
IDENTITY_STORE_ID="$(aws sso-admin list-instances --output text --query 'Instances[0].IdentityStoreId')"
for acctid in $(aws organizations list-accounts --query 'Accounts[][Id]' --output text); do
echo "acct:$(aws organizations describe-account --account-id "$acctid" --output text --query 'Account.[Id, Email, Name]')"
for psarn in $(aws sso-admin list-permission-sets-provisioned-to-account --account-id "$acctid" --instance-arn "$IDENTITY_CENTER_INSTANCE_ARN" --output text --query 'PermissionSets[]'); do
echo " permissionset:$(aws sso-admin describe-permission-set --instance-arn "$IDENTITY_CENTER_INSTANCE_ARN" --permission-set-arn "$psarn" --output text --query 'PermissionSet.[Name]')"
for groupid in $(aws sso-admin list-account-assignments --account-id "$acctid" --instance-arn "$IDENTITY_CENTER_INSTANCE_ARN" --permission-set-arn "$psarn" --output text --query 'AccountAssignments[?P
@atheiman
atheiman / README.md
Last active October 24, 2023 10:26
AWS organization terraform multi-account pipeline
  1. build accounts - this can be terraform executed in the mgmt acct
  2. multi-account terragrunt run-all
    template/
      terragrunt.hcl
      main.tf
    111111111111/
      customization.tf
    
    

mkdir generated