Peran RAM instans memungkinkan Instance ECS mengasumsikan peran dengan izin tertentu. Jika aplikasi yang Anda kelola sendiri dideploy pada Instance ECS Alibaba Cloud, Anda dapat menggunakan peran RAM instans untuk mengakses KMS tanpa hardcoding kredensial akses. Topik ini menjelaskan cara menggunakan peran RAM instans untuk mengakses KMS.
Lingkup
Alibaba Cloud SDK: Digunakan untuk melakukan operasi lapisan kontrol.
Credentials SDK: Termasuk Secrets Manager Client, Secrets Manager JDBC Client, dan RAM secret plug-in. Digunakan untuk mengambil nilai rahasia.
Prasyarat
Instance ECS berada dalam VPC.
Hanya satu peran RAM yang dapat disambungkan ke satu Instance ECS dalam satu waktu.
Jika Anda adalah Pengguna RAM, mintalah izin yang diperlukan dari administrator Akun Alibaba Cloud Anda untuk mengonfigurasi peran RAM. Untuk informasi lebih lanjut, lihat peran RAM instans.
Langkah 1: Buat peran RAM dan berikan izin
Konsol RAM
Buat peran RAM dan atur entitas tepercayanya menjadi layanan Alibaba Cloud.
Login ke Konsol RAM.
Pada panel navigasi di sebelah kiri, pilih .
Pada halaman Roles, klik Create Role dan ikuti petunjuk di layar. Konfigurasikan parameter berikut dan sesuaikan parameter lainnya sesuai kebutuhan.
Nama peran: Topik ini menggunakan EcsRamRoleTest sebagai contoh.
Tipe entitas tepercaya: Pilih Alibaba Cloud Service.
Pilih layanan tepercaya: Pilih ECS.
Berikan izin kepada peran RAM untuk mengakses KMS.
Secara default, peran RAM baru tidak memiliki izin apa pun. Anda harus memberikan izin kepada peran tersebut.
Pada halaman Identities > Roles, klik Attach Policy pada kolom Actions dari peran RAM yang dituju.
Pada panel Attach Policy, pilih System Policy, cari dan pilih AliyunKMSFullAccess, lalu klik OK.
RAM API
Buat peran RAM dan atur entitas tepercayanya menjadi layanan Alibaba Cloud.
Panggil operasi API CreateRole RAM dengan parameter berikut:
RoleName: Masukkan nama untuk peran RAM. Topik ini menggunakan EcsRamRoleTest sebagai contoh.AssumeRolePolicyDocument: Gunakan isi kebijakan berikut untuk mengizinkan ECS mengasumsikan peran ini.{ "Statement": [ { "Action": "sts:AssumeRole", "Effect": "Allow", "Principal": { "Service": [ "ecs.aliyuncs.com" ] } } ], "Version": "1" }
Berikan izin kepada peran RAM untuk mengakses KMS.
Panggil operasi API AttachPolicyToRole RAM untuk menyambungkan System Policy AliyunKMSFullAccess ke peran RAM instans EcsRamRoleTest. Atur parameter berikut:
PolicyType: Atur ke System untuk menunjukkan System Policy.PolicyName: Atur ke AliyunKMSFullAccess.RoleName: Atur ke nama peran RAM, misalnya EcsRamRoleTest.
Langkah 2: Sambungkan peran RAM ke Instance ECS
Konsol ECS
Jika Anda belum membeli Instance ECS, beli terlebih dahulu. Untuk informasi lebih lanjut, lihat Buat instans pada tab peluncuran kustom.
Login ke Konsol ECS.
Pada panel navigasi di sebelah kiri, pilih Instances & Images> Instances.
Pada bilah navigasi atas, pilih wilayah dan kelompok sumber daya tempat Instance ECS Anda berada.
Temukan Instance ECS yang dituju, lalu pada kolom Actions, pilih
>Instance Settings>Attach/Detach RAM Role.Pada kotak dialog yang muncul, pilih peran RAM yang telah Anda buat dan klik OK.
API ECS
Sambungkan peran RAM instans ke Instance ECS yang sudah ada
Panggil operasi API AttachInstanceRamRole ECS untuk menyambungkan peran RAM instans ke Instance ECS yang sudah ada dalam VPC. Atur parameter berikut:
RegionId: ID wilayah tempat instans berada.RamRoleName: Nama peran RAM, misalnya EcsRamRoleTest.InstanceIds: ID Instance ECS, misalnya ["i-bXXXXXXXX"].
Tentukan peran RAM instans saat membuat Instance ECS
Buat instans.
Panggil operasi API CreateInstance ECS. Atur parameter berikut:
RegionId: ID wilayah tempat instans berada.ImageId: ID image untuk instans. Contoh: centos_7_03_64_40G_alibase_****.vhd.InstanceType: Tipe instans. Contoh: ecs.g6.large.VSwitchId: ID vSwitch dalam VPC tempat instans berada.CatatanPeran RAM instans hanya didukung untuk Instance ECS dalam VPC. Parameter ini wajib diisi.
RamRoleName: Nama peran RAM instans, misalnya EcsRamRoleTest.
Anda juga dapat memberi otorisasi kepada Pengguna RAM untuk menggunakan peran RAM instans. Untuk informasi lebih lanjut, lihat peran RAM instans.
Panggil operasi API ModifyInstanceVncPasswd dan StartInstance ECS untuk mengatur password instans dan menjalankannya.
Langkah 3: Akses KMS dengan peran RAM
Bagian ini memberikan contoh Java tentang cara memanggil operasi API KMS ListKeys untuk mencantumkan semua ID kunci di wilayah saat ini. Untuk panduan SDK yang lebih rinci, lihat referensi SDK.
Alibaba Cloud SDK V2.0
package com.aliyun.sample;
import com.aliyun.tea.*;
public class Sample {
public static com.aliyun.kms20160120.Client createClient() throws Exception {
com.aliyun.credentials.models.Config credentialConfig = new com.aliyun.credentials.models.Config();
// Set the credential type.
credentialConfig.type = "ecs_ram_role";
// Optional. To reduce API calls, specify the instance RAM role name. If this parameter is omitted, the role name is retrieved automatically.
credentialConfig.roleName = "<your-ecsRamRoleName>";
com.aliyun.credentials.Client credentialClient = new com.aliyun.credentials.Client(credentialConfig);
com.aliyun.teaopenapi.models.Config kmsClientConfig = new com.aliyun.teaopenapi.models.Config()
// Set the KMS endpoint. Example: kms.cn-hangzhou.aliyuncs.com
.setEndpoint( "kms.cn-hangzhou.aliyuncs.com").
setCredential(credentialClient);
return new com.aliyun.kms20160120.Client(kmsClientConfig);
}
public static void main(String[] args_) throws Exception {
java.util.List<String> args = java.util.Arrays.asList(args_);
com.aliyun.kms20160120.Client client = Sample.createClient();
com.aliyun.kms20160120.models.ListKeysRequest listKeysRequest = new com.aliyun.kms20160120.models.ListKeysRequest();
com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
try {
client.listKeysWithOptions(listKeysRequest, runtime);
} catch (TeaException error) {
System.out.println(error.getMessage());
com.aliyun.teautil.Common.assertAsString(error.message);
} catch (Exception _error) {
_error.printStackTrace();
}
}
}Tab body
Secrets Manager Client
Untuk informasi lebih lanjut, lihat Secrets Manager Client.
Konfigurasikan parameter berikut dalam file
secretsmanager.propertiesatau sebagai variabel lingkungan sistem.Parameter
Nilai
credentials_type
Atur ke
ecs_ram_role.credentials_role_session_name
Nama kustom untuk sesi peran, digunakan untuk audit.
cache_client_region_id
Formatnya adalah [{"regionId":"<your region id>"}]. Ganti
<your region id>dengan ID wilayah aktual Anda.Buat klien untuk mengambil nilai rahasia.
import com.aliyuncs.kms.secretsmanager.client.v2.SecretCacheClient; import com.aliyuncs.kms.secretsmanager.client.v2.SecretCacheClientBuilder; import com.aliyuncs.kms.secretsmanager.client.v2.exception.CacheSecretException; import com.aliyuncs.kms.secretsmanager.client.v2.model.SecretInfo; public class CacheClientEnvironmentSample { public static void main(String[] args) { try { SecretCacheClient client = SecretCacheClientBuilder.newClient(); SecretInfo secretInfo = client.getSecretInfo("#secretName#"); System.out.println(secretInfo); } catch (CacheSecretException e) { e.printStackTrace(); } } }
Secrets Manager JDBC Client
Bagian ini menggunakan contoh koneksi database MySQL melalui JDBC. Untuk informasi lebih lanjut, lihat Secrets Manager JDBC Client.
Dalam kode aplikasi proyek Anda, tambahkan file konfigurasi bernama
secretsmanager.properties.## Type of access credentials credentials_type=ecs_ram_role ## Name of the ECS RAM role credentials_role_name=#credentials_role_name# ## Region of the associated KMS instance cache_client_region_id=[{"regionId":"#regionId#"}] ## Custom refresh interval. Unit: milliseconds. Default: 6 hours. Minimum: 5 minutes. refresh_secret_ttl=21600000Hubungkan ke database MySQL melalui JDBC.
import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class SecretManagerJDBCSample { public static void main(String[] args) throws Exception { // Load the Alibaba Cloud Secrets Manager JDBC driver com.aliyun.kms.secretsmanager.MysqlSecretsManagerSimpleDriver Class.forName("com.aliyun.kms.secretsmanager.MysqlSecretsManagerSimpleDriver"); Connection connect = null; try { connect = DriverManager.getConnection("secrets-manager:mysql://<YOUR-MYSQL-IP>:<YOUR-MYSQL-PORT>/<YOUR-DATABASE-NAME>", "#your-mysql-secret-name#",""); } catch(SQLException e) { e.printStackTrace(); } } }
RAM secret plug-in
Untuk informasi lebih lanjut, lihat RAM secret plug-in.
Tambahkan file konfigurasi
managed_credentials_providers.propertieske kode waktu proses proyek Anda.credentials_type=ecs_ram_role ## Name of the ECS RAM role credentials_role_name=#credentials_role_name# ## Region of the associated KMS instance cache_client_region_id=[{"regionId":"#regionId#"}]Dapatkan klien Alibaba Cloud SDK for Java dan panggil layanan cloud.
Contoh berikut menunjukkan cara memanggil operasi DescribeInstanceStatus dari ECS:
CatatanSebelum menjalankan kode contoh, tambahkan dependensi
aliyun-java-sdk-ecske file pom.xml Anda.import com.aliyuncs.IAcsClient; import com.aliyuncs.ecs.model.v20140526.DescribeInstanceStatusRequest; import com.aliyuncs.ecs.model.v20140526.DescribeInstanceStatusResponse; import com.aliyun.kms.secretsmanager.plugin.sdkcore.ProxyAcsClient; import com.aliyuncs.exceptions.ClientException; import com.aliyuncs.exceptions.ServerException; public class AliyunSdkProviderSample { public static void main(String[]args) { String secretName="******"; /* If the application cannot read the default configuration file (managed_credentials_providers.properties) from the classpath or an executable JAR file, or if you need to use a custom configuration file name, you can call the following code to specify a custom configuration file. The file is read in the following order: 1. If "your-config-name" is an absolute path, the file is read from that path. 2. If "your-config-name" is only a file name, the file is read from the classpath first, and then from the executable JAR file. */ //ConfigLoader.setConfigName("your-config-name"); // 1. Obtain an IAcsClient by using aliyun-java-sdk-managed-credentials-provider. IAcsClient client = null; try { client = new ProxyAcsClient("<the regionId of ECS>", secretName); } catch (ClientException e) { e.printStackTrace(); } // 2. Call an ECS API operation to implement your business logic. DescribeInstanceStatusRequest request = new DescribeInstanceStatusRequest(); DescribeInstanceStatusResponse response; try { response = client.getAcsResponse(request); } catch (ServerException e) { e.printStackTrace(); } catch (ClientException e) { e.printStackTrace(); } // 3. Shut down the client to release resources used by the plug-in. client.shutdown(); } }
Alibaba Cloud SDK V1.0 (Tidak Direkomendasikan)
package com.aliyuncs.kms.examples;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.auth.AlibabaCloudCredentialsProvider;
import com.aliyuncs.auth.InstanceProfileCredentialsProvider;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.kms.model.v20160120.*;
import com.aliyuncs.profile.DefaultProfile;
public class RamRoleTest {
public static void main(final String[] args) throws Exception {
String regionId = "<region-id>";
DefaultProfile profile = DefaultProfile.getProfile(regionId);
// Set the RAM role. This topic uses EcsRamRoleTest as an example.
String roleName = "EcsRamRoleTest";
// Create the credentials provider for the instance RAM role.
AlibabaCloudCredentialsProvider provider = new InstanceProfileCredentialsProvider(roleName);
IAcsClient client = new DefaultAcsClient(profile, provider);
ListKeysRequest request = new ListKeysRequest();
try {
ListKeysResponse response = client.getAcsResponse(request);
System.out.println(new Gson().toJson(response));
} catch (ServerException e) {
e.printStackTrace();
} catch (ClientException e) {
System.out.println("ErrCode:" + e.getErrCode());
System.out.println("ErrMsg:" + e.getErrMsg());
System.out.println("RequestId:" + e.getRequestId());
}
}
}Referensi
Kelola kredensial akses (Alibaba Cloud SDK V1.0)
Kelola kredensial akses (Alibaba Cloud SDK V2.0)
Pelajari lebih lanjut tentang peran RAM: