搭AttachRolePolicy配 AWS SDK或使用 CLI - AWS SDK 程式碼範例

AWS 文檔 AWS SDK示例 GitHub 回購中有更多SDK示例

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

AttachRolePolicy配 AWS SDK或使用 CLI

下列程式碼範例會示範如何使用AttachRolePolicy

動作範例是大型程式的程式碼摘錄,必須在內容中執行。您可以在下列程式碼範例的內容中看到此動作:

.NET
AWS SDK for .NET
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

/// <summary> /// Attach an IAM policy to a role. /// </summary> /// <param name="policyArn">The policy to attach.</param> /// <param name="roleName">The role that the policy will be attached to.</param> /// <returns>A Boolean value indicating the success of the action.</returns> public async Task<bool> AttachRolePolicyAsync(string policyArn, string roleName) { var response = await _IAMService.AttachRolePolicyAsync(new AttachRolePolicyRequest { PolicyArn = policyArn, RoleName = roleName, }); return response.HttpStatusCode == System.Net.HttpStatusCode.OK; }
  • 如需詳API細資訊,請參閱AWS SDK for .NET API參考AttachRolePolicy中的。

Bash
AWS CLI 與 Bash 腳本
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

############################################################################### # function errecho # # This function outputs everything sent to it to STDERR (standard error output). ############################################################################### function errecho() { printf "%s\n" "$*" 1>&2 } ############################################################################### # function iam_attach_role_policy # # This function attaches an IAM policy to a tole. # # Parameters: # -n role_name -- The name of the IAM role. # -p policy_ARN -- The IAM policy document ARN.. # # Returns: # 0 - If successful. # 1 - If it fails. ############################################################################### function iam_attach_role_policy() { local role_name policy_arn response local option OPTARG # Required to use getopts command in a function. # bashsupport disable=BP5008 function usage() { echo "function iam_attach_role_policy" echo "Attaches an AWS Identity and Access Management (IAM) policy to an IAM role." echo " -n role_name The name of the IAM role." echo " -p policy_ARN -- The IAM policy document ARN." echo "" } # Retrieve the calling parameters. while getopts "n:p:h" option; do case "${option}" in n) role_name="${OPTARG}" ;; p) policy_arn="${OPTARG}" ;; h) usage return 0 ;; \?) echo "Invalid parameter" usage return 1 ;; esac done export OPTIND=1 if [[ -z "$role_name" ]]; then errecho "ERROR: You must provide a role name with the -n parameter." usage return 1 fi if [[ -z "$policy_arn" ]]; then errecho "ERROR: You must provide a policy ARN with the -p parameter." usage return 1 fi response=$(aws iam attach-role-policy \ --role-name "$role_name" \ --policy-arn "$policy_arn") local error_code=${?} if [[ $error_code -ne 0 ]]; then aws_cli_error_log $error_code errecho "ERROR: AWS reports attach-role-policy operation failed.\n$response" return 1 fi echo "$response" return 0 }
  • 如需詳API細資訊,請參閱AWS CLI 指令參考AttachRolePolicy中的。

C++
SDK對於 C ++
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

bool AwsDoc::IAM::attachRolePolicy(const Aws::String &roleName, const Aws::String &policyArn, const Aws::Client::ClientConfiguration &clientConfig) { Aws::IAM::IAMClient iam(clientConfig); Aws::IAM::Model::ListAttachedRolePoliciesRequest list_request; list_request.SetRoleName(roleName); bool done = false; while (!done) { auto list_outcome = iam.ListAttachedRolePolicies(list_request); if (!list_outcome.IsSuccess()) { std::cerr << "Failed to list attached policies of role " << roleName << ": " << list_outcome.GetError().GetMessage() << std::endl; return false; } const auto &policies = list_outcome.GetResult().GetAttachedPolicies(); if (std::any_of(policies.cbegin(), policies.cend(), [=](const Aws::IAM::Model::AttachedPolicy &policy) { return policy.GetPolicyArn() == policyArn; })) { std::cout << "Policy " << policyArn << " is already attached to role " << roleName << std::endl; return true; } done = !list_outcome.GetResult().GetIsTruncated(); list_request.SetMarker(list_outcome.GetResult().GetMarker()); } Aws::IAM::Model::AttachRolePolicyRequest request; request.SetRoleName(roleName); request.SetPolicyArn(policyArn); Aws::IAM::Model::AttachRolePolicyOutcome outcome = iam.AttachRolePolicy(request); if (!outcome.IsSuccess()) { std::cerr << "Failed to attach policy " << policyArn << " to role " << roleName << ": " << outcome.GetError().GetMessage() << std::endl; } else { std::cout << "Successfully attached policy " << policyArn << " to role " << roleName << std::endl; } return outcome.IsSuccess(); }
  • 如需詳API細資訊,請參閱AWS SDK for C++ API參考AttachRolePolicy中的。

