Gunakan CreateLaunchTemplate dengan AWS SDK atau CLI - Amazon Elastic Compute Cloud

Terjemahan disediakan oleh mesin penerjemah. Jika konten terjemahan yang diberikan bertentangan dengan versi bahasa Inggris aslinya, utamakan versi bahasa Inggris.

Gunakan CreateLaunchTemplate dengan AWS SDK atau CLI

Contoh kode berikut menunjukkan cara menggunakanCreateLaunchTemplate.

Contoh tindakan adalah kutipan kode dari program yang lebih besar dan harus dijalankan dalam konteks. Anda dapat melihat tindakan ini dalam konteks dalam contoh kode berikut:

.NET
AWS SDK for .NET
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara mengatur dan menjalankannya di AWS Repositori Contoh Kode.

/// <summary> /// Creates an Amazon EC2 launch template to use with Amazon EC2 Auto Scaling. /// The launch template specifies a Bash script in its user data field that runs after /// the instance is started. This script installs the Python packages and starts a Python /// web server on the instance. /// </summary> /// <param name="startupScriptPath">The path to a Bash script file that is run.</param> /// <param name="instancePolicyPath">The path to a permissions policy to create and attach to the profile.</param> /// <returns>The template object.</returns> public async Task<Amazon.EC2.Model.LaunchTemplate> CreateTemplate(string startupScriptPath, string instancePolicyPath) { await CreateKeyPair(_keyPairName); await CreateInstanceProfileWithName(_instancePolicyName, _instanceRoleName, _instanceProfileName, instancePolicyPath); var startServerText = await File.ReadAllTextAsync(startupScriptPath); var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(startServerText); var amiLatest = await _amazonSsm.GetParameterAsync( new GetParameterRequest() { Name = _amiParam }); var amiId = amiLatest.Parameter.Value; var launchTemplateResponse = await _amazonEc2.CreateLaunchTemplateAsync( new CreateLaunchTemplateRequest() { LaunchTemplateName = _launchTemplateName, LaunchTemplateData = new RequestLaunchTemplateData() { InstanceType = _instanceType, ImageId = amiId, IamInstanceProfile = new LaunchTemplateIamInstanceProfileSpecificationRequest() { Name = _instanceProfileName }, KeyName = _keyPairName, UserData = System.Convert.ToBase64String(plainTextBytes) } }); return launchTemplateResponse.LaunchTemplate; }
CLI
AWS CLI

Contoh 1: Untuk membuat templat peluncuran

Contoh create-launch-template berikut membuat templat peluncuran yang menentukan subnet untuk meluncurkan instans, menetapkan alamat IP publik dan alamat IPv6 ke instans, lalu membuat tanda untuk instans.

aws ec2 create-launch-template \ --launch-template-name TemplateForWebServer \ --version-description WebVersion1 \ --launch-template-data '{"NetworkInterfaces":[{"AssociatePublicIpAddress":true,"DeviceIndex":0,"Ipv6AddressCount":1,"SubnetId":"subnet-7b16de0c"}],"ImageId":"ami-8c1be5f6","InstanceType":"t2.small","TagSpecifications":[{"ResourceType":"instance","Tags":[{"Key":"purpose","Value":"webserver"}]}]}'

Output:

{ "LaunchTemplate": { "LatestVersionNumber": 1, "LaunchTemplateId": "lt-01238c059e3466abc", "LaunchTemplateName": "TemplateForWebServer", "DefaultVersionNumber": 1, "CreatedBy": "arn:aws:iam::123456789012:user/Bob", "CreateTime": "2019-01-27T09:13:24.000Z" } }

Untuk informasi selengkapnya, lihat Meluncurkan Instans dari Templat Peluncuran di Panduan Pengguna Amazon Elastic Compute Cloud. Untuk informasi tentang mengutip parameter berformat JSON, lihat Mengutip String di Panduan Pengguna Antarmuka Baris Perintah AWS .

Contoh 2: Guna membuat templat peluncuran untuk Amazon EC2 Auto Scaling

