Skip to content

Commit 96735a0

Browse files
twarnockMark Beacom
authored andcommitted
get_copy_status now uses role assumption (#89)
1 parent 59fe94c commit 96735a0

File tree

1 file changed

+25
-4
lines changed

1 file changed

+25
-4
lines changed

step/lambdas/get_copy_status.py

Lines changed: 25 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -29,18 +29,39 @@ def lambda_handler(event: Dict[str, Any], context: Any) -> str:
2929
copy_ami: str = event["copy_ami"]
3030
region: str = event.get("region", os.environ.get("AWS_REGION"))
3131
instance_name: str = event.get("name", "")
32-
ec2_client = boto3.client("ec2", region)
32+
role: str = event.get("role", "")
33+
34+
sts_client = boto3.client("sts")
35+
36+
print(f"Assuming role: {role}")
37+
assumed_role: Dict[str, Any] = sts_client.assume_role(
38+
RoleArn=role, RoleSessionName="GetCopyStatusLambda"
39+
)
40+
41+
credentials = assumed_role.get("Credentials")
42+
43+
ec2_client = boto3.client(
44+
"ec2",
45+
region_name=region,
46+
aws_access_key_id=credentials["AccessKeyId"],
47+
aws_secret_access_key=credentials["SecretAccessKey"],
48+
aws_session_token=credentials["SessionToken"],
49+
)
3350

3451
try:
3552
ami_state: Dict[str, Any] = ec2_client.describe_images(ImageIds=[copy_ami])
3653
except Exception as e:
3754
print(e)
3855
return "error"
3956

40-
state = ami_state["Images"][0]["State"]
41-
if state == "available":
57+
images = ami_state.get("Images")
58+
if not images:
59+
return "no-image-yet"
60+
61+
state = images[0].get("State")
62+
if state and state == "available":
4263
MigrationStateHandler().update_state(
4364
state="IMAGE_COPIED", machine_name=instance_name
4465
)
4566

46-
return ami_state["Images"][0]["State"]
67+
return state

0 commit comments

Comments
 (0)