-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathaws_session_assume.py
More file actions
48 lines (37 loc) · 1.27 KB
/
aws_session_assume.py
File metadata and controls
48 lines (37 loc) · 1.27 KB
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
#!/usr/bin/env python
import boto3
_AWS_ACCOUNT_FOR_ENV = {
"dev": "dev",
"dev-sandbox": "dev",
"qa": "test",
"qa-sandbox": "test",
"ref": "test",
"int": "test",
"int-sandbox": "test",
"prod": "prod",
}
def get_account_name(env: str):
if env not in _AWS_ACCOUNT_FOR_ENV:
raise ValueError(f"Invalid environment: {env}")
return _AWS_ACCOUNT_FOR_ENV[env]
def get_account_id(env: str):
account_name = get_account_name(env)
secretsmanager = boto3.client("secretsmanager", region_name="eu-west-2")
secret_id = f"nhsd-nrlf--mgmt--{account_name}-account-id"
result = secretsmanager.get_secret_value(SecretId=secret_id)
account_id = result["SecretString"]
return account_id
def get_boto_session(env: str) -> boto3.Session:
account_id = get_account_id(env)
sts = boto3.client("sts", region_name="eu-west-2")
result = sts.assume_role(
RoleArn=f"arn:aws:iam::{account_id}:role/terraform",
RoleSessionName="get-account-id",
DurationSeconds=900,
)
credentials = result["Credentials"]
return boto3.Session(
aws_access_key_id=credentials["AccessKeyId"],
aws_secret_access_key=credentials["SecretAccessKey"],
aws_session_token=credentials["SessionToken"],
)