IAM用SDK于 Rust 的示例 - AWS SDK代码示例

AWS 文档 AWS SDK示例 GitHub 存储库中还有更多SDK示例

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

IAM用SDK于 Rust 的示例

以下代码示例向您展示了如何使用 for Rust 来执行操作和实现常见场景IAM。 AWS SDK

基础知识是向您展示如何在服务中执行基本操作的代码示例。

操作是大型程序的代码摘录,必须在上下文中运行。您可以通过操作了解如何调用单个服务函数,还可以通过函数相关场景的上下文查看操作。

每个示例都包含一个指向完整源代码的链接,您可以在其中找到有关如何在上下文中设置和运行代码的说明。

开始使用

以下代码示例展示了如何开始使用IAM。

SDK对于 Rust
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

来自 src/bin/hello.rs。

use aws_sdk_iam::error::SdkError; use aws_sdk_iam::operation::list_policies::ListPoliciesError; use clap::Parser; const PATH_PREFIX_HELP: &str = "The path prefix for filtering the results."; #[derive(Debug, clap::Parser)] #[command(about)] struct HelloScenarioArgs { #[arg(long, default_value="/", help=PATH_PREFIX_HELP)] pub path_prefix: String, } #[tokio::main] async fn main() -> Result<(), SdkError<ListPoliciesError>> { let sdk_config = aws_config::load_from_env().await; let client = aws_sdk_iam::Client::new(&sdk_config); let args = HelloScenarioArgs::parse(); iam_service::list_policies(client, args.path_prefix).await?; Ok(()) }

来自 src/ .r iam-service-lib s.

pub async fn list_policies( client: iamClient, path_prefix: String, ) -> Result<Vec<String>, SdkError<ListPoliciesError>> { let list_policies = client .list_policies() .path_prefix(path_prefix) .scope(PolicyScopeType::Local) .into_paginator() .items() .send() .try_collect() .await?; let policy_names = list_policies .into_iter() .map(|p| { let name = p .policy_name .unwrap_or_else(|| "Missing Policy Name".to_string()); println!("{}", name); name }) .collect(); Ok(policy_names) }
  • 有关API详细信息,请参见ListPolicies中的 Rust AWS SDK API 参考

基础知识

以下代码示例展示了如何创建用户并代入角色。

警告

为避免安全风险,在开发专用软件或处理真实数据时,请勿使用IAM用户进行身份验证。而是使用与身份提供商的联合身份验证,例如 AWS IAM Identity Center

  • 创建没有权限的用户。

  • 创建授予列出账户的 Amazon S3 存储桶的权限的角色

  • 添加策略以允许用户代入该角色。

  • 代入角色并使用临时凭证列出 S3 存储桶,然后清除资源。

SDK对于 Rust
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