CLI
AWS CLI

將受管理的策略附加到IAM角色

下列attach-role-policy命令會將名為的 AWS 受管理原則附加ReadOnlyAccess至名為的IAM角色ReadOnlyRole

aws iam attach-role-policy \ --policy-arn arn:aws:iam::aws:policy/ReadOnlyAccess \ --role-name ReadOnlyRole

此命令不會產生輸出。

如需詳細資訊,請參閱AWS IAM使用指南中的受管理策略和內嵌政策

  • 如需詳API細資訊,請參閱AWS CLI 指令參考AttachRolePolicy中的。

Go
SDK對於轉到 V2
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

// RoleWrapper encapsulates AWS Identity and Access Management (IAM) role actions // used in the examples. // It contains an IAM service client that is used to perform role actions. type RoleWrapper struct { IamClient *iam.Client } // AttachRolePolicy attaches a policy to a role. func (wrapper RoleWrapper) AttachRolePolicy(policyArn string, roleName string) error { _, err := wrapper.IamClient.AttachRolePolicy(context.TODO(), &iam.AttachRolePolicyInput{ PolicyArn: aws.String(policyArn), RoleName: aws.String(roleName), }) if err != nil { log.Printf("Couldn't attach policy %v to role %v. Here's why: %v\n", policyArn, roleName, err) } return err }
  • 如需詳API細資訊,請參閱AWS SDK for Go API參考AttachRolePolicy中的。

