

# 将 `PutUserPolicy` 与 AWS SDK 或 CLI 配合使用
<a name="iam_example_iam_PutUserPolicy_section"></a>

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

操作示例是大型程序的代码摘录，必须在上下文中运行。在以下代码示例中，您可以查看此操作的上下文：
+  [了解基本功能](iam_example_iam_Scenario_CreateUserAssumeRole_section.md) 

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

**AWS CLI**  
**将策略附加到 IAM 用户**  
以下 `put-user-policy` 命令可将策略附加到名为 `Bob` 的 IAM 用户。  

```
aws iam put-user-policy \
    --user-name Bob \
    --policy-name ExamplePolicy \
    --policy-document file://AdminPolicy.json
```
此命令不生成任何输出。  
该策略在 *AdminPolicy.json* 文件中定义为 JSON 文档。（文件名和扩展名没有意义。）  
有关更多信息，请参阅《AWS IAM 用户指南》**中的[添加和删​​除 IAM 身份权限](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_manage-attach-detach.html)。  
+  有关 API 详细信息，请参阅《AWS CLI 命令参考》**中的 [PutUserPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/put-user-policy.html)。

------
#### [ Go ]

**适用于 Go 的 SDK V2**  
 查看 GitHub，了解更多信息。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/iam#code-examples)中查找完整示例，了解如何进行设置和运行。

```
import (
	"context"
	"encoding/json"
	"errors"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/iam"
	"github.com/aws/aws-sdk-go-v2/service/iam/types"
	"github.com/aws/smithy-go"
)

// UserWrapper encapsulates user actions used in the examples.
// It contains an IAM service client that is used to perform user actions.
type UserWrapper struct {
	IamClient *iam.Client
}



// CreateUserPolicy adds an inline policy to a user. This example creates a policy that
// grants a list of actions on a specified role.
// PolicyDocument shows how to work with a policy document as a data structure and
// serialize it to JSON by using Go's JSON marshaler.
func (wrapper UserWrapper) CreateUserPolicy(ctx context.Context, userName string, policyName string, actions []string,
	roleArn string) error {
	policyDoc := PolicyDocument{
		Version: "2012-10-17",
		Statement: []PolicyStatement{{
			Effect:   "Allow",
			Action:   actions,
			Resource: aws.String(roleArn),
		}},
	}
	policyBytes, err := json.Marshal(policyDoc)
	if err != nil {
		log.Printf("Couldn't create policy document for %v. Here's why: %v\n", roleArn, err)
		return err
	}
	_, err = wrapper.IamClient.PutUserPolicy(ctx, &iam.PutUserPolicyInput{
		PolicyDocument: aws.String(string(policyBytes)),
		PolicyName:     aws.String(policyName),
		UserName:       aws.String(userName),
	})
	if err != nil {
		log.Printf("Couldn't create policy for user %v. Here's why: %v\n", userName, err)
	}
	return err
}
```
+  有关 API 详细信息，请参阅*《适用于 Go 的 AWS SDK API Reference》*中的 [PutUserPolicy](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.PutUserPolicy)。

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

**适用于 PowerShell V4 的工具**  
**示例 1：此示例创建一个名为 `EC2AccessPolicy` 的内联策略并将其嵌入到 IAM 用户 `Bob` 中。如果已经存在同名的内联策略，则该策略将被覆盖。JSON 策略内容来自文件 `EC2AccessPolicy.json`。请注意，必须使用 `-Raw` 参数才能成功处理 JSON 文件的内容。**  

```
Write-IAMUserPolicy -UserName Bob -PolicyName EC2AccessPolicy -PolicyDocument (Get-Content -Raw EC2AccessPolicy.json)
```
+  有关 API 详细信息，请参阅《AWS Tools for PowerShell Cmdlet Reference (V4)》**中的 [PutUserPolicy](https://docs.aws.amazon.com/powershell/v4/reference)。

**Tools for PowerShell V5**  
**示例 1：此示例创建一个名为 `EC2AccessPolicy` 的内联策略并将其嵌入到 IAM 用户 `Bob` 中。如果已经存在同名的内联策略，则该策略将被覆盖。JSON 策略内容来自文件 `EC2AccessPolicy.json`。请注意，必须使用 `-Raw` 参数才能成功处理 JSON 文件的内容。**  

```
Write-IAMUserPolicy -UserName Bob -PolicyName EC2AccessPolicy -PolicyDocument (Get-Content -Raw EC2AccessPolicy.json)
```
+  有关 API 详细信息，请参阅《*AWS Tools for PowerShell Cmdlet Reference (V5)*》中的 [PutUserPolicy](https://docs.aws.amazon.com/powershell/v5/reference)。

------
#### [ Ruby ]

**适用于 Ruby 的 SDK**  
 查看 GitHub，了解更多信息。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/iam#code-examples)中查找完整示例，了解如何进行设置和运行。

```
  # Creates an inline policy for a specified user.
  # @param username [String] The name of the IAM user.
  # @param policy_name [String] The name of the policy to create.
  # @param policy_document [String] The JSON policy document.
  # @return [Boolean]
  def create_user_policy(username, policy_name, policy_document)
    @iam_client.put_user_policy({
                                  user_name: username,
                                  policy_name: policy_name,
                                  policy_document: policy_document
                                })
    @logger.info("Policy #{policy_name} created for user #{username}.")
    true
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Couldn't create policy #{policy_name} for user #{username}. Here's why:")
    @logger.error("\t#{e.code}: #{e.message}")
    false
  end
```
+  有关 API 详细信息，请参阅*《适用于 Ruby 的 AWS SDK API Reference》*中的 [PutUserPolicy](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/PutUserPolicy)。

------
#### [ Swift ]

**适用于 Swift 的 SDK**  
 查看 GitHub，了解更多信息。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/iam#code-examples)中查找完整示例，了解如何进行设置和运行。

```
import AWSIAM
import AWSS3


    func putUserPolicy(policyDocument: String, policyName: String, user: IAMClientTypes.User) async throws {
        let input = PutUserPolicyInput(
            policyDocument: policyDocument,
            policyName: policyName,
            userName: user.userName
        )
        do {
            _ = try await iamClient.putUserPolicy(input: input)
        } catch {
            print("ERROR: putUserPolicy:", dump(error))
            throw error
        }
    }
```
+  有关 API 详细信息，请参阅《AWS SDK for Swift API 参考》**中的 [PutUserPolicy](https://sdk.amazonaws.com/swift/api/awsiam/latest/documentation/awsiam/iamclient/putuserpolicy(input:))。

------

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