use aws_config::meta::region::RegionProviderChain; use aws_sdk_iam::Error as iamError; use aws_sdk_iam::{config::Credentials as iamCredentials, config::Region, Client as iamClient}; use aws_sdk_s3::Client as s3Client; use aws_sdk_sts::Client as stsClient; use tokio::time::{sleep, Duration}; use uuid::Uuid; #[tokio::main] async fn main() -> Result<(), iamError> { let (client, uuid, list_all_buckets_policy_document, inline_policy_document) = initialize_variables().await; if let Err(e) = run_iam_operations( client, uuid, list_all_buckets_policy_document, inline_policy_document, ) .await { println!("{:?}", e); }; Ok(()) } async fn initialize_variables() -> (iamClient, String, String, String) { let region_provider = RegionProviderChain::first_try(Region::new("us-west-2")); let shared_config = aws_config::from_env().region(region_provider).load().await; let client = iamClient::new(&shared_config); let uuid = Uuid::new_v4().to_string(); let list_all_buckets_policy_document = "{ \"Version\": \"2012-10-17\", \"Statement\": [{ \"Effect\": \"Allow\", \"Action\": \"s3:ListAllMyBuckets\", \"Resource\": \"arn:aws:s3:::*\"}] }" .to_string(); let inline_policy_document = "{ \"Version\": \"2012-10-17\", \"Statement\": [{ \"Effect\": \"Allow\", \"Action\": \"sts:AssumeRole\", \"Resource\": \"{}\"}] }" .to_string(); ( client, uuid, list_all_buckets_policy_document, inline_policy_document, ) } async fn run_iam_operations( client: iamClient, uuid: String, list_all_buckets_policy_document: String, inline_policy_document: String, ) -> Result<(), iamError> { let user = iam_service::create_user(&client, &format!("{}{}", "iam_demo_user_", uuid)).await?; println!("Created the user with the name: {}", user.user_name()); let key = iam_service::create_access_key(&client, user.user_name()).await?; let assume_role_policy_document = "{ \"Version\": \"2012-10-17\", \"Statement\": [{ \"Effect\": \"Allow\", \"Principal\": {\"AWS\": \"{}\"}, \"Action\": \"sts:AssumeRole\" }] }" .to_string() .replace("{}", user.arn()); let assume_role_role = iam_service::create_role( &client, &format!("{}{}", "iam_demo_role_", uuid), &assume_role_policy_document, ) .await?; println!("Created the role with the ARN: {}", assume_role_role.arn()); let list_all_buckets_policy = iam_service::create_policy( &client, &format!("{}{}", "iam_demo_policy_", uuid), &list_all_buckets_policy_document, ) .await?; println!( "Created policy: {}", list_all_buckets_policy.policy_name.as_ref().unwrap() ); let attach_role_policy_result = iam_service::attach_role_policy(&client, &assume_role_role, &list_all_buckets_policy) .await?; println!( "Attached the policy to the role: {:?}", attach_role_policy_result ); let inline_policy_name = format!("{}{}", "iam_demo_inline_policy_", uuid); let inline_policy_document = inline_policy_document.replace("{}", assume_role_role.arn()); iam_service::create_user_policy(&client, &user, &inline_policy_name, &inline_policy_document) .await?; println!("Created inline policy."); //First, fail to list the buckets with the user. let creds = iamCredentials::from_keys(key.access_key_id(), key.secret_access_key(), None); let fail_config = aws_config::from_env() .credentials_provider(creds.clone()) .load() .await; println!("Fail config: {:?}", fail_config); let fail_client: s3Client = s3Client::new(&fail_config); match fail_client.list_buckets().send().await { Ok(e) => { println!("This should not run. {:?}", e); } Err(e) => { println!("Successfully failed with error: {:?}", e) } } let sts_config = aws_config::from_env() .credentials_provider(creds.clone()) .load() .await; let sts_client: stsClient = stsClient::new(&sts_config); sleep(Duration::from_secs(10)).await; let assumed_role = sts_client .assume_role() .role_arn(assume_role_role.arn()) .role_session_name(&format!("{}{}", "iam_demo_assumerole_session_", uuid)) .send() .await; println!("Assumed role: {:?}", assumed_role); sleep(Duration::from_secs(10)).await; let assumed_credentials = iamCredentials::from_keys( assumed_role .as_ref() .unwrap() .credentials .as_ref() .unwrap() .access_key_id(), assumed_role .as_ref() .unwrap() .credentials .as_ref() .unwrap() .secret_access_key(), Some( assumed_role .as_ref() .unwrap() .credentials .as_ref() .unwrap() .session_token .clone(), ), ); let succeed_config = aws_config::from_env() .credentials_provider(assumed_credentials) .load() .await; println!("succeed config: {:?}", succeed_config); let succeed_client: s3Client = s3Client::new(&succeed_config); sleep(Duration::from_secs(10)).await; match succeed_client.list_buckets().send().await { Ok(_) => { println!("This should now run successfully.") } Err(e) => { println!("This should not run. {:?}", e); panic!() } } //Clean up. iam_service::detach_role_policy( &client, assume_role_role.role_name(), list_all_buckets_policy.arn().unwrap_or_default(), ) .await?; iam_service::delete_policy(&client, list_all_buckets_policy).await?; iam_service::delete_role(&client, &assume_role_role).await?; println!("Deleted role {}", assume_role_role.role_name()); iam_service::delete_access_key(&client, &user, &key).await?; println!("Deleted key for {}", key.user_name()); iam_service::delete_user_policy(&client, &user, &inline_policy_name).await?; println!("Deleted inline user policy: {}", inline_policy_name); iam_service::delete_user(&client, &user).await?; println!("Deleted user {}", user.user_name()); Ok(()) }