Java
SDK對於爪哇 2.x
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.iam.IamClient; import software.amazon.awssdk.services.iam.model.IamException; import software.amazon.awssdk.services.iam.model.AttachRolePolicyRequest; import software.amazon.awssdk.services.iam.model.AttachedPolicy; import software.amazon.awssdk.services.iam.model.ListAttachedRolePoliciesRequest; import software.amazon.awssdk.services.iam.model.ListAttachedRolePoliciesResponse; import java.util.List; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class AttachRolePolicy { public static void main(String[] args) { final String usage = """ Usage: <roleName> <policyArn>\s Where: roleName - A role name that you can obtain from the AWS Management Console.\s policyArn - A policy ARN that you can obtain from the AWS Management Console.\s """; if (args.length != 2) { System.out.println(usage); System.exit(1); } String roleName = args[0]; String policyArn = args[1]; Region region = Region.AWS_GLOBAL; IamClient iam = IamClient.builder() .region(region) .build(); attachIAMRolePolicy(iam, roleName, policyArn); iam.close(); } public static void attachIAMRolePolicy(IamClient iam, String roleName, String policyArn) { try { ListAttachedRolePoliciesRequest request = ListAttachedRolePoliciesRequest.builder() .roleName(roleName) .build(); ListAttachedRolePoliciesResponse response = iam.listAttachedRolePolicies(request); List<AttachedPolicy> attachedPolicies = response.attachedPolicies(); // Ensure that the policy is not attached to this role String polArn = ""; for (AttachedPolicy policy : attachedPolicies) { polArn = policy.policyArn(); if (polArn.compareTo(policyArn) == 0) { System.out.println(roleName + " policy is already attached to this role."); return; } } AttachRolePolicyRequest attachRequest = AttachRolePolicyRequest.builder() .roleName(roleName) .policyArn(policyArn) .build(); iam.attachRolePolicy(attachRequest); System.out.println("Successfully attached policy " + policyArn + " to role " + roleName); } catch (IamException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } System.out.println("Done"); } }
  • 如需詳API細資訊,請參閱AWS SDK for Java 2.x API參考AttachRolePolicy中的。

JavaScript
SDK對於 JavaScript (3)
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

連接政策。

import { AttachRolePolicyCommand, IAMClient } from "@aws-sdk/client-iam"; const client = new IAMClient({}); /** * * @param {string} policyArn * @param {string} roleName */ export const attachRolePolicy = (policyArn, roleName) => { const command = new AttachRolePolicyCommand({ PolicyArn: policyArn, RoleName: roleName, }); return client.send(command); };
SDK對於 JavaScript (第 2 個)
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

// Load the AWS SDK for Node.js var AWS = require("aws-sdk"); // Set the region AWS.config.update({ region: "REGION" }); // Create the IAM service object var iam = new AWS.IAM({ apiVersion: "2010-05-08" }); var paramsRoleList = { RoleName: process.argv[2], }; iam.listAttachedRolePolicies(paramsRoleList, function (err, data) { if (err) { console.log("Error", err); } else { var myRolePolicies = data.AttachedPolicies; myRolePolicies.forEach(function (val, index, array) { if (myRolePolicies[index].PolicyName === "AmazonDynamoDBFullAccess") { console.log( "AmazonDynamoDBFullAccess is already attached to this role." ); process.exit(); } }); var params = { PolicyArn: "arn:aws:iam::aws:policy/AmazonDynamoDBFullAccess", RoleName: process.argv[2], }; iam.attachRolePolicy(params, function (err, data) { if (err) { console.log("Unable to attach policy to role", err); } else { console.log("Role attached successfully"); } }); } });
Kotlin
SDK對於科特林
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

suspend fun attachIAMRolePolicy( roleNameVal: String, policyArnVal: String, ) { val request = ListAttachedRolePoliciesRequest { roleName = roleNameVal } IamClient { region = "AWS_GLOBAL" }.use { iamClient -> val response = iamClient.listAttachedRolePolicies(request) val attachedPolicies = response.attachedPolicies // Ensure that the policy is not attached to this role. val checkStatus: Int if (attachedPolicies != null) { checkStatus = checkList(attachedPolicies, policyArnVal) if (checkStatus == -1) { return } } val policyRequest = AttachRolePolicyRequest { roleName = roleNameVal policyArn = policyArnVal } iamClient.attachRolePolicy(policyRequest) println("Successfully attached policy $policyArnVal to role $roleNameVal") } } fun checkList( attachedPolicies: List<AttachedPolicy>, policyArnVal: String, ): Int { for (policy in attachedPolicies) { val polArn = policy.policyArn.toString() if (polArn.compareTo(policyArnVal) == 0) { println("The policy is already attached to this role.") return -1 } } return 0 }
  • 有API關詳細資訊,請參閱AttachRolePolicyAWS SDK的以取得 Kotlin API 的參考資料

PHP
適用於 PHP 的 SDK
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

$uuid = uniqid(); $service = new IAMService(); $assumeRolePolicyDocument = "{ \"Version\": \"2012-10-17\", \"Statement\": [{ \"Effect\": \"Allow\", \"Principal\": {\"AWS\": \"{$user['Arn']}\"}, \"Action\": \"sts:AssumeRole\" }] }"; $assumeRoleRole = $service->createRole("iam_demo_role_$uuid", $assumeRolePolicyDocument); echo "Created role: {$assumeRoleRole['RoleName']}\n"; $listAllBucketsPolicyDocument = "{ \"Version\": \"2012-10-17\", \"Statement\": [{ \"Effect\": \"Allow\", \"Action\": \"s3:ListAllMyBuckets\", \"Resource\": \"arn:aws:s3:::*\"}] }"; $listAllBucketsPolicy = $service->createPolicy("iam_demo_policy_$uuid", $listAllBucketsPolicyDocument); echo "Created policy: {$listAllBucketsPolicy['PolicyName']}\n"; $service->attachRolePolicy($assumeRoleRole['RoleName'], $listAllBucketsPolicy['Arn']); public function attachRolePolicy($roleName, $policyArn) { return $this->customWaiter(function () use ($roleName, $policyArn) { $this->iamClient->attachRolePolicy([ 'PolicyArn' => $policyArn, 'RoleName' => $roleName, ]); }); }
  • 如需詳API細資訊,請參閱AWS SDK for PHP API參考AttachRolePolicy中的。

PowerShell
適用的工具 PowerShell

範例 1:此範例會將名為的 AWS 受管理策略附加SecurityAudit至IAM角色CoSecurityAuditors。承擔該角色的使用者會立即受到該原則最新版本中定義的權限影響。

Register-IAMRolePolicy -RoleName CoSecurityAuditors -PolicyArn arn:aws:iam::aws:policy/SecurityAudit
  • 如需詳API細資訊,請參閱AWS Tools for PowerShell 指令程AttachRolePolicy式參考中的。

Python
SDK對於 Python(肉毒桿菌 3)
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

使用 Boto3 Policy 物件將政策連接至角色。

def attach_to_role(role_name, policy_arn): """ Attaches a policy to a role. :param role_name: The name of the role. **Note** this is the name, not the ARN. :param policy_arn: The ARN of the policy. """ try: iam.Policy(policy_arn).attach_role(RoleName=role_name) logger.info("Attached policy %s to role %s.", policy_arn, role_name) except ClientError: logger.exception("Couldn't attach policy %s to role %s.", policy_arn, role_name) raise

使用 Boto3 Role 物件將政策連接至角色。

def attach_policy(role_name, policy_arn): """ Attaches a policy to a role. :param role_name: The name of the role. **Note** this is the name, not the ARN. :param policy_arn: The ARN of the policy. """ try: iam.Role(role_name).attach_policy(PolicyArn=policy_arn) logger.info("Attached policy %s to role %s.", policy_arn, role_name) except ClientError: logger.exception("Couldn't attach policy %s to role %s.", policy_arn, role_name) raise
  • 如需詳API細資訊,請參閱AttachRolePolicyAWS SDK的〈〉以取得 Python (Boto3) API 參考資料。

Ruby
SDK對於紅寶石
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

此範例模組會列出、建立、附加和解除連結角色原則。

# Manages policies in AWS Identity and Access Management (IAM) class RolePolicyManager # Initialize with an AWS IAM client # # @param iam_client [Aws::IAM::Client] An initialized IAM client def initialize(iam_client, logger: Logger.new($stdout)) @iam_client = iam_client @logger = logger @logger.progname = "PolicyManager" end # Creates a policy # # @param policy_name [String] The name of the policy # @param policy_document [Hash] The policy document # @return [String] The policy ARN if successful, otherwise nil def create_policy(policy_name, policy_document) response = @iam_client.create_policy( policy_name: policy_name, policy_document: policy_document.to_json ) response.policy.arn rescue Aws::IAM::Errors::ServiceError => e @logger.error("Error creating policy: #{e.message}") nil end # Fetches an IAM policy by its ARN # @param policy_arn [String] the ARN of the IAM policy to retrieve # @return [Aws::IAM::Types::GetPolicyResponse] the policy object if found def get_policy(policy_arn) response = @iam_client.get_policy(policy_arn: policy_arn) policy = response.policy @logger.info("Got policy '#{policy.policy_name}'. Its ID is: #{policy.policy_id}.") policy rescue Aws::IAM::Errors::NoSuchEntity @logger.error("Couldn't get policy '#{policy_arn}'. The policy does not exist.") raise rescue Aws::IAM::Errors::ServiceError => e @logger.error("Couldn't get policy '#{policy_arn}'. Here's why: #{e.code}: #{e.message}") raise end # Attaches a policy to a role # # @param role_name [String] The name of the role # @param policy_arn [String] The policy ARN # @return [Boolean] true if successful, false otherwise def attach_policy_to_role(role_name, policy_arn) @iam_client.attach_role_policy( role_name: role_name, policy_arn: policy_arn ) true rescue Aws::IAM::Errors::ServiceError => e @logger.error("Error attaching policy to role: #{e.message}") false end # Lists policy ARNs attached to a role # # @param role_name [String] The name of the role # @return [Array<String>] List of policy ARNs def list_attached_policy_arns(role_name) response = @iam_client.list_attached_role_policies(role_name: role_name) response.attached_policies.map(&:policy_arn) rescue Aws::IAM::Errors::ServiceError => e @logger.error("Error listing policies attached to role: #{e.message}") [] end # Detaches a policy from a role # # @param role_name [String] The name of the role # @param policy_arn [String] The policy ARN # @return [Boolean] true if successful, false otherwise def detach_policy_from_role(role_name, policy_arn) @iam_client.detach_role_policy( role_name: role_name, policy_arn: policy_arn ) true rescue Aws::IAM::Errors::ServiceError => e @logger.error("Error detaching policy from role: #{e.message}") false end end
  • 如需詳API細資訊,請參閱AWS SDK for Ruby API參考AttachRolePolicy中的。

Rust
SDK對於銹
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

pub async fn attach_role_policy( client: &iamClient, role: &Role, policy: &Policy, ) -> Result<AttachRolePolicyOutput, SdkError<AttachRolePolicyError>> { client .attach_role_policy() .role_name(role.role_name()) .policy_arn(policy.arn().unwrap_or_default()) .send() .await }
  • 如需詳API細資訊,請參閱AttachRolePolicyAWS SDK的以取得 Rust API 參考

Swift
SDK為斯威夫特
注意

這是預覽版的售前版說明文件。SDK內容可能變動。

注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

public func attachRolePolicy(role: String, policyArn: String) async throws { let input = AttachRolePolicyInput( policyArn: policyArn, roleName: role ) do { _ = try await client.attachRolePolicy(input: input) } catch { throw error } }
  • 有API關詳細信息,請參閱AttachRolePolicyAWS SDK的以獲取 Swift API 參考