-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.py
83 lines (64 loc) · 2.42 KB
/
utils.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
82
83
import functools
from dataclasses import dataclass
from typing import Any
import boto3
@dataclass
class AWSAccount:
name: str
session: boto3.Session
class EachAccount:
"""Iterator or decorator to yield a session for each account in the organization."""
def __init__(self):
self.org_client = boto3.client("organizations")
def list_accounts_raw(self):
"""List all accounts in the organisation in JSON format."""
accounts = []
paginator = self.org_client.get_paginator("list_accounts")
for page in paginator.paginate():
accounts.extend(page["Accounts"])
return accounts
def assume_role(self, account_id):
"""Assume role in the target account."""
sts_client = boto3.client("sts")
role_arn = f"arn:aws:iam::{account_id}:role/OrganizationAccountAccessRole"
response = sts_client.assume_role(
RoleArn=role_arn, RoleSessionName="OrgAccountSession"
)
credentials = response["Credentials"]
return boto3.Session(
aws_access_key_id=credentials["AccessKeyId"],
aws_secret_access_key=credentials["SecretAccessKey"],
aws_session_token=credentials["SessionToken"],
region_name="eu-west-2",
)
def __iter__(self) -> AWSAccount:
raw_accounts = self.list_accounts_raw()
for raw_account in raw_accounts:
if raw_account["Name"] == "Root Root - DC":
continue
if raw_account["Status"] == "ACTIVE":
session = self.assume_role(raw_account["Id"])
yield AWSAccount(name=raw_account["Name"], session=session)
def __call__(self, func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
for session in self:
func(session, *args, **kwargs)
return wrapper
PER_RUN_VALUES = set()
def once_per_run(value: Any) -> bool:
"""
Because @EachAccount ends up calling the function once per AWS account,
it can be hard to print a single value once per run, e.g the header row of a CSV.
This util stores values in a set. If it's seen the value before, then it returns False,
else True and it will store the fact it's seen the value.
Use by:
```
if once_per_run("foo"):
// Do a thing once
```
"""
if value in PER_RUN_VALUES:
return False
PER_RUN_VALUES.add(value)
return True