

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# 跟踪您的 AMS Accelerate 账户中的更改
<a name="acc-change-record"></a>

**重要**  
自 2025 年 7 月 1 日起，变更记录服务已被弃用。  
新账户无法加入 “更改记录” 服务。  
要查询您的 AMS Accelerate 账户中的 CloudTrail 数据，您可以使用以下服务：  
在中 AWS CloudTrail，选择**事件历史记录**并使用查找属性筛选事件。您可以使用时间范围过滤器，选择按`s3.amazon.aws.com`指定事件源筛选事件历史记录，也可以选择按用户名筛选事件历史记录。有关更多信息，请参阅[使用 CloudTrail 事件历史记录](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/view-cloudtrail-events.html)。
使用 AWS CloudTrail Lake 通过查询收集数据。在中 AWS CloudTrail 选择 “**湖泊**”，然后选择 “**查询**”。您可以创建自己的查询、使用查询生成器或使用示例查询来收集基于事件的数据。例如，您可以询问上周谁删除了 Amazon EC2 实例。有关更多信息，请参阅[通过 AWS CloudTrail 源和[CloudTrailLake 查询](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/cloudtrail-lake-queries.html)创建数据湖](https://docs.aws.amazon.com/lake-formation/latest/dg/getting-started-cloudtrail-tutorial.html)。
 AWS CloudTrail 在中创建 Amazon Athena 表，并将存储位置设置为与您的跟踪关联的 Amazon S3 存储桶。验证您的跟踪的主区域和 Amazon S3 存储桶是否相同。在 Amazon Athena 中，使用查询编辑器运行 Accelerate 提供的与 Athena 控制台配合使用的[默认](#acc-cr-canned-queries)查询。[有关如何创建 Athena 表来 CloudTrail 查询日志的更多信息，请参阅查询日志。 AWS CloudTrail](https://docs.aws.amazon.com/athena/latest/ug/cloudtrail-logs.html)

**Topics**
+ [查看您的变更记录](#acc-cr-using)
+ [默认查询](#acc-cr-canned-queries)
+ [更改记录权限](#acc-cr-permissions)

AWS Managed Services 使用亚马逊 Athena（At [hena](https://docs.aws.amazon.com/athena/)）控制台和 AMS 加速日志管理提供可查询的界面，帮助您跟踪 AMS 加速运营团队和 AMS 加速自动化所做的更改。

Athena 是一项交互式查询服务，您可以使用标准结构化查询语言 (SQL) 来分析 Amazon S3 中的数据（[参见 Amazon Athena 的 SQL 参](https://docs.aws.amazon.com/athena/latest/ug/ddl-sql-reference.html)考）。Athena 没有服务器，没有要管理的基础设施，只需为运行的查询付费。AMS Accelerate 创建包含每日日志分区 CloudTrail 的 Athena 表，并提供有关您的 AWS 主要区域和工作组内部的查询。**ams-change-record**您可以选择任何默认查询并根据需要运行它们。[要了解有关 Athena 工作组的更多信息，请参阅工作组的工作原理。](https://docs.aws.amazon.com/athena/latest/ug/user-created-workgroups.html)

**注意**  
只有当加速[与您的组织跟踪集成时，Accelerate 才能使用 Athena 查询 CloudTrail 您的](https://docs.aws.amazon.com/managedservices/latest/accelerate-guide/acc-onb-trail-choices.html) Accelerate 账户 CloudTrail 的事件，除非您的组织管理员部署了 IAM 角色，以便在入职期间使用 Athena 查询和 CloudTrail 分析您账户中的事件。

使用更改记录，您可以轻松回答以下问题：
+ 谁（AMS 加速系统或 AMS 加速运营商）访问了您的账户
+ AMS Accelerate 对您的账户进行了哪些更改
+ AMS Accelerate 是什么时候对你的账户进行更改的
+ 去哪里查看账户中所做的更改
+ 为什么 AMS Accelerate 需要对你的账户进行更改
+ 如何修改查询以获得所有非 AMS 变更问题的答案

## 查看您的变更记录
<a name="acc-cr-using"></a>

要使用 Athena 查询，请登录管理控制台并 AWS 导航到主区域中的 Athena 控制台。 AWS 

**注意**  
**如果您在执行任何步骤时看到 **Amazon Athena 入**门页面，请单击 “开始”。**即使您的 “更改记录” 基础架构已经到位，您也可能会看到此信息。

1. 从 Athena 控制**台的上方导航面板中选择 “工作组**”。

1. 选择**ams-change-record**工作组，然后单击 “**切换工作**组”。

1. **ams-change-record-database**从 “**数据库” 组合**框中进行选择。**ams-change-record-database**包括**ams-change-record-table**表格。

1. 从上方的导航面板中选择 “**已保存的查询**”。

1. “**已保存的查询**” 窗口显示 AMS Accelerate 提供的查询列表，您可以运行这些查询。从 “**已保存的查询” 列表中选择要运行的查询**。例如，**ams\$1session\$1access\$1v1 查询**。

   有关预设 AMS 加速查询的完整列表，请参阅[默认查询](#acc-cr-canned-queries)。

1. 根据需要调整查询编辑器框中的**日期时间**过滤器；默认情况下，查询仅检查与上一天相比的更改。

1. 选择**运行查询**。

## 默认查询
<a name="acc-cr-canned-queries"></a>

AMS Accelerate 提供了几个默认查询，您可以在 Athena 控制台中使用。下表列出了默认查询。

**注意**  
所有查询都接受**日期时间范围**作为可选筛选条件；默认情况下，所有查询都在过去 24 小时内运行。有关预期的输入，请参阅以下小节[修改查询中的日期时间过滤器](#acc-cr-canned-queries-mod-timestamp)。
可以或需要更改的参数输入*<PARAMETER\$1NAME>*与角大括号一样显示在查询中。用您的参数值替换占位符**和**角括号。
所有过滤器都是可选的。在查询中，一些可选的过滤器在行首用双破折号 (--) 注释掉。所有查询都将在没有它们的情况下运行，并使用默认参数。如果要为这些可选筛选器指定参数值，请删除该行开头的双破折号 (--)，然后根据需要替换参数。
所有查询都返回`IAM PincipalId``IAM SessionId`并在输出中
运行查询的计算费用取决于为该账户生成的 CloudTrail 日志数量。要计算成本，请使用 [AWS Athena 定](https://aws.amazon.com/athena/pricing/)价计算器。


**预设查询**  

| 目的/描述 | 输入 | 输出 | 
| --- | --- | --- | 
| **查询名称**：`ams\$1access\$1session\$1query\$1v1` | 
| 跟踪 AMS 加速访问会话 提供有关特定 AMS 加速访问会话的信息。该查询接受 IAM 委托人 ID 作为可选筛选条件，并返回事件时间、访问账户的业务需求、请求者等。 您可以通过取消注释行并在查询编辑器中将占位符*IAM PrincipalId*替换为特定 ID 来筛选特定 IAM 委托人 ID。 您还可以通过删除查询的 WHERE 子句中的**用户代理**筛选器行来列出非 AMS 访问会话。 | （可选）`IAM PrincipalId`：尝试访问的资源的 IAM 委托人标识符。格式为*UNIQUE\$1IDENTIFIER*:*RESOURCE\$1NAME*. 有关详细信息，请参阅[唯一标识符](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_identifiers.html#identifiers-unique-ids)。您可以在不使用此筛选条件的情况下运行查询，以确定要筛选 PrincipalId 的确切 IAM。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/managedservices/latest/accelerate-guide/acc-change-record.html) | 
| **查询名称**：`ams\$1events\$1query\$1v1` | 
| 跟踪 AMS Accelerate 完成的所有变异动作 返回使用该 AMS Accelerate 角色筛选器对账户完成的所有写入操作。 您还可以通过从查询的 WHERE 子句中删除 **useridentity.arn** 筛选器行来跟踪非 AMS 角色所做的变更操作。 | （可选） 仅限**日期时间范围**。请参阅[修改查询中的日期时间过滤器](#acc-cr-canned-queries-mod-timestamp)。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/managedservices/latest/accelerate-guide/acc-change-record.html) | 
| **查询名称**：`ams\$1instance\$1access\$1sessions\$1query\$1v1` | 
| 通过 AMS Accelerate 追踪实例访问情况 返回 AMS Accelerate 实例访问列表；每条记录都包括事件时间、事件区域、实例 ID、IAM 委托人 ID、IAM 会话 ID、SSM 会话 ID、SSM 会话 ID。您可以使用 IAM 委托人 ID 通过 At `ams_access_sessions_query_v1` hena 查询获取有关访问实例的业务需求的更多详细信息。您可以使用 SSM 会话 ID 来获取有关实例访问会话的更多详细信息，包括会话的开始和结束时间、日志详细信息以及使用实例 AWS 区域中的 AWS 会话管理器控制台。 用户还可以通过删除查询 WHERE 子句中的**用户身份**筛选器行来列出非 AMS 实例访问权限。 | 仅限 `datetime range`。请参阅[修改查询中的日期时间过滤器](#acc-cr-canned-queries-mod-timestamp)。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/managedservices/latest/accelerate-guide/acc-change-record.html) | 
| **查询名称**：`ams\$1privilege\$1escalation\$1events\$1query\$1v1` | 
| 跟踪 AMS 和非 AMS 用户的许可（升级）事件 提供可能直接或可能导致权限升级的事件列表。该查询接受 ActionedBy 为可选过滤器 EventName，并返回 EventId EventTime、、等。还会返回与该事件关联的所有字段。如果不适用于该事件，则字段为空。默认情况下， ActionedBy 过滤器处于禁用状态；要启用该过滤器，请从该行中删除 “--”。 默认情况下， ActionedBy 筛选器处于禁用状态（它将显示所有用户的权限升级事件）。要显示特定用户或角色的事件，请从 WHERE 子句的**用户身份**筛选器行中删除双破折号 (--)，并将占位符*ACTIONEDBY\$1PUT\$1USER\$1NAME\$1HERE*替换为 IAM 用户或角色名称。您可以在不使用筛选器的情况下运行查询，以确定要筛选的确切用户。 | （可选）`ACTIONEDBY_PUT_USER_NAME`：ActionedBy 用户的用户名。这可以是 IAM 用户或角色。例如 ams-access-admin。 （可选）`datetime range`。请参阅[修改查询中的日期时间过滤器](#acc-cr-canned-queries-mod-timestamp)。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/managedservices/latest/accelerate-guide/acc-change-record.html) | 
| **查询名称**：`ams\$1resource\$1events\$1query\$1v1` | 
| 跟踪特定资源 AMS 或非 AMS 的写入事件 提供在特定资源上完成的事件的列表。查询接受资源 ID 作为筛选器的一部分（替换查询的 WHERE 子句*RESOURCE\$1INFO*中的占位符），并返回对该资源执行的所有写入操作。 | （必填）`RESOURCE_INFO`：资源标识符可以是账户中任何 AWS 资源的 ID。不要将其与资源 ARNs混淆。例如，实例的实例 ID、DynamoDB 表的表名 logGroupName 、日志的表 CloudWatch 名等。 EC2  （可选）`datetime range`。请参阅[修改查询中的日期时间过滤器](#acc-cr-canned-queries-mod-timestamp)。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/managedservices/latest/accelerate-guide/acc-change-record.html) | 
| **查询名称**：`ams\$1session\$1events\$1query\$1v1` | 
| 跟踪 AMS Accelerate 在特定会话期间执行的写入操作 提供在特定会话中完成的事件列表。该查询接受 IAM 委托人 ID 作为筛选条件的一部分（替换查询的 WHERE 子句*PRINCIPAL\$1ID*中的占位符），并返回对该资源执行的所有写入操作。 | （必填）`PRINCIPAL_ID`：会话的主人 ID。格式为*UNIQUE\$1IDENTIFIER*:*RESOURCE\$1NAME*. 有关详细信息，请参阅[唯一标识符](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_identifiers.html#identifiers-unique-ids)。你可以运行查询 “ams\$1session\$1ids\$1by\$1requester\$1v1” 来获取请求者的 IAM 委托人列表。 IDs 您也可以在不使用此筛选条件的情况下运行查询，以确定 PrincipalId 要筛选的确切 IAM。 （可选）`datetime range`。请参阅[修改查询中的日期时间过滤器](#acc-cr-canned-queries-mod-timestamp)。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/managedservices/latest/accelerate-guide/acc-change-record.html) | 
| **查询名称**：`ams\$1session\$1ids\$1by\$1requester\$1v1` | 
| 跟踪特定请求 Principal/Session IDs 者的 IAM。 该查询接受 “请求者”（替换查询的 WHERE 子句*Requester*中的占位符），并返回该请求者在指定时间范围内的所有 IAM 委托人 ID。 | （必填）`Requester`：访问账户的操作员 ID（例如：操作员的别名）或访问该账户的自动化系统（例如： OsConfiguration AlarmManager、等）。 （可选）`datetime range`。请参阅[修改查询中的日期时间过滤器](#acc-cr-canned-queries-mod-timestamp)。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/managedservices/latest/accelerate-guide/acc-change-record.html) | 

### 修改查询中的日期时间过滤器
<a name="acc-cr-canned-queries-mod-timestamp"></a>

所有查询都接受**日期时间**范围作为可选过滤器。默认情况下，所有查询都是在过去一天内运行的。

**日期时间**字段使用的格式为yyyy/MM/dd（例如：2021/01/01）。请记住，它只存储日期，而不是整个时间戳。对于整个时间戳，请使用 e **vent** ime 字段，该字段以 ISO 8601 格式存储时间戳 yyyy-MM-dd **T** HH: mm: ss **Z（例如：2021-01-01T23：59:59 Z**）。但是，由于表是在日期时间字段上进行[分区](https://docs.aws.amazon.com/athena/latest/ug/partitions.html)的，因此您需要将日期时间和事件时间过滤器同时传递给查询。请见以下 示例。

**注意**  
要查看所有可接受的修改范围的方法，请参阅基于当前用于**日期和时间函数和运算符的 Athena 引擎版本的最新 Presto 函数**[文档](https://docs.aws.amazon.com/athena/latest/ug/presto-functions.html)，了解修改范围的所有可接受的方式。

**日期级别：过去 1 天或过去 24 小时（默认）**示例：如果 CURRENT\$1DATE='2021/01/01'，则筛选器将从当前日期中减去一天并将其格式化为日期时间 > '2020/12/31'

```
datetime > date_format(date_add('day', - 1, CURRENT_DATE), '%Y/%m/%d')
```

**日期级别：过去 2 个月**示例：

```
datetime > date_format(date_add('month', - 2, CURRENT_DATE), '%Y/%m/%d')
```

**日期级别：2 个日期之间**示例：

```
datetime > '2021/01/01'
      AND
      datetime < '2021/01/10'
```

**时间戳级别：过去 12 小时**示例：

将分区数据扫描到最近 1 天，然后筛选过去 12 小时内的所有事件

```
datetime > date_format(date_add('day', - 1, CURRENT_DATE), '%Y/%m/%d')
      AND
      eventtime > date_format(date_add('hour', - 12, CURRENT_TIMESTAMP), '%Y-%m-%dT%H:%i:%sZ')
```

**时间戳级别：在 2 个时间戳之间**示例：

获取在 2021 年 1 月 1 日下午 12:00 至 2021 年 1 月 10 日下午 3:00 之间的活动。

```
datetime > '2021/01/01' AND datetime < '2021/01/10'
      AND
      eventtime > '2021-01-01T12:00:00Z' AND eventtime < '2021-01-10T15:00:00Z'
```

### 默认查询示例
<a name="acc-default-query-examples"></a>

#### `ams_access_session_query_v1`
<a name="ams-access-session-query-v1"></a>

```
Name: ams_access_session_query_v1

Description: >-
   The query provides more information on specific AMS access session.
   The query accepts IAM Principal Id as an optional filter and returns event time, business need for accessing the account, requester, ... etc.
   By default; the query filter last day events only, the user can change the datetime filter to search for more wide time range.
   By default; the IAM PrincipalId filter is disabled. To enable it, remove "-- " from that line.

AthenaQueryString: |-
   /*
     The query provides list of AMS access sessions during specific time range.
     The query accepts IAM Principal Id as an optional filter and returns event time, business need for accessing the account, requester, ... etc.

     By default, the query filters the last day's events only; you can change the "datetime" filter to search for a wider time range.

     By default; the IAM Principal ID filter is disabled (it shows access sessions for all IAM principals).
     If you want to only show access sessions for a particular IAM principal ID, remove the double-dash (--) from
     the "IAM Principal ID" filter line in the WHERE clause of the query, and replace the placeholder "<IAM PrincipalId>" with the specific ID that you want.
     You can run the query without the filter to determine the exact IAM PrincipalId you want to filter with.

     By default; the query only shows AMS access sessions. If you also want to show non-AMS access sessions,
     remove the "useragent" filter in the WHERE clause of the query.

     For expected inputs and scenarios, refer to AMS Documentation -> Tracking changes in your AMS Accelerate accounts -> Default Queries
   */

   SELECT
      json_extract_scalar(responseelements, '$.assumedRoleUser.assumedRoleId') AS "IAM PrincipalId",
      json_extract_scalar(responseelements, '$.credentials.accessKeyId') AS "IAM SessionId",
      eventtime AS "EventTime",
      eventname AS "EventName",
      awsregion AS "EventRegion",
      eventid AS "EventId",
      json_extract_scalar(requestparameters, '$.tags[0].value') AS "BusinessNeed",
      json_extract_scalar(requestparameters, '$.tags[1].value') AS "BusinessNeedType",
      json_extract_scalar(requestparameters, '$.tags[2].value') AS "Requester",
      json_extract_scalar(requestparameters, '$.tags[3].value') AS "AccessRequestType"
   FROM
       "{DATABASE NAME HERE}".{TABLENAME HERE} <- This should auto-populate
   WHERE
      datetime > date_format(date_add('day', - 1, CURRENT_DATE), '%Y/%m/%d')
      AND eventname = 'AssumeRole'
      AND useragent = 'access.managedservices.amazonaws.com'
      -- AND  json_extract_scalar(responseelements, '$.assumedRoleUser.assumedRoleId') = '<IAM PrincipalId>'
   ORDER BY eventtime

InsightsQueryString: |-
   # The query provides list of AMS access sessions during specific time range.
   # The query accepts IAM Principal Id as an optional filter and returns event time, business need for accessing the account, requester, ... etc.
   #
   # By default; the IAM Principal ID filter is disabled (it shows access sessions for all IAM principals).
   # If you want to only show access sessions for a particular IAM principal ID, remove the # (#) from
   # the "IAM Principal ID" filter of the query, and replace the placeholder "<IAM PrincipalId>" with the specific ID that you want.
   # You can run the query without the filter to determine the exact IAM PrincipalId you want to filter with.
   #
   # By default; the query only shows AMS access sessions. If you also want to show non-AMS access sessions,
   # remove the "useragent" filter from the query.
   #
   # For expected inputs and scenarios, refer to AMS Documentation -> Tracking changes in your AMS Accelerate accounts -> Default Queries

   filter eventName="AssumeRole" AND userAgent="access.managedservices.amazonaws.com"
   # | filter responseElements.assumedRoleUser.assumedRoleId= "<IAM PrincipalId>"
   | sort eventTime desc
   | fields
      responseElements.assumedRoleUser.assumedRoleId as IAMPrincipalId,
      responseElements.credentials.accessKeyId as IAMSessionId,
      eventTime as EventTime,
      eventName as EventName,
      awsRegion as EventRegion,
      eventID as EventId,
      requestParameters.tags.0.value as BusinessNeed,
      requestParameters.tags.1.value as BusinessNeedType,
      requestParameters.tags.2.value as Requester,
      requestParameters.tags.3.value as AccessRequestType
```

#### `ams_events_query_v1`
<a name="ams-events-query-v1"></a>

```
ams_events_query_v1.yaml
/*
  The query provides list of events to track write actions for all AMS changes.
  The query returns all write actions done on the account using that AMS role filter.

  By default, the query filters the last day's events only; you can change the "datetime" filter to search for a wider time range.

  You can also track mutating actions done by non-AMS roles by removing the "useridentity.arn" filter lines from the WHERE clause of the query.

  For expected inputs and scenarios, refer to AMS Documentation -> Tracking changes in your AMS Accelerate accounts -> Default Queries
*/

SELECT
   useridentity.principalId AS "IAM PrincipalId",
   useridentity.accesskeyid AS "IAM SessionId",
   useridentity.accountid AS "AccountId",
   useridentity.arn AS "RoleArn",
   eventid AS "EventId",
   eventname AS "EventName",
   awsregion AS "EventRegion",
   eventsource AS "EventService",
   eventtime AS "EventTime",
   requestparameters As "RequestParameters",
   responseelements AS "ResponseElements",
   useragent AS "UserAgent"
FROM
   "{DATABASE NAME HERE}".{TABLENAME HERE} <- This should auto-populate
WHERE
   readonly <> 'true'
   AND
   (
      LOWER(useridentity.arn) LIKE '%/ams%'
      OR LOWER(useridentity.arn) LIKE '%/customer_ssm_automation_role%'
   )
ORDER BY eventtime
```

#### `ams_instance_access_sessions_query_v1`
<a name="ams-instance-access-sessions-query-v1"></a>

```
ams_instance_access_sessions_query_v1
/*
  The query provides list of AMS Instance accesses during specific time range.

  The query returns the list of AMS instance accesses; every record includes the event time, the event AWS Region, the instance ID, the IAM session ID, and the SSM session ID.
  You can use the IAM Principal ID to get more details on the business need for accessing the instance by using ams_access_session_query_v1 athena query.
  You can use the SSM session ID to get more details on the instance access session, including the start and end time of the session and log details, using the AWS Session Manager Console in the instance's AWS Region.

  You can also list non-AMS instance accesses by removing the "useridentity" filter line in the WHERE clause of the query.

  By default, the query filters the last day's events only; you can change the "datetime" filter to search for a wider time range.

  For expected inputs and scenarios, refer to AMS Documentation -> Tracking changes in your AMS Accelerate accounts -> Default Queries
*/

SELECT
   useridentity.principalId AS "IAM PrincipalId",
   useridentity.accesskeyid AS "IAM SessionId",
   json_extract_scalar(requestparameters, '$.target') AS "InstanceId",
   json_extract_scalar(responseelements, '$.sessionId') AS "SSM SessionId",
   eventname AS "EventName",
   awsregion AS "EventRegion",
   eventid AS "EventId",
   eventsource AS "EventService",
   eventtime AS "EventTime" 
FROM
   "{DATABASE NAME HERE}".{TABLENAME HERE} <- This should auto-populate
WHERE
   useridentity.sessionContext.sessionIssuer.arn like '%/ams_%' 
   AND eventname = 'StartSession' 
ORDER BY eventtime
```

#### `ams_privilege_escalation_events_query_v1`
<a name="ams-privilege-escalation-events-query-v1"></a>

```
ams_privilege_escalation_events_query_v1.yaml
/*
  The query provides list of events that can directly or potentially lead to a privilege escalation.

  The query accepts ActionedBy as an optional filter and returns EventName, EventId, EventTime, ... etc.
  All fields associated with the event are also returned. Some fields are blank if not applicable for that event.
  You can use the IAM Session ID to get more details about events happened in that session by using ams_session_events_query_v1 query.

  By default, the query filters the last day's events only; you can change the "datetime" filter to search for a wider time range.

  By default, the ActionedBy filter is disabled (it shows privilege escalation events from all users).
  To show events for a particular user or role, remove the double-dash (--) from the useridentity filter line in the WHERE clause of the query
  and replace the placeholder "<ACTIONEDBY_PUT_USER_NAME_HERE>" with an IAM user or role name.
  You can run the query without the filter to determine the exact user you want to filter with.

  For expected inputs and scenarios, refer to AMS Documentation -> Tracking changes in your AMS Accelerate accounts -> Default Queries
*/

SELECT
   useridentity.principalId AS "IAM PrincipalId",
   useridentity.accesskeyid AS "IAM SessionId",
   useridentity.accountid AS "AccountId",
   reverse(split_part(reverse(useridentity.arn), ':', 1)) AS "ActionedBy",
   eventname AS "EventName",
   awsregion AS "EventRegion",
   eventid AS "EventId",
   eventtime AS "EventTime",
   json_extract_scalar(requestparameters, '$.userName') AS "UserName",
   json_extract_scalar(requestparameters, '$.roleName') AS "RoleName",
   json_extract_scalar(requestparameters, '$.groupName') AS "GroupName",
   json_extract_scalar(requestparameters, '$.policyArn') AS "PolicyArn",
   json_extract_scalar(requestparameters, '$.policyName') AS "PolicyName",
   json_extract_scalar(requestparameters, '$.permissionsBoundary') AS "PermissionsBoundary",
   json_extract_scalar(requestparameters, '$.instanceProfileName') AS "InstanceProfileName",
   json_extract_scalar(requestparameters, '$.openIDConnectProviderArn') AS "OpenIDConnectProviderArn",
   json_extract_scalar(requestparameters, '$.serialNumber') AS "SerialNumber",
   json_extract_scalar(requestparameters, '$.serverCertificateName') AS "ServerCertificateName",
   json_extract_scalar(requestparameters, '$.accessKeyId') AS "AccessKeyId",
   json_extract_scalar(requestparameters, '$.certificateId') AS "CertificateId",
   json_extract_scalar(requestparameters, '$.newUserName') AS "NewUserName",
   json_extract_scalar(requestparameters, '$.newGroupName') AS "NewGroupName",
   json_extract_scalar(requestparameters, '$.newServerCertificateName') AS "NewServerCertificateName",
   json_extract_scalar(requestparameters, '$.name') AS "SAMLProviderName",
   json_extract_scalar(requestparameters, '$.sAMLProviderArn') AS "SAMLProviderArn",
   json_extract_scalar(requestparameters, '$.sSHPublicKeyId') AS "SSHPublicKeyId",
   json_extract_scalar(requestparameters, '$.virtualMFADeviceName') AS "VirtualMFADeviceName"
FROM
   "{DATABASE NAME HERE}".{TABLENAME HERE} <- This should auto-populate
WHERE
   (
     -- More event names can be found at https://docs.aws.amazon.com/IAM/latest/UserGuide/list_identityandaccessmanagement.html
     eventname LIKE 'Add%' OR
     eventname LIKE 'Attach%' OR
     eventname LIKE 'Delete%' AND eventname != 'DeleteAccountAlias' OR
     eventname LIKE 'Detach%' OR
     eventname LIKE 'Create%' AND eventname != 'CreateAccountAlias' OR
     eventname LIKE 'Put%' OR
     eventname LIKE 'Remove%' OR
     eventname LIKE 'Update%' OR
     eventname LIKE 'Upload%' OR
     eventname = 'DeactivateMFADevice' OR
     eventname = 'EnableMFADevice' OR
     eventname = 'ResetServiceSpecificCredential' OR
     eventname = 'SetDefaultPolicyVersion'
   )
   AND eventsource = 'iam.amazonaws.com'
ORDER BY eventtime
```

#### `ams_resource_events_query_v1`
<a name="ams-resource-events-query-v1"></a>

```
Name: ams_resource_events_query_v1

Description: >-
   The query provides list of events done on specific resource.
   The query accepts resource id as part of the filters, and return all write actions done on that resource.
   By default; the query list the accesses for last day, the user can change the time range by changing the datetime filter.

AthenaQueryString: |-
   /*
     The query provides list of events done on specific resource.

     The query accepts the resource ID as part of the filters (replace the placeholder "<RESOURCE_INFO>" in the WHERE clause of the query),
     and returns all write actions done on that resource. The resource ID can be an ID for any AWS resource in the account.
     Example: An instance ID for an EC2 instance, table name for a DynamoDB table, logGroupName for a CloudWatch Log, etc.

     By default, the query filters the last day's events only; you can change the "datetime" filter to search for a wider time range.

     For expected inputs and scenarios, refer to AMS Documentation -> Tracking changes in your AMS Accelerate accounts -> Default Queries
   */

   SELECT
      useridentity.principalId AS "IAM PrincipalId",
      useridentity.accesskeyid AS "IAM SessionId",
      useridentity.accountid AS "AccountId",
      reverse(split_part(reverse(useridentity.arn), ':', 1)) AS "ActionedBy",
      eventname AS "EventName",
      awsregion AS "EventRegion",
      eventid AS "EventId",
      eventsource AS "EventService",
      eventtime AS "EventTime" 
   FROM
       "{DATABASE NAME HERE}".{TABLENAME HERE} <- This should auto-populate
   WHERE
      datetime > date_format(date_add('day', - 1, CURRENT_DATE), '%Y/%m/%d')
      AND readonly <> 'true'
      AND 
      (
         requestparameters LIKE '%<RESOURCE_INFO>%' 
         OR responseelements LIKE '%<RESOURCE_INFO>%'
      )
   ORDER BY eventtime

InsightsQueryString: |-
   # The query provides list of events done on specific resource.
   #
   # The query accepts the resource ID as part of the filters (replace the placeholder "<RESOURCE_INFO>" in the filter of the query),
   # and returns all write actions done on that resource. The resource ID can be an ID for any AWS resource in the account.
   # Example: An instance ID for an EC2 instance, table name for a DynamoDB table, logGroupName for a CloudWatch Log, etc.
   #
   # For expected inputs and scenarios, refer to AMS Documentation -> Tracking changes in your AMS Accelerate accounts -> Default Queries

   filter readOnly=0
   | parse @message '"requestParameters":{*}' as RequestParameters
   | parse @message '"responseElements":{*}' as ResponseElements
   # | filter RequestParameters like "RESOURCE_INFO" or ResponseElements like "<RESOURCE_INFO>"
   | fields
      userIdentity.principalId as IAMPrincipalId,
      userIdentity.accessKeyId as IAMSessionId,
      userIdentity.accountId as AccountId,
      userIdentity.arn as ActionedBy,
      eventName as EventName,
      awsRegion as EventRegion,
      eventID as EventId,
      eventSource as EventService,
      eventTime as EventTime
   | display IAMPrincipalId, IAMSessionId, AccountId, ActionedBy, EventName, EventRegion, EventId, EventService, EventTime
   | sort eventTime desc
```

#### `ams_session_events_query_v1`
<a name="ams-session-events-query-v1"></a>

```
Name: ams_session_events_query_v1

Description: >-
   The query provides list of events done on specific session.
   The query accepts IAM Principal Id as part of the filters, and return all write actions done on that resource.
   By default; the query list the accesses for last day, the user can change the time range by changing the datetime filter.

AthenaQueryString: |-
   /*
     The query provides a list of events executed on a specific session.

     The query accepts the IAM principal ID as part of the filters (replace the placeholder "<PRINCIPAL_ID>" in the WHERE clause of the query),
     and returns all write actions done on that resource.

     By default, the query filters the last day's events only; you can change the "datetime" filter to search for a wider time range.

     For expected inputs and scenarios, refer to AMS Documentation -> Tracking changes in your AMS Accelerate accounts -> Default Queries
   */

   SELECT
      useridentity.principalId AS "IAM PrincipalId",
      useridentity.accesskeyid AS "IAM SessionId",
      useridentity.accountid AS "AccountId",
      reverse(split_part(reverse(useridentity.arn), ':', 1)) AS "ActionedBy",
      eventname AS "EventName",
      awsregion AS "EventRegion",
      eventsource AS "EventService",
      eventtime AS "EventTime",
      requestparameters As "RequestParameters",
      responseelements AS "ResponseElements",
      useragent AS "UserAgent"
   FROM
       "{DATABASE NAME HERE}".{TABLENAME HERE} <- This should auto-populate   WHERE
      useridentity.principalid = '<PRINCIPAL_ID>'
      AND datetime > date_format(date_add('day', - 1, CURRENT_DATE), '%Y/%m/%d')
      AND readonly <> 'true'
   ORDER BY eventtime

InsightsQueryString: |-
   # The query provides a list of events executed on a specific session.
   #
   # The query accepts the IAM principal ID as part of the filters (replace the placeholder "<PRINCIPAL_ID>" in the filter of the query),
   # and returns all write actions done on that resource.
   #
   # For expected inputs and scenarios, refer to AMS Documentation -> Tracking changes in your AMS Accelerate accounts -> Default Queries

   filter readOnly=0 AND userIdentity.principalId = "<IAM Principal>"
   | sort eventTime desc
   | fields
      userIdentity.accessKeyId as IAMSessionId,
      userIdentity.principalId as IAMPrincipalId,
      userIdentity.accountId as AccountId,
      userIdentity.arn as ActionedBy,
      eventName as EventName,
      awsRegion as EventRegion,
      eventSource as EventService,
      eventTime as EventTime,
      userAgent as UserAgent
   | parse @message '"requestParameters":{*}' as RequestParameters
   | parse @message '"responseElements":{*}' as ResponseElements
```

#### `ams_session_ids_by_requester_v1`
<a name="ams-session-ids-by-requester-v1"></a>

```
Name: ams_session_ids_by_requester_v1

Description: >-
   The query provides list of IAM Principal/Session Ids for specific requester.
   The query accepts requester and return all IAM Principal/Session Ids by that requester during specific time range.
   By default; the query list the accesses for last day, the user can change the time range by changing the datetime filter.

AthenaQueryString: |-
   /*
     The query provides list of IAM Principal IDs for a specific requester.

     The query accepts the requester (replace placeholder "<Requester>" in the WHERE clause of the query),
     and returns all IAM Principal IDs by that requester during a specific time range.

     By default, the query filters the last day's events only; you can change the "datetime" filter to search for a wider time range.

     For expected inputs and scenarios, refer to AMS Documentation -> Tracking changes in your AMS Accelerate accounts -> Default Queries
   */

   SELECT
      json_extract_scalar(responseelements, '$.assumedRoleUser.assumedRoleId') AS "IAM PrincipalId",
      json_extract_scalar(responseelements, '$.credentials.accessKeyId') AS "IAM SessionIId",
      eventtime AS "EventTime"
   FROM
       "{DATABASE NAME HERE}".{TABLENAME HERE} <- This should auto-populate
   WHERE
      datetime > date_format(date_add('day', - 1, CURRENT_DATE), '%Y/%m/%d') 
      AND json_extract_scalar(requestparameters, '$.tags[2].value') = '<Requester>'
   ORDER BY eventtime

InsightsQueryString: |-
   # The query provides list of IAM Principal IDs for a specific requester.
   #
   # The query accepts the requester (replace placeholder "<Requester>" in the filter of the query),
   # and returns all IAM Principal IDs by that requester during a specific time range.
   #
   # For expected inputs and scenarios, refer to AMS Documentation -> Tracking changes in your AMS Accelerate accounts -> Default Queries
   filter eventName="AssumeRole" AND requestParameters.tags.2.value="<Requester>"
   | sort eventTime desc
   | fields
      responseElements.assumedRoleUser.assumedRoleId as IAMPrincipalId,
      responseElements.credentials.accessKeyId as IAMSessionId,
      eventTime as EventTime
```

## 更改记录权限
<a name="acc-cr-permissions"></a>

运行更改记录查询需要以下权限：
+ **Athena**
  + 雅典娜：GetWorkGroup
  + 雅典娜：StartQueryExecution
  + 雅典娜：ListDataCatalogs
  + 雅典娜：GetQueryExecution
  + 雅典娜：GetQueryResults
  + 雅典娜：BatchGetNamedQuery
  + 雅典娜：ListWorkGroups
  + 雅典娜：UpdateWorkGroup
  + 雅典娜：GetNamedQuery
  + 雅典娜：ListQueryExecutions
  + 雅典娜：ListNamedQueries
+ **AWS KMS**
  + kms:Decrypt
  + AWS KMS 的 AMSCloudTrailLogManagement密钥 ID 或您的 AWS KMS 密钥 ID（如果 Accelerate 使用您的 CloudTrail 跟踪事件 Amazon S3 存储桶数据存储，则使用 [SSE-KMS](https://docs.aws.amazon.com/AmazonS3/latest/userguide/UsingKMSEncryption.html) 加密）。
+ **AWS Glue**
  + 胶水：GetDatabase
  + 胶水：GetTables
  + 胶水：GetDatabases
  + 胶水：GetTable
+ **亚马逊 S3 读取权限**
  + 亚马逊 S3 存储桶 CloudTrail 数据存储：ams-a *AccountId*-cloudtrail-，或者*primary region*你的亚马逊 S3 存储桶名称，跟踪事件 Ama CloudTrail zon S3 存储桶数据存储。
+ **亚马逊 S3 写入权限**
  + Athena 事件查询结果 Amazon S3 存储桶：ams-a athena-results-*AccountId* *primary region*