Utilizzare CreateLaunchTemplate con un AWS SDK o CLI - Amazon Elastic Compute Cloud

Le traduzioni sono generate tramite traduzione automatica. In caso di conflitto tra il contenuto di una traduzione e la versione originale in Inglese, quest'ultima prevarrà.

Utilizzare CreateLaunchTemplate con un AWS SDK o CLI

I seguenti esempi di codice mostrano come utilizzareCreateLaunchTemplate.

Gli esempi di operazioni sono estratti di codice da programmi più grandi e devono essere eseguiti nel contesto. È possibile visualizzare questa operazione nel contesto nel seguente esempio di codice:

.NET
AWS SDK for .NET
Nota

C'è altro su. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS.

/// <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) { try { 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; } catch (AmazonEC2Exception ec2Exception) { if (ec2Exception.ErrorCode == "InvalidLaunchTemplateName.AlreadyExistsException") { _logger.LogError($"Could not create the template, the name {_launchTemplateName} already exists. " + $"Please try again with a unique name."); } throw; } catch (Exception ex) { _logger.LogError($"An error occurred while creating the template.: {ex.Message}"); throw; } }
CLI
AWS CLI

Esempio 1: per creare un modello di avvio

L'create-launch-templateesempio seguente crea un modello di avvio che specifica la sottorete in cui avviare l'istanza, assegna un indirizzo IP pubblico e un IPv6 indirizzo all'istanza e crea un tag per l'istanza.

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" } }

Per maggiori informazioni, consulta Avvio di istanze da un modello di avvio nella Guida per l'utente di Amazon Elastic Compute Cloud. Per informazioni sulla quotazione dei parametri JSON -formatted, vedete Quoting Strings nella Command Line Interface User Guide.AWS

Esempio 2: creare un modello di lancio per Amazon EC2 Auto Scaling

L'create-launch-templateesempio seguente crea un modello di lancio con più tag e una mappatura dei dispositivi a blocchi per specificare un EBS volume aggiuntivo all'avvio di un'istanza. Specificate un valore Groups corrispondente ai gruppi di sicurezza in VPC cui il gruppo Auto Scaling lancerà le istanze. Specificate le sottoreti VPC and come proprietà del gruppo 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" } }

Per ulteriori informazioni, consulta Creating a Launch Template for an Auto Scaling Group nella Amazon Auto EC2 Scaling User Guide. Per informazioni su come quotare i parametri JSON -formatted, consulta Quoting Strings nella Command Line Interface User Guide.AWS

Esempio 3: creare un modello di avvio che specifichi la crittografia dei volumi EBS

L'create-launch-templateesempio seguente crea un modello di avvio che include EBS volumi crittografati creati da un'istantanea non crittografata. Inoltre, vengono applicati i tag ai volumi durante la creazione. Se la crittografia predefinita è disabilitata, è necessario specificare l'opzione "Encrypted" come mostrato nel seguente esempio. Se si utilizza l'"KmsKeyId"opzione per specificare un servizio gestito dal clienteCMK, è necessario specificare l'"Encrypted"opzione anche se la crittografia è abilitata per impostazione predefinita.

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

Contenuto di 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" } }

Per ulteriori informazioni, consulta Restoring an Amazon EBS Volume from a Snapshot and Encryption by Default nella Amazon Elastic Compute Cloud User Guide.

JavaScript
SDKper JavaScript (v3)
Nota

C'è di più su. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS.

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
SDKper Python (Boto3)
Nota

C'è di più su. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS.

In questo esempio viene creato un modello di avvio che include un profilo dell'istanza che concede autorizzazioni specifiche all'istanza e uno script Bash per i dati utente che viene eseguito sull'istanza dopo l'avvio.

class AutoScalingWrapper: """ Encapsulates Amazon EC2 Auto Scaling and EC2 management actions. """ def __init__( self, resource_prefix: str, inst_type: str, ami_param: str, autoscaling_client: boto3.client, ec2_client: boto3.client, ssm_client: boto3.client, iam_client: boto3.client, ): """ Initializes the AutoScaler class with the necessary parameters. :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 sts_client = boto3.client("sts") self.account_id = sts_client.get_caller_identity()["Account"] self.key_pair_name = f"{resource_prefix}-key-pair" self.launch_template_name = f"{resource_prefix}-template-" self.group_name = f"{resource_prefix}-group" # Happy path self.instance_policy_name = f"{resource_prefix}-pol" self.instance_role_name = f"{resource_prefix}-role" self.instance_profile_name = f"{resource_prefix}-prof" # Failure mode 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" def create_template( self, server_startup_script_file: str, instance_policy_file: str ) -> Dict[str, Any]: """ 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: # Create key pair and instance profile 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, ) # Read the startup script with open(server_startup_script_file) as file: start_server_script = file.read() # Get the latest AMI ID ami_latest = self.ssm_client.get_parameter(Name=self.ami_param) ami_id = ami_latest["Parameter"]["Value"] # Create the launch template 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( f"Created launch template {self.launch_template_name} for AMI {ami_id} on {self.inst_type}." ) except ClientError as err: log.error(f"Failed to create launch template {self.launch_template_name}.") error_code = err.response["Error"]["Code"] if error_code == "InvalidLaunchTemplateName.AlreadyExistsException": log.info( f"Launch template {self.launch_template_name} already exists, nothing to do." ) log.error(f"Full error:\n\t{err}") return template

Per un elenco completo delle guide per gli AWS SDK sviluppatori e degli esempi di codice, consulta. Crea EC2 risorse Amazon utilizzando un AWS SDK Questo argomento include anche informazioni su come iniziare e dettagli sulle SDK versioni precedenti.