-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathapply_iam_inline_policy.py
More file actions
122 lines (105 loc) · 4.41 KB
/
Copy pathapply_iam_inline_policy.py
File metadata and controls
122 lines (105 loc) · 4.41 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
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
#!/usr/bin/env python3
"""
Apply IAM inline policy to daylily-service user for zebra_day DynamoDB access.
Uses inline policy to avoid the 10 managed policies per user limit.
"""
import json
import sys
import time
try:
import boto3
from botocore.exceptions import ClientError
except ImportError:
print("ERROR: boto3 is not installed. Install with: pip install boto3")
sys.exit(1)
POLICY_FILE = "iam-policy-daylily-service-zebra-day.json"
POLICY_NAME = "ZebraDayDynamoDBAccess"
USER_NAME = "daylily-service"
def main():
# Get AWS profile from command line or environment
profile = sys.argv[1] if len(sys.argv) > 1 else None
# Load policy document
try:
with open(POLICY_FILE, "r") as f:
policy_document = json.load(f)
except FileNotFoundError:
print(f"ERROR: Policy file '{POLICY_FILE}' not found")
sys.exit(1)
except json.JSONDecodeError as e:
print(f"ERROR: Invalid JSON in policy file: {e}")
sys.exit(1)
# Create IAM client
session_kwargs = {}
if profile:
session_kwargs["profile_name"] = profile
print(f"Using AWS profile: {profile}")
session = boto3.Session(**session_kwargs)
iam = session.client("iam")
# Put inline policy (creates or updates)
print(f"Adding inline policy '{POLICY_NAME}' to user '{USER_NAME}'...")
try:
iam.put_user_policy(
UserName=USER_NAME,
PolicyName=POLICY_NAME,
PolicyDocument=json.dumps(policy_document),
)
print(f"✓ Inline policy '{POLICY_NAME}' added to user '{USER_NAME}'")
except ClientError as e:
if e.response["Error"]["Code"] == "NoSuchEntity":
print(f"ERROR: User '{USER_NAME}' does not exist")
sys.exit(1)
else:
print(f"ERROR adding inline policy: {e}")
sys.exit(1)
# Verify inline policy
print(f"\nVerifying inline policy...")
try:
response = iam.list_user_policies(UserName=USER_NAME)
inline_policies = response.get("PolicyNames", [])
if POLICY_NAME in inline_policies:
print(f"✓ Inline policy '{POLICY_NAME}' is attached to '{USER_NAME}'")
else:
print(f"⚠ WARNING: Policy not found in inline policies list")
print(f"\nAll inline policies for '{USER_NAME}':")
for policy_name in inline_policies:
print(f" - {policy_name}")
except ClientError as e:
print(f"ERROR verifying inline policy: {e}")
sys.exit(1)
# Wait for IAM propagation
print(f"\n⏳ Waiting 60 seconds for IAM policy propagation...")
time.sleep(60)
print("✓ Wait complete")
# Test DynamoDB access with daylily-service-lsmc profile
print(f"\nTesting DynamoDB access to 'zebra-day-config' in us-west-2...")
print(f"(Using profile: daylily-service-lsmc)")
try:
test_session = boto3.Session(profile_name="daylily-service-lsmc")
dynamodb = test_session.client("dynamodb", region_name="us-west-2")
response = dynamodb.describe_table(TableName="zebra-day-config")
print(f"✓ Successfully accessed table 'zebra-day-config'")
print(f" Status: {response['Table']['TableStatus']}")
print(f" Items: {response['Table']['ItemCount']}")
except ClientError as e:
if e.response["Error"]["Code"] == "AccessDeniedException":
print(f"⚠ WARNING: Still getting AccessDeniedException")
print(f" This may indicate:")
print(f" 1. IAM propagation needs more time (wait another 30-60s)")
print(f" 2. AWS credentials are not using the 'daylily-service' user")
print(f" 3. Additional permissions are needed")
elif e.response["Error"]["Code"] == "ResourceNotFoundException":
print(f"⚠ WARNING: Table 'zebra-day-config' does not exist in us-west-2")
print(f" Run: zday dynamo init --region us-west-2")
else:
print(f"ERROR testing DynamoDB access: {e}")
except Exception as e:
print(f"ERROR: {e}")
print(f"\n{'='*60}")
print(f"IAM inline policy setup complete!")
print(f"{'='*60}")
print(f"\nNext steps:")
print(f"1. Test the GUI backend switch at https://localhost:8118/config")
print(f"2. If still getting errors, wait another 30-60 seconds for IAM propagation")
print(f"3. Use AWS profile: daylily-service-lsmc")
if __name__ == "__main__":
main()