Contoh create-launch-template berikut membuat templat peluncuran dengan banyak tanda dan pemetaan perangkat blok untuk menentukan volume EBS tambahan saat instans diluncurkan. Tentukan nilai untuk Groups yang sesuai dengan grup keamanan untuk VPC yang akan menjadi tujuan peluncuran instans oleh grup Auto Scaling Anda. Tentukan VPC dan subnet sebagai properti grup Auto Scaling.

aws ec2 create-launch-template \ --launch-template-name TemplateForAutoScaling \ --version-description AutoScalingVersion1 \ --launch-template-data '{"NetworkInterfaces":[{"DeviceIndex":0,"AssociatePublicIpAddress":true,"Groups":["sg-7c227019,sg-903004f8"],"DeleteOnTermination":true}],"ImageId":"ami-b42209de","InstanceType":"m4.large","TagSpecifications":[{"ResourceType":"instance","Tags":[{"Key":"environment","Value":"production"},{"Key":"purpose","Value":"webserver"}]},{"ResourceType":"volume","Tags":[{"Key":"environment","Value":"production"},{"Key":"cost-center","Value":"cc123"}]}],"BlockDeviceMappings":[{"DeviceName":"/dev/sda1","Ebs":{"VolumeSize":100}}]}' --region us-east-1

Output:

{ "LaunchTemplate": { "LatestVersionNumber": 1, "LaunchTemplateId": "lt-0123c79c33a54e0abc", "LaunchTemplateName": "TemplateForAutoScaling", "DefaultVersionNumber": 1, "CreatedBy": "arn:aws:iam::123456789012:user/Bob", "CreateTime": "2019-04-30T18:16:06.000Z" } }

Untuk informasi selengkapnya, lihat Membuat Templat Peluncuran untuk Grup Auto Scaling di Panduan Pengguna Amazon EC2 Auto Scaling. Untuk informasi tentang mengutip parameter berformat JSON, lihat Mengutip String di Panduan Pengguna Antarmuka Baris Perintah AWS .

Contoh 3: Untuk membuat templat peluncuran yang menentukan enkripsi volume EBS

Contoh create-launch-template berikut membuat templat peluncuran yang menyertakan volume EBS terenkripsi yang dibuat dari snapshot yang tidak terenkripsi. Contoh tersebut juga menandai volume selama pembuatan. Jika enkripsi secara default dinonaktifkan, Anda harus menentukan opsi "Encrypted" seperti yang ditunjukkan pada contoh berikut. Jika menggunakan opsi "KmsKeyId" untuk menentukan CMK yang dikelola pelanggan, Anda juga harus menentukan opsi "Encrypted" bahkan jika enkripsi secara default diaktifkan.

aws ec2 create-launch-template \ --launch-template-name TemplateForEncryption \ --launch-template-data file://config.json

Isi dari config.json:

{ "BlockDeviceMappings":[ { "DeviceName":"/dev/sda1", "Ebs":{ "VolumeType":"gp2", "DeleteOnTermination":true, "SnapshotId":"snap-066877671789bd71b", "Encrypted":true, "KmsKeyId":"arn:aws:kms:us-east-1:012345678910:key/abcd1234-a123-456a-a12b-a123b4cd56ef" } } ], "ImageId":"ami-00068cd7555f543d5", "InstanceType":"c5.large", "TagSpecifications":[ { "ResourceType":"volume", "Tags":[ { "Key":"encrypted", "Value":"yes" } ] } ] }

Output:

{ "LaunchTemplate": { "LatestVersionNumber": 1, "LaunchTemplateId": "lt-0d5bd51bcf8530abc", "LaunchTemplateName": "TemplateForEncryption", "DefaultVersionNumber": 1, "CreatedBy": "arn:aws:iam::123456789012:user/Bob", "CreateTime": "2020-01-07T19:08:36.000Z" } }

Untuk informasi selengkapnya, lihat Memulihkan Volume Amazon EBS dari Snapshot dan Enkripsi secara Default di Panduan Pengguna Amazon Elastic Compute Cloud.

JavaScript
SDK untuk JavaScript (v3)
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara mengatur dan menjalankannya di AWS Repositori Contoh Kode.

const ssmClient = new SSMClient({}); const { Parameter } = await ssmClient.send( new GetParameterCommand({ Name: "/aws/service/ami-amazon-linux-latest/amzn2-ami-hvm-x86_64-gp2", }), ); const ec2Client = new EC2Client({}); await ec2Client.send( new CreateLaunchTemplateCommand({ LaunchTemplateName: NAMES.launchTemplateName, LaunchTemplateData: { InstanceType: "t3.micro", ImageId: Parameter.Value, IamInstanceProfile: { Name: NAMES.instanceProfileName }, UserData: readFileSync( join(RESOURCES_PATH, "server_startup_script.sh"), ).toString("base64"), KeyName: NAMES.keyPairName, }, }),
Python
SDK untuk Python (Boto3)
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode AWS.

Contoh ini membuat templat peluncuran yang menyertakan profil instans yang memberikan izin khusus ke instans, dan skrip Bash data pengguna yang berjalan pada instans tersebut setelah dimulai.

class AutoScaler: """ Encapsulates Amazon EC2 Auto Scaling and EC2 management actions. """ def __init__( self, resource_prefix, inst_type, ami_param, autoscaling_client, ec2_client, ssm_client, iam_client, ): """ :param resource_prefix: The prefix for naming AWS resources that are created by this class. :param inst_type: The type of EC2 instance to create, such as t3.micro. :param ami_param: The Systems Manager parameter used to look up the AMI that is created. :param autoscaling_client: A Boto3 EC2 Auto Scaling client. :param ec2_client: A Boto3 EC2 client. :param ssm_client: A Boto3 Systems Manager client. :param iam_client: A Boto3 IAM client. """ self.inst_type = inst_type self.ami_param = ami_param self.autoscaling_client = autoscaling_client self.ec2_client = ec2_client self.ssm_client = ssm_client self.iam_client = iam_client self.launch_template_name = f"{resource_prefix}-template" self.group_name = f"{resource_prefix}-group" self.instance_policy_name = f"{resource_prefix}-pol" self.instance_role_name = f"{resource_prefix}-role" self.instance_profile_name = f"{resource_prefix}-prof" self.bad_creds_policy_name = f"{resource_prefix}-bc-pol" self.bad_creds_role_name = f"{resource_prefix}-bc-role" self.bad_creds_profile_name = f"{resource_prefix}-bc-prof" self.key_pair_name = f"{resource_prefix}-key-pair" def create_template(self, server_startup_script_file, instance_policy_file): """ Creates an Amazon EC2 launch template to use with Amazon EC2 Auto Scaling. The launch template specifies a Bash script in its user data field that runs after the instance is started. This script installs Python packages and starts a Python web server on the instance. :param server_startup_script_file: The path to a Bash script file that is run when an instance starts. :param instance_policy_file: The path to a file that defines a permissions policy to create and attach to the instance profile. :return: Information about the newly created template. """ template = {} try: self.create_key_pair(self.key_pair_name) self.create_instance_profile( instance_policy_file, self.instance_policy_name, self.instance_role_name, self.instance_profile_name, ) with open(server_startup_script_file) as file: start_server_script = file.read() ami_latest = self.ssm_client.get_parameter(Name=self.ami_param) ami_id = ami_latest["Parameter"]["Value"] lt_response = self.ec2_client.create_launch_template( LaunchTemplateName=self.launch_template_name, LaunchTemplateData={ "InstanceType": self.inst_type, "ImageId": ami_id, "IamInstanceProfile": {"Name": self.instance_profile_name}, "UserData": base64.b64encode( start_server_script.encode(encoding="utf-8") ).decode(encoding="utf-8"), "KeyName": self.key_pair_name, }, ) template = lt_response["LaunchTemplate"] log.info( "Created launch template %s for AMI %s on %s.", self.launch_template_name, ami_id, self.inst_type, ) except ClientError as err: if ( err.response["Error"]["Code"] == "InvalidLaunchTemplateName.AlreadyExistsException" ): log.info( "Launch template %s already exists, nothing to do.", self.launch_template_name, ) else: raise AutoScalerError( f"Couldn't create launch template {self.launch_template_name}: {err}." ) return template

Untuk daftar lengkap panduan pengembang AWS SDK dan contoh kode, lihatMembuat sumber daya Amazon EC2 menggunakan SDK AWS. Topik ini juga mencakup informasi tentang memulai dan detail tentang versi SDK sebelumnya.