操作

以下代码示例显示了如何使用AttachRolePolicy

SDK对于 Rust
注意

还有更多相关信息 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详细信息,请参见AttachRolePolicy中的 Rust AWS SDK API 参考

以下代码示例显示了如何使用AttachUserPolicy

SDK对于 Rust
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

pub async fn attach_user_policy( client: &iamClient, user_name: &str, policy_arn: &str, ) -> Result<(), iamError> { client .attach_user_policy() .user_name(user_name) .policy_arn(policy_arn) .send() .await?; Ok(()) }
  • 有关API详细信息,请参见AttachUserPolicy中的 Rust AWS SDK API 参考

以下代码示例显示了如何使用CreateAccessKey

SDK对于 Rust
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

pub async fn create_access_key(client: &iamClient, user_name: &str) -> Result<AccessKey, iamError> { let mut tries: i32 = 0; let max_tries: i32 = 10; let response: Result<CreateAccessKeyOutput, SdkError<CreateAccessKeyError>> = loop { match client.create_access_key().user_name(user_name).send().await { Ok(inner_response) => { break Ok(inner_response); } Err(e) => { tries += 1; if tries > max_tries { break Err(e); } sleep(Duration::from_secs(2)).await; } } }; Ok(response.unwrap().access_key.unwrap()) }
  • 有关API详细信息,请参见CreateAccessKey中的 Rust AWS SDK API 参考

以下代码示例显示了如何使用CreatePolicy

SDK对于 Rust
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

pub async fn create_policy( client: &iamClient, policy_name: &str, policy_document: &str, ) -> Result<Policy, iamError> { let policy = client .create_policy() .policy_name(policy_name) .policy_document(policy_document) .send() .await?; Ok(policy.policy.unwrap()) }
  • 有关API详细信息,请参见CreatePolicy中的 Rust AWS SDK API 参考

以下代码示例显示了如何使用CreateRole

SDK对于 Rust
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

pub async fn create_role( client: &iamClient, role_name: &str, role_policy_document: &str, ) -> Result<Role, iamError> { let response: CreateRoleOutput = loop { if let Ok(response) = client .create_role() .role_name(role_name) .assume_role_policy_document(role_policy_document) .send() .await { break response; } }; Ok(response.role.unwrap()) }
  • 有关API详细信息,请参见CreateRole中的 Rust AWS SDK API 参考

以下代码示例显示了如何使用CreateServiceLinkedRole

SDK对于 Rust
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

pub async fn create_service_linked_role( client: &iamClient, aws_service_name: String, custom_suffix: Option<String>, description: Option<String>, ) -> Result<CreateServiceLinkedRoleOutput, SdkError<CreateServiceLinkedRoleError>> { let response = client .create_service_linked_role() .aws_service_name(aws_service_name) .set_custom_suffix(custom_suffix) .set_description(description) .send() .await?; Ok(response) }

以下代码示例显示了如何使用CreateUser

SDK对于 Rust
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

pub async fn create_user(client: &iamClient, user_name: &str) -> Result<User, iamError> { let response = client.create_user().user_name(user_name).send().await?; Ok(response.user.unwrap()) }
  • 有关API详细信息,请参见CreateUser中的 Rust AWS SDK API 参考

以下代码示例显示了如何使用DeleteAccessKey

SDK对于 Rust
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

pub async fn delete_access_key( client: &iamClient, user: &User, key: &AccessKey, ) -> Result<(), iamError> { loop { match client .delete_access_key() .user_name(user.user_name()) .access_key_id(key.access_key_id()) .send() .await { Ok(_) => { break; } Err(e) => { println!("Can't delete the access key: {:?}", e); sleep(Duration::from_secs(2)).await; } } } Ok(()) }
  • 有关API详细信息,请参见DeleteAccessKey中的 Rust AWS SDK API 参考

以下代码示例显示了如何使用DeletePolicy

SDK对于 Rust
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

pub async fn delete_policy(client: &iamClient, policy: Policy) -> Result<(), iamError> { client .delete_policy() .policy_arn(policy.arn.unwrap()) .send() .await?; Ok(()) }
  • 有关API详细信息,请参见DeletePolicy中的 Rust AWS SDK API 参考

以下代码示例显示了如何使用DeleteRole

SDK对于 Rust
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

pub async fn delete_role(client: &iamClient, role: &Role) -> Result<(), iamError> { let role = role.clone(); while client .delete_role() .role_name(role.role_name()) .send() .await .is_err() { sleep(Duration::from_secs(2)).await; } Ok(()) }
  • 有关API详细信息,请参见DeleteRole中的 Rust AWS SDK API 参考

以下代码示例显示了如何使用DeleteServiceLinkedRole

SDK对于 Rust
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

pub async fn delete_service_linked_role( client: &iamClient, role_name: &str, ) -> Result<(), iamError> { client .delete_service_linked_role() .role_name(role_name) .send() .await?; Ok(()) }

以下代码示例显示了如何使用DeleteUser

SDK对于 Rust
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

pub async fn delete_user(client: &iamClient, user: &User) -> Result<(), SdkError<DeleteUserError>> { let user = user.clone(); let mut tries: i32 = 0; let max_tries: i32 = 10; let response: Result<(), SdkError<DeleteUserError>> = loop { match client .delete_user() .user_name(user.user_name()) .send() .await { Ok(_) => { break Ok(()); } Err(e) => { tries += 1; if tries > max_tries { break Err(e); } sleep(Duration::from_secs(2)).await; } } }; response }
  • 有关API详细信息,请参见DeleteUser中的 Rust AWS SDK API 参考

以下代码示例显示了如何使用DeleteUserPolicy

SDK对于 Rust
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

pub async fn delete_user_policy( client: &iamClient, user: &User, policy_name: &str, ) -> Result<(), SdkError<DeleteUserPolicyError>> { client .delete_user_policy() .user_name(user.user_name()) .policy_name(policy_name) .send() .await?; Ok(()) }
  • 有关API详细信息,请参见DeleteUserPolicy中的 Rust AWS SDK API 参考

以下代码示例显示了如何使用DetachRolePolicy

SDK对于 Rust
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

pub async fn detach_role_policy( client: &iamClient, role_name: &str, policy_arn: &str, ) -> Result<(), iamError> { client .detach_role_policy() .role_name(role_name) .policy_arn(policy_arn) .send() .await?; Ok(()) }
  • 有关API详细信息,请参见DetachRolePolicy中的 Rust AWS SDK API 参考

以下代码示例显示了如何使用DetachUserPolicy

SDK对于 Rust
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

pub async fn detach_user_policy( client: &iamClient, user_name: &str, policy_arn: &str, ) -> Result<(), iamError> { client .detach_user_policy() .user_name(user_name) .policy_arn(policy_arn) .send() .await?; Ok(()) }
  • 有关API详细信息,请参见DetachUserPolicy中的 Rust AWS SDK API 参考

以下代码示例显示了如何使用GetAccountPasswordPolicy

SDK对于 Rust
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

pub async fn get_account_password_policy( client: &iamClient, ) -> Result<GetAccountPasswordPolicyOutput, SdkError<GetAccountPasswordPolicyError>> { let response = client.get_account_password_policy().send().await?; Ok(response) }

以下代码示例显示了如何使用GetRole

