an AWS SDK 또는 CLICreateDBInstance와 함께 사용 - AWS SDK 코드 예제

AWS Doc SDK ExamplesWord AWS SDK 리포지토리에는 더 많은 GitHub 예제가 있습니다.

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

an AWS SDK 또는 CLICreateDBInstance와 함께 사용

다음 코드 예제는 CreateDBInstance의 사용 방법을 보여 줍니다.

작업 예제는 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 다음 코드 예제에서는 컨텍스트 내에서 이 작업을 확인할 수 있습니다.

.NET
AWS SDK for .NET
참고

더 많은 on GitHub가 있습니다. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

/// <summary> /// Create an RDS DB instance with a particular set of properties. Use the action DescribeDBInstancesAsync /// to determine when the DB instance is ready to use. /// </summary> /// <param name="dbName">Name for the DB instance.</param> /// <param name="dbInstanceIdentifier">DB instance identifier.</param> /// <param name="parameterGroupName">DB parameter group to associate with the instance.</param> /// <param name="dbEngine">The engine for the DB instance.</param> /// <param name="dbEngineVersion">Version for the DB instance.</param> /// <param name="instanceClass">Class for the DB instance.</param> /// <param name="allocatedStorage">The amount of storage in gibibytes (GiB) to allocate to the DB instance.</param> /// <param name="adminName">Admin user name.</param> /// <param name="adminPassword">Admin user password.</param> /// <returns>DB instance object.</returns> public async Task<DBInstance> CreateDBInstance(string dbName, string dbInstanceIdentifier, string parameterGroupName, string dbEngine, string dbEngineVersion, string instanceClass, int allocatedStorage, string adminName, string adminPassword) { var response = await _amazonRDS.CreateDBInstanceAsync( new CreateDBInstanceRequest() { DBName = dbName, DBInstanceIdentifier = dbInstanceIdentifier, DBParameterGroupName = parameterGroupName, Engine = dbEngine, EngineVersion = dbEngineVersion, DBInstanceClass = instanceClass, AllocatedStorage = allocatedStorage, MasterUsername = adminName, MasterUserPassword = adminPassword }); return response.DBInstance; }
  • API 세부 정보는 AWS SDK for .NET API 참조CreateDBInstance를 참조하세요.

C++
C++ SDK
참고

더 많은 on GitHub가 있습니다. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

Aws::Client::ClientConfiguration clientConfig; // Optional: Set to the AWS Region (overrides config file). // clientConfig.region = "us-east-1"; Aws::RDS::RDSClient client(clientConfig); Aws::RDS::Model::CreateDBInstanceRequest request; request.SetDBName(DB_NAME); request.SetDBInstanceIdentifier(DB_INSTANCE_IDENTIFIER); request.SetDBParameterGroupName(PARAMETER_GROUP_NAME); request.SetEngine(engineVersion.GetEngine()); request.SetEngineVersion(engineVersion.GetEngineVersion()); request.SetDBInstanceClass(dbInstanceClass); request.SetStorageType(DB_STORAGE_TYPE); request.SetAllocatedStorage(DB_ALLOCATED_STORAGE); request.SetMasterUsername(administratorName); request.SetMasterUserPassword(administratorPassword); Aws::RDS::Model::CreateDBInstanceOutcome outcome = client.CreateDBInstance(request); if (outcome.IsSuccess()) { std::cout << "The DB instance creation has started." << std::endl; } else { std::cerr << "Error with RDS::CreateDBInstance. " << outcome.GetError().GetMessage() << std::endl; cleanUpResources(PARAMETER_GROUP_NAME, "", client); return false; }
  • API 세부 정보는 AWS SDK for C++ API 참조CreateDBInstance를 참조하세요.

CLI
AWS CLI

DB 인스턴스를 생성하려면

다음 create-db-instance 예제에서는 필수 옵션을 사용하여 새 DB 인스턴스를 시작합니다.

aws rds create-db-instance \ --db-instance-identifier test-mysql-instance \ --db-instance-class db.t3.micro \ --engine mysql \ --master-username admin \ --master-user-password secret99 \ --allocated-storage 20

출력:

