From 12d58bbf298509f33f6991943e8591ccc38b232d Mon Sep 17 00:00:00 2001 From: Kent Ou <84220825+kentnsw@users.noreply.github.com> Date: Fri, 5 Aug 2022 02:18:06 +1000 Subject: [PATCH] iam - add RoleLastUsed to get_role response (#5302) --- moto/iam/models.py | 15 +++++++++++++++ tests/test_iam/test_iam.py | 22 ++++++++++++++++++++++ 2 files changed, 37 insertions(+) diff --git a/moto/iam/models.py b/moto/iam/models.py index bb1adc10b..43f8d1cbb 100644 --- a/moto/iam/models.py +++ b/moto/iam/models.py @@ -592,6 +592,8 @@ class Role(CloudFormationModel): self.managed_policies = {} self.create_date = datetime.utcnow() self.tags = tags + self.last_used = None + self.last_used_region = None self.description = description self.permissions_boundary = permissions_boundary self.max_session_duration = max_session_duration @@ -601,6 +603,11 @@ class Role(CloudFormationModel): def created_iso_8601(self): return iso_8601_datetime_with_milliseconds(self.create_date) + @property + def last_used_iso_8601(self): + if self.last_used: + return iso_8601_datetime_with_milliseconds(self.last_used) + @staticmethod def cloudformation_name_type(): return "RoleName" @@ -788,6 +795,14 @@ class Role(CloudFormationModel): {% endfor %} {% endif %} + + {% if role.last_used %} + {{ role.last_used_iso_8601 }} + {% endif %} + {% if role.last_used_region %} + {{ role.last_used_region }} + {% endif %} + """ ) return template.render(role=self) diff --git a/tests/test_iam/test_iam.py b/tests/test_iam/test_iam.py index a1c94da95..67232fef4 100644 --- a/tests/test_iam/test_iam.py +++ b/tests/test_iam/test_iam.py @@ -79,6 +79,28 @@ def test_get_role__should_throw__when_role_does_not_exist(): err["Message"].should.contain("not found") +@mock_iam +def test_get_role__should_contain_last_used(): + conn = boto3.client("iam", region_name="us-east-1") + conn.create_role( + RoleName="my-role", AssumeRolePolicyDocument="some policy", Path="/" + ) + role = conn.get_role(RoleName="my-role")["Role"] + role["RoleLastUsed"].should.equal({}) + + if not settings.TEST_SERVER_MODE: + iam_backend = get_backend("iam")["global"] + last_used = datetime.strptime( + "2022-07-18T10:30:00+00:00", "%Y-%m-%dT%H:%M:%S+00:00" + ) + region = "us-west-1" + iam_backend.roles[role["RoleId"]].last_used = last_used + iam_backend.roles[role["RoleId"]].last_used_region = region + roleLastUsed = conn.get_role(RoleName="my-role")["Role"]["RoleLastUsed"] + roleLastUsed["LastUsedDate"].replace(tzinfo=None).should.equal(last_used) + roleLastUsed["Region"].should.equal(region) + + @mock_iam def test_get_instance_profile__should_throw__when_instance_profile_does_not_exist(): conn = boto3.client("iam", region_name="us-east-1")