SDK对于 Rust
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

pub async fn get_role( client: &iamClient, role_name: String, ) -> Result<GetRoleOutput, SdkError<GetRoleError>> { let response = client.get_role().role_name(role_name).send().await?; Ok(response) }
  • 有关API详细信息,请参见GetRole中的 Rust AWS SDK API 参考

以下代码示例显示了如何使用ListAttachedRolePolicies

SDK对于 Rust
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

pub async fn list_attached_role_policies( client: &iamClient, role_name: String, path_prefix: Option<String>, marker: Option<String>, max_items: Option<i32>, ) -> Result<ListAttachedRolePoliciesOutput, SdkError<ListAttachedRolePoliciesError>> { let response = client .list_attached_role_policies() .role_name(role_name) .set_path_prefix(path_prefix) .set_marker(marker) .set_max_items(max_items) .send() .await?; Ok(response) }

以下代码示例显示了如何使用ListGroups

SDK对于 Rust
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

pub async fn list_groups( client: &iamClient, path_prefix: Option<String>, marker: Option<String>, max_items: Option<i32>, ) -> Result<ListGroupsOutput, SdkError<ListGroupsError>> { let response = client .list_groups() .set_path_prefix(path_prefix) .set_marker(marker) .set_max_items(max_items) .send() .await?; Ok(response) }
  • 有关API详细信息,请参见ListGroups中的 Rust AWS SDK API 参考

以下代码示例显示了如何使用ListPolicies

SDK对于 Rust
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

pub async fn list_policies( client: iamClient, path_prefix: String, ) -> Result<Vec<String>, SdkError<ListPoliciesError>> { let list_policies = client .list_policies() .path_prefix(path_prefix) .scope(PolicyScopeType::Local) .into_paginator() .items() .send() .try_collect() .await?; let policy_names = list_policies .into_iter() .map(|p| { let name = p .policy_name .unwrap_or_else(|| "Missing Policy Name".to_string()); println!("{}", name); name }) .collect(); Ok(policy_names) }
  • 有关API详细信息,请参见ListPolicies中的 Rust AWS SDK API 参考

以下代码示例显示了如何使用ListRolePolicies

SDK对于 Rust
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

pub async fn list_role_policies( client: &iamClient, role_name: &str, marker: Option<String>, max_items: Option<i32>, ) -> Result<ListRolePoliciesOutput, SdkError<ListRolePoliciesError>> { let response = client .list_role_policies() .role_name(role_name) .set_marker(marker) .set_max_items(max_items) .send() .await?; Ok(response) }
  • 有关API详细信息,请参见ListRolePolicies中的 Rust AWS SDK API 参考

以下代码示例显示了如何使用ListRoles

SDK对于 Rust
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

pub async fn list_roles( client: &iamClient, path_prefix: Option<String>, marker: Option<String>, max_items: Option<i32>, ) -> Result<ListRolesOutput, SdkError<ListRolesError>> { let response = client .list_roles() .set_path_prefix(path_prefix) .set_marker(marker) .set_max_items(max_items) .send() .await?; Ok(response) }
  • 有关API详细信息,请参见ListRoles中的 Rust AWS SDK API 参考

以下代码示例显示了如何使用ListSAMLProviders

SDK对于 Rust
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

pub async fn list_saml_providers( client: &Client, ) -> Result<ListSamlProvidersOutput, SdkError<ListSAMLProvidersError>> { let response = client.list_saml_providers().send().await?; Ok(response) }

以下代码示例显示了如何使用ListUsers

SDK对于 Rust
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

pub async fn list_users( client: &iamClient, path_prefix: Option<String>, marker: Option<String>, max_items: Option<i32>, ) -> Result<ListUsersOutput, SdkError<ListUsersError>> { let response = client .list_users() .set_path_prefix(path_prefix) .set_marker(marker) .set_max_items(max_items) .send() .await?; Ok(response) }
  • 有关API详细信息,请参见ListUsers中的 Rust AWS SDK API 参考