{ "DBInstance": { "DBInstanceIdentifier": "test-mysql-instance", "DBInstanceClass": "db.t3.micro", "Engine": "mysql", "DBInstanceStatus": "creating", "MasterUsername": "admin", "AllocatedStorage": 20, "PreferredBackupWindow": "12:55-13:25", "BackupRetentionPeriod": 1, "DBSecurityGroups": [], "VpcSecurityGroups": [ { "VpcSecurityGroupId": "sg-12345abc", "Status": "active" } ], "DBParameterGroups": [ { "DBParameterGroupName": "default.mysql5.7", "ParameterApplyStatus": "in-sync" } ], "DBSubnetGroup": { "DBSubnetGroupName": "default", "DBSubnetGroupDescription": "default", "VpcId": "vpc-2ff2ff2f", "SubnetGroupStatus": "Complete", "Subnets": [ { "SubnetIdentifier": "subnet-########", "SubnetAvailabilityZone": { "Name": "us-west-2c" }, "SubnetStatus": "Active" }, { "SubnetIdentifier": "subnet-########", "SubnetAvailabilityZone": { "Name": "us-west-2d" }, "SubnetStatus": "Active" }, { "SubnetIdentifier": "subnet-########", "SubnetAvailabilityZone": { "Name": "us-west-2a" }, "SubnetStatus": "Active" }, { "SubnetIdentifier": "subnet-########", "SubnetAvailabilityZone": { "Name": "us-west-2b" }, "SubnetStatus": "Active" } ] }, "PreferredMaintenanceWindow": "sun:08:07-sun:08:37", "PendingModifiedValues": { "MasterUserPassword": "****" }, "MultiAZ": false, "EngineVersion": "5.7.22", "AutoMinorVersionUpgrade": true, "ReadReplicaDBInstanceIdentifiers": [], "LicenseModel": "general-public-license", "OptionGroupMemberships": [ { "OptionGroupName": "default:mysql-5-7", "Status": "in-sync" } ], "PubliclyAccessible": true, "StorageType": "gp2", "DbInstancePort": 0, "StorageEncrypted": false, "DbiResourceId": "db-5555EXAMPLE44444444EXAMPLE", "CACertificateIdentifier": "rds-ca-2019", "DomainMemberships": [], "CopyTagsToSnapshot": false, "MonitoringInterval": 0, "DBInstanceArn": "arn:aws:rds:us-west-2:123456789012:db:test-mysql-instance", "IAMDatabaseAuthenticationEnabled": false, "PerformanceInsightsEnabled": false, "DeletionProtection": false, "AssociatedRoles": [] } }

자세한 내용은 Amazon RDS 사용 설명서의 Amazon Word DB 인스턴스 생성을 참조하세요. RDS

  • API 세부 정보는 AWS CLI 명령 참조CreateDBInstance를 참조하세요.

Go
SDK for Go V2
참고

더 많은 on GitHub가 있습니다. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

