

# 将 `GetContextKeysForPrincipalPolicy` 与 CLI 配合使用
<a name="iam_example_iam_GetContextKeysForPrincipalPolicy_section"></a>

以下代码示例演示如何使用 `GetContextKeysForPrincipalPolicy`。

------
#### [ CLI ]

**AWS CLI**  
**列出与 IAM 主体关联的所有策略引用的上下文键**  
以下 `get-context-keys-for-principal-policy` 命令检索附加到用户 `saanvi` 及其所属任何组的所有策略。然后，该命令会解析每个策略并列出这些策略使用的上下文键。使用此命令来确定必须提供哪些上下文键值才能成功使用 `simulate-custom-policy` 和 `simulate-principal-policy` 命令。您还可以使用 `get-context-keys-for-custom-policy` 命令检索任意 JSON 策略使用的上下文键列表。  

```
aws iam get-context-keys-for-principal-policy \
   --policy-source-arn arn:aws:iam::123456789012:user/saanvi
```
输出：  

```
{
    "ContextKeyNames": [
        "aws:username",
        "aws:CurrentTime"
    ]
}
```
有关更多信息，请参阅《AWS IAM 用户指南》**中的[使用 IAM Policy Simulator（AWS CLI 和 AWS API）](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_testing-policies.html#policies-simulator-using-api)。  
+  有关 API 详细信息，请参阅《AWS CLI 命令参考》**中的 [GetContextKeysForPrincipalPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/get-context-keys-for-principal-policy.html)。

------
#### [ PowerShell ]

**适用于 PowerShell V4 的工具**  
**示例 1：此示例获取所提供的策略 json 中和附加到 IAM 实体（用户/角色等）的策略中存在的所有上下文键。对于 -PolicyInputList，您可用逗号分隔值的形式提供多个值列表。**  

```
$policy1 = '{"Version":"2012-10-17",		 	 	 "Statement":{"Effect":"Allow","Action":"dynamodb:*","Resource":"arn:aws:dynamodb:us-west-2:123456789012:table/","Condition":{"DateGreaterThan":{"aws:CurrentTime":"2015-08-16T12:00:00Z"}}}}'
$policy2 = '{"Version":"2012-10-17",		 	 	 "Statement":{"Effect":"Allow","Action":"dynamodb:*","Resource":"arn:aws:dynamodb:us-west-2:123456789012:table/"}}'
Get-IAMContextKeysForPrincipalPolicy -PolicyInputList $policy1,$policy2 -PolicySourceArn arn:aws:iam::852640994763:user/TestUser
```
+  有关 API 详细信息，请参阅《AWS Tools for PowerShell Cmdlet Reference (V4)》**中的 [GetContextKeysForPrincipalPolicy](https://docs.aws.amazon.com/powershell/v4/reference)。

**Tools for PowerShell V5**  
**示例 1：此示例获取所提供的策略 json 中和附加到 IAM 实体（用户/角色等）的策略中存在的所有上下文键。对于 -PolicyInputList，您可用逗号分隔值的形式提供多个值列表。**  

```
$policy1 = '{"Version":"2012-10-17",		 	 	 "Statement":{"Effect":"Allow","Action":"dynamodb:*","Resource":"arn:aws:dynamodb:us-west-2:123456789012:table/","Condition":{"DateGreaterThan":{"aws:CurrentTime":"2015-08-16T12:00:00Z"}}}}'
$policy2 = '{"Version":"2012-10-17",		 	 	 "Statement":{"Effect":"Allow","Action":"dynamodb:*","Resource":"arn:aws:dynamodb:us-west-2:123456789012:table/"}}'
Get-IAMContextKeysForPrincipalPolicy -PolicyInputList $policy1,$policy2 -PolicySourceArn arn:aws:iam::852640994763:user/TestUser
```
+  有关 API 详细信息，请参阅《*AWS Tools for PowerShell Cmdlet 参考 (V5)*》中的 [GetContextKeysForPrincipalPolicy](https://docs.aws.amazon.com/powershell/v5/reference)。

------

有关 AWS SDK 开发人员指南和代码示例的完整列表，请参阅 [将此服务与 AWS SDK 结合使用](sdk-general-information-section.md) 本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。