-
Notifications
You must be signed in to change notification settings - Fork 1
/
aws-config-rules.py
81 lines (68 loc) · 2.3 KB
/
aws-config-rules.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#!/usr/bin/env python
"""
Download a list of resource compliance rules
Usage: ./aws-config-rules.py \
--profile profile-name \
--region {us-east-1}\
--output output-dir
"""
from argparse import ArgumentDefaultsHelpFormatter, ArgumentParser
from datetime import date
from itertools import count
from json import loads
from os import path
from pathlib import Path
import boto3
TODAY = date.today().strftime("%Y%m%d")
parser = ArgumentParser(
description="List Config rules across all accounts and regions.",
formatter_class=ArgumentDefaultsHelpFormatter,
)
parser.add_argument(
"--profile",
"-p",
required=True,
help="AWS profile name. "
"Parsed from ~/.aws/config (SSO) or credentials (API key). "
"Corresponds to the account where Config is deployed.",
)
parser.add_argument(
"--region", "-r", default="us-east-1", help="AWS Region of Config Aggregator."
)
parser.add_argument("--output", "-o", default="", help="Output directory of CSV.")
args = parser.parse_args()
profile = args.profile
region = args.region
dir_path = args.output
Path(dir_path).mkdir(parents=True, exist_ok=True)
session = boto3.session.Session(profile_name=profile, region_name=region)
client = session.client("config")
def select_aggregate_resource_config(expression):
"""Run Config (SQL) query specified by "expression" argument"""
results = []
response = {}
for i in count():
params = {
"Expression": expression,
"ConfigurationAggregatorName": "OrganizationConfigAggregator",
}
if i == 0 or "NextToken" in response:
if "NextToken" in response:
params["NextToken"] = response["NextToken"]
response = client.select_aggregate_resource_config(**params)
results.extend(response["Results"])
else:
break
return results
# List all rules
rule_list = select_aggregate_resource_config(
"SELECT configuration.configRuleList.configRuleName "
"WHERE resourceType = 'AWS::Config::ResourceCompliance'"
)
all_rules = set()
for result in rule_list:
for rule in loads(result)["configuration"]["configRuleList"]:
all_rules.add(rule["configRuleName"])
with open(path.join(dir_path, f"aws-config-rules-{TODAY}.txt", "w")) as f:
for rule in all_rules:
f.write(rule + "\n")