import ( "context" "errors" "log" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/rds" "github.com/aws/aws-sdk-go-v2/service/rds/types" ) type DbInstances struct { RdsClient *rds.Client } // CreateInstance creates a DB instance. func (instances *DbInstances) CreateInstance(ctx context.Context, instanceName string, dbName string, dbEngine string, dbEngineVersion string, parameterGroupName string, dbInstanceClass string, storageType string, allocatedStorage int32, adminName string, adminPassword string) ( *types.DBInstance, error) { output, err := instances.RdsClient.CreateDBInstance(ctx, &rds.CreateDBInstanceInput{ DBInstanceIdentifier: aws.String(instanceName), DBName: aws.String(dbName), DBParameterGroupName: aws.String(parameterGroupName), Engine: aws.String(dbEngine), EngineVersion: aws.String(dbEngineVersion), DBInstanceClass: aws.String(dbInstanceClass), StorageType: aws.String(storageType), AllocatedStorage: aws.Int32(allocatedStorage), MasterUsername: aws.String(adminName), MasterUserPassword: aws.String(adminPassword), }) if err != nil { log.Printf("Couldn't create instance %v: %v\n", instanceName, err) return nil, err } else { return output.DBInstance, nil } }
  • API 세부 정보는 AWS SDK for Go API 참조CreateDBInstance를 참조하세요.

Java
Java 2.x용 SDK
참고

더 많은 on GitHub가 있습니다. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

import com.google.gson.Gson; import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.rds.RdsClient; import software.amazon.awssdk.services.rds.model.DescribeDbInstancesRequest; import software.amazon.awssdk.services.rds.model.CreateDbInstanceRequest; import software.amazon.awssdk.services.rds.model.CreateDbInstanceResponse; import software.amazon.awssdk.services.rds.model.RdsException; import software.amazon.awssdk.services.rds.model.DescribeDbInstancesResponse; import software.amazon.awssdk.services.rds.model.DBInstance; import software.amazon.awssdk.services.secretsmanager.SecretsManagerClient; import software.amazon.awssdk.services.secretsmanager.model.GetSecretValueRequest; import software.amazon.awssdk.services.secretsmanager.model.GetSecretValueResponse; 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 * * This example requires an AWS Secrets Manager secret that contains the * database credentials. If you do not create a * secret, this example will not work. For more details, see: * * https://docs.aws.amazon.com/secretsmanager/latest/userguide/integrating_how-services-use-secrets_RS.html * * */ public class CreateDBInstance { public static long sleepTime = 20; public static void main(String[] args) { final String usage = """ Usage: <dbInstanceIdentifier> <dbName> <secretName> Where: dbInstanceIdentifier - The database instance identifier.\s dbName - The database name.\s secretName - The name of the AWS Secrets Manager secret that contains the database credentials." """; if (args.length != 3) { System.out.println(usage); System.exit(1); } String dbInstanceIdentifier = args[0]; String dbName = args[1]; String secretName = args[2]; Gson gson = new Gson(); User user = gson.fromJson(String.valueOf(getSecretValues(secretName)), User.class); Region region = Region.US_WEST_2; RdsClient rdsClient = RdsClient.builder() .region(region) .build(); createDatabaseInstance(rdsClient, dbInstanceIdentifier, dbName, user.getUsername(), user.getPassword()); waitForInstanceReady(rdsClient, dbInstanceIdentifier); rdsClient.close(); } private static SecretsManagerClient getSecretClient() { Region region = Region.US_WEST_2; return SecretsManagerClient.builder() .region(region) .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); } private static String getSecretValues(String secretName) { SecretsManagerClient secretClient = getSecretClient(); GetSecretValueRequest valueRequest = GetSecretValueRequest.builder() .secretId(secretName) .build(); GetSecretValueResponse valueResponse = secretClient.getSecretValue(valueRequest); return valueResponse.secretString(); } public static void createDatabaseInstance(RdsClient rdsClient, String dbInstanceIdentifier, String dbName, String userName, String userPassword) { try { CreateDbInstanceRequest instanceRequest = CreateDbInstanceRequest.builder() .dbInstanceIdentifier(dbInstanceIdentifier) .allocatedStorage(100) .dbName(dbName) .engine("mysql") .dbInstanceClass("db.m4.large") .engineVersion("8.0") .storageType("standard") .masterUsername(userName) .masterUserPassword(userPassword) .build(); CreateDbInstanceResponse response = rdsClient.createDBInstance(instanceRequest); System.out.print("The status is " + response.dbInstance().dbInstanceStatus()); } catch (RdsException e) { System.out.println(e.getLocalizedMessage()); System.exit(1); } } // Waits until the database instance is available. public static void waitForInstanceReady(RdsClient rdsClient, String dbInstanceIdentifier) { boolean instanceReady = false; String instanceReadyStr; System.out.println("Waiting for instance to become available."); try { DescribeDbInstancesRequest instanceRequest = DescribeDbInstancesRequest.builder() .dbInstanceIdentifier(dbInstanceIdentifier) .build(); // Loop until the cluster is ready. while (!instanceReady) { DescribeDbInstancesResponse response = rdsClient.describeDBInstances(instanceRequest); List<DBInstance> instanceList = response.dbInstances(); for (DBInstance instance : instanceList) { instanceReadyStr = instance.dbInstanceStatus(); if (instanceReadyStr.contains("available")) instanceReady = true; else { System.out.print("."); Thread.sleep(sleepTime * 1000); } } } System.out.println("Database instance is available!"); } catch (RdsException | InterruptedException e) { System.err.println(e.getMessage()); System.exit(1); } }
  • API 세부 정보는 AWS SDK for Java 2.x API 참조CreateDBInstance를 참조하세요.

Kotlin
Kotlin용 SDK
참고

더 많은 on GitHub가 있습니다. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

suspend fun createDatabaseInstance( dbInstanceIdentifierVal: String?, dbNamedbVal: String?, masterUsernameVal: String?, masterUserPasswordVal: String?, ) { val instanceRequest = CreateDbInstanceRequest { dbInstanceIdentifier = dbInstanceIdentifierVal allocatedStorage = 100 dbName = dbNamedbVal engine = "mysql" dbInstanceClass = "db.m4.large" engineVersion = "8.0" storageType = "standard" masterUsername = masterUsernameVal masterUserPassword = masterUserPasswordVal } RdsClient { region = "us-west-2" }.use { rdsClient -> val response = rdsClient.createDbInstance(instanceRequest) print("The status is ${response.dbInstance?.dbInstanceStatus}") } } // Waits until the database instance is available. suspend fun waitForInstanceReady(dbInstanceIdentifierVal: String?) { val sleepTime: Long = 20 var instanceReady = false var instanceReadyStr: String println("Waiting for instance to become available.") val instanceRequest = DescribeDbInstancesRequest { dbInstanceIdentifier = dbInstanceIdentifierVal } RdsClient { region = "us-west-2" }.use { rdsClient -> while (!instanceReady) { val response = rdsClient.describeDbInstances(instanceRequest) val instanceList = response.dbInstances if (instanceList != null) { for (instance in instanceList) { instanceReadyStr = instance.dbInstanceStatus.toString() if (instanceReadyStr.contains("available")) { instanceReady = true } else { println("...$instanceReadyStr") delay(sleepTime * 1000) } } } } println("Database instance is available!") } }
  • API 세부 정보는 AWS SDK for Kotlin API 참조CreateDBInstance를 참조하세요.

PHP
PHP용 SDK
참고

더 많은 on GitHub가 있습니다. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

require __DIR__ . '/vendor/autoload.php'; use Aws\Exception\AwsException; $rdsClient = new Aws\Rds\RdsClient([ 'region' => 'us-east-2' ]); $dbIdentifier = '<<{{db-identifier}}>>'; $dbClass = 'db.t2.micro'; $storage = 5; $engine = 'MySQL'; $username = 'MyUser'; $password = 'MyPassword'; try { $result = $rdsClient->createDBInstance([ 'DBInstanceIdentifier' => $dbIdentifier, 'DBInstanceClass' => $dbClass, 'AllocatedStorage' => $storage, 'Engine' => $engine, 'MasterUsername' => $username, 'MasterUserPassword' => $password, ]); var_dump($result); } catch (AwsException $e) { echo $e->getMessage(); echo "\n"; }
  • API 세부 정보는 AWS SDK for PHP API 참조CreateDBInstance를 참조하세요.

Python
Python용 SDK(Boto3)
참고

더 많은 on GitHub가 있습니다. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

class InstanceWrapper: """Encapsulates Amazon RDS DB instance actions.""" def __init__(self, rds_client): """ :param rds_client: A Boto3 Amazon RDS client. """ self.rds_client = rds_client @classmethod def from_client(cls): """ Instantiates this class from a Boto3 client. """ rds_client = boto3.client("rds") return cls(rds_client) def create_db_instance( self, db_name, instance_id, parameter_group_name, db_engine, db_engine_version, instance_class, storage_type, allocated_storage, admin_name, admin_password, ): """ Creates a DB instance. :param db_name: The name of the database that is created in the DB instance. :param instance_id: The ID to give the newly created DB instance. :param parameter_group_name: A parameter group to associate with the DB instance. :param db_engine: The database engine of a database to create in the DB instance. :param db_engine_version: The engine version for the created database. :param instance_class: The DB instance class for the newly created DB instance. :param storage_type: The storage type of the DB instance. :param allocated_storage: The amount of storage allocated on the DB instance, in GiBs. :param admin_name: The name of the admin user for the created database. :param admin_password: The admin password for the created database. :return: Data about the newly created DB instance. """ try: response = self.rds_client.create_db_instance( DBName=db_name, DBInstanceIdentifier=instance_id, DBParameterGroupName=parameter_group_name, Engine=db_engine, EngineVersion=db_engine_version, DBInstanceClass=instance_class, StorageType=storage_type, AllocatedStorage=allocated_storage, MasterUsername=admin_name, MasterUserPassword=admin_password, ) db_inst = response["DBInstance"] except ClientError as err: logger.error( "Couldn't create DB instance %s. Here's why: %s: %s", instance_id, err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise else: return db_inst
  • API 세부 정보는 AWS SDK for Python(Boto3) API 참조CreateDBInstance를 참조하세요.