Best Python code snippet using localstack_python
test_launch_templates.py
Source:test_launch_templates.py
...38 str(ex.value).should.equal(39 "An error occurred (InvalidLaunchTemplateName.AlreadyExistsException) when calling the CreateLaunchTemplate operation: Launch template name already in use."40 )41@mock_ec242def test_describe_launch_template_versions():43 template_data = {44 "ImageId": "ami-abc123",45 "DisableApiTermination": False,46 "TagSpecifications": [47 {"ResourceType": "instance", "Tags": [{"Key": "test", "Value": "value"}]}48 ],49 "SecurityGroupIds": ["sg-1234", "sg-ab5678"],50 }51 cli = boto3.client("ec2", region_name="us-east-1")52 create_resp = cli.create_launch_template(53 LaunchTemplateName="test-template", LaunchTemplateData=template_data54 )55 # test using name56 resp = cli.describe_launch_template_versions(57 LaunchTemplateName="test-template", Versions=["1"]58 )59 templ = resp["LaunchTemplateVersions"][0]["LaunchTemplateData"]60 templ.should.equal(template_data)61 # test using id62 resp = cli.describe_launch_template_versions(63 LaunchTemplateId=create_resp["LaunchTemplate"]["LaunchTemplateId"],64 Versions=["1"],65 )66 templ = resp["LaunchTemplateVersions"][0]["LaunchTemplateData"]67 templ.should.equal(template_data)68@mock_ec269def test_create_launch_template_version():70 cli = boto3.client("ec2", region_name="us-east-1")71 create_resp = cli.create_launch_template(72 LaunchTemplateName="test-template", LaunchTemplateData={"ImageId": "ami-abc123"}73 )74 version_resp = cli.create_launch_template_version(75 LaunchTemplateName="test-template",76 LaunchTemplateData={"ImageId": "ami-def456"},77 VersionDescription="new ami",78 )79 version_resp.should.have.key("LaunchTemplateVersion")80 version = version_resp["LaunchTemplateVersion"]81 version["DefaultVersion"].should.equal(False)82 version["LaunchTemplateId"].should.equal(83 create_resp["LaunchTemplate"]["LaunchTemplateId"]84 )85 version["VersionDescription"].should.equal("new ami")86 version["VersionNumber"].should.equal(2)87@mock_ec288def test_create_launch_template_version_by_id():89 cli = boto3.client("ec2", region_name="us-east-1")90 create_resp = cli.create_launch_template(91 LaunchTemplateName="test-template", LaunchTemplateData={"ImageId": "ami-abc123"}92 )93 version_resp = cli.create_launch_template_version(94 LaunchTemplateId=create_resp["LaunchTemplate"]["LaunchTemplateId"],95 LaunchTemplateData={"ImageId": "ami-def456"},96 VersionDescription="new ami",97 )98 version_resp.should.have.key("LaunchTemplateVersion")99 version = version_resp["LaunchTemplateVersion"]100 version["DefaultVersion"].should.equal(False)101 version["LaunchTemplateId"].should.equal(102 create_resp["LaunchTemplate"]["LaunchTemplateId"]103 )104 version["VersionDescription"].should.equal("new ami")105 version["VersionNumber"].should.equal(2)106@mock_ec2107def test_describe_launch_template_versions_with_multiple_versions():108 cli = boto3.client("ec2", region_name="us-east-1")109 cli.create_launch_template(110 LaunchTemplateName="test-template", LaunchTemplateData={"ImageId": "ami-abc123"}111 )112 cli.create_launch_template_version(113 LaunchTemplateName="test-template",114 LaunchTemplateData={"ImageId": "ami-def456"},115 VersionDescription="new ami",116 )117 resp = cli.describe_launch_template_versions(LaunchTemplateName="test-template")118 resp["LaunchTemplateVersions"].should.have.length_of(2)119 resp["LaunchTemplateVersions"][0]["LaunchTemplateData"]["ImageId"].should.equal(120 "ami-abc123"121 )122 resp["LaunchTemplateVersions"][1]["LaunchTemplateData"]["ImageId"].should.equal(123 "ami-def456"124 )125@mock_ec2126def test_describe_launch_template_versions_with_versions_option():127 cli = boto3.client("ec2", region_name="us-east-1")128 cli.create_launch_template(129 LaunchTemplateName="test-template", LaunchTemplateData={"ImageId": "ami-abc123"}130 )131 cli.create_launch_template_version(132 LaunchTemplateName="test-template",133 LaunchTemplateData={"ImageId": "ami-def456"},134 VersionDescription="new ami",135 )136 cli.create_launch_template_version(137 LaunchTemplateName="test-template",138 LaunchTemplateData={"ImageId": "ami-hij789"},139 VersionDescription="new ami, again",140 )141 resp = cli.describe_launch_template_versions(142 LaunchTemplateName="test-template", Versions=["2", "3"]143 )144 resp["LaunchTemplateVersions"].should.have.length_of(2)145 resp["LaunchTemplateVersions"][0]["LaunchTemplateData"]["ImageId"].should.equal(146 "ami-def456"147 )148 resp["LaunchTemplateVersions"][1]["LaunchTemplateData"]["ImageId"].should.equal(149 "ami-hij789"150 )151@mock_ec2152def test_describe_launch_template_versions_with_min():153 cli = boto3.client("ec2", region_name="us-east-1")154 cli.create_launch_template(155 LaunchTemplateName="test-template", LaunchTemplateData={"ImageId": "ami-abc123"}156 )157 cli.create_launch_template_version(158 LaunchTemplateName="test-template",159 LaunchTemplateData={"ImageId": "ami-def456"},160 VersionDescription="new ami",161 )162 cli.create_launch_template_version(163 LaunchTemplateName="test-template",164 LaunchTemplateData={"ImageId": "ami-hij789"},165 VersionDescription="new ami, again",166 )167 resp = cli.describe_launch_template_versions(168 LaunchTemplateName="test-template", MinVersion="2"169 )170 resp["LaunchTemplateVersions"].should.have.length_of(2)171 resp["LaunchTemplateVersions"][0]["LaunchTemplateData"]["ImageId"].should.equal(172 "ami-def456"173 )174 resp["LaunchTemplateVersions"][1]["LaunchTemplateData"]["ImageId"].should.equal(175 "ami-hij789"176 )177@mock_ec2178def test_describe_launch_template_versions_with_max():179 cli = boto3.client("ec2", region_name="us-east-1")180 cli.create_launch_template(181 LaunchTemplateName="test-template", LaunchTemplateData={"ImageId": "ami-abc123"}182 )183 cli.create_launch_template_version(184 LaunchTemplateName="test-template",185 LaunchTemplateData={"ImageId": "ami-def456"},186 VersionDescription="new ami",187 )188 cli.create_launch_template_version(189 LaunchTemplateName="test-template",190 LaunchTemplateData={"ImageId": "ami-hij789"},191 VersionDescription="new ami, again",192 )193 resp = cli.describe_launch_template_versions(194 LaunchTemplateName="test-template", MaxVersion="2"195 )196 resp["LaunchTemplateVersions"].should.have.length_of(2)197 resp["LaunchTemplateVersions"][0]["LaunchTemplateData"]["ImageId"].should.equal(198 "ami-abc123"199 )200 resp["LaunchTemplateVersions"][1]["LaunchTemplateData"]["ImageId"].should.equal(201 "ami-def456"202 )203@mock_ec2204def test_describe_launch_template_versions_with_min_and_max():205 cli = boto3.client("ec2", region_name="us-east-1")206 cli.create_launch_template(207 LaunchTemplateName="test-template", LaunchTemplateData={"ImageId": "ami-abc123"}208 )209 cli.create_launch_template_version(210 LaunchTemplateName="test-template",211 LaunchTemplateData={"ImageId": "ami-def456"},212 VersionDescription="new ami",213 )214 cli.create_launch_template_version(215 LaunchTemplateName="test-template",216 LaunchTemplateData={"ImageId": "ami-hij789"},217 VersionDescription="new ami, again",218 )219 cli.create_launch_template_version(220 LaunchTemplateName="test-template",221 LaunchTemplateData={"ImageId": "ami-345abc"},222 VersionDescription="new ami, because why not",223 )224 resp = cli.describe_launch_template_versions(225 LaunchTemplateName="test-template", MinVersion="2", MaxVersion="3"226 )227 resp["LaunchTemplateVersions"].should.have.length_of(2)228 resp["LaunchTemplateVersions"][0]["LaunchTemplateData"]["ImageId"].should.equal(229 "ami-def456"230 )231 resp["LaunchTemplateVersions"][1]["LaunchTemplateData"]["ImageId"].should.equal(232 "ami-hij789"233 )234@mock_ec2235def test_describe_launch_templates():236 cli = boto3.client("ec2", region_name="us-east-1")237 lt_ids = []238 r = cli.create_launch_template(239 LaunchTemplateName="test-template", LaunchTemplateData={"ImageId": "ami-abc123"}240 )241 lt_ids.append(r["LaunchTemplate"]["LaunchTemplateId"])242 r = cli.create_launch_template(243 LaunchTemplateName="test-template2",244 LaunchTemplateData={"ImageId": "ami-abc123"},245 )246 lt_ids.append(r["LaunchTemplate"]["LaunchTemplateId"])247 # general call, all templates248 resp = cli.describe_launch_templates()249 resp.should.have.key("LaunchTemplates")250 resp["LaunchTemplates"].should.have.length_of(2)251 resp["LaunchTemplates"][0]["LaunchTemplateName"].should.equal("test-template")252 resp["LaunchTemplates"][1]["LaunchTemplateName"].should.equal("test-template2")253 # filter by names254 resp = cli.describe_launch_templates(255 LaunchTemplateNames=["test-template2", "test-template"]256 )257 resp.should.have.key("LaunchTemplates")258 resp["LaunchTemplates"].should.have.length_of(2)259 resp["LaunchTemplates"][0]["LaunchTemplateName"].should.equal("test-template2")260 resp["LaunchTemplates"][1]["LaunchTemplateName"].should.equal("test-template")261 # filter by ids262 resp = cli.describe_launch_templates(LaunchTemplateIds=lt_ids)263 resp.should.have.key("LaunchTemplates")264 resp["LaunchTemplates"].should.have.length_of(2)265 resp["LaunchTemplates"][0]["LaunchTemplateName"].should.equal("test-template")266 resp["LaunchTemplates"][1]["LaunchTemplateName"].should.equal("test-template2")267@mock_ec2268def test_describe_launch_templates_with_filters():269 cli = boto3.client("ec2", region_name="us-east-1")270 r = cli.create_launch_template(271 LaunchTemplateName="test-template", LaunchTemplateData={"ImageId": "ami-abc123"}272 )273 cli.create_tags(274 Resources=[r["LaunchTemplate"]["LaunchTemplateId"]],275 Tags=[276 {"Key": "tag1", "Value": "a value"},277 {"Key": "another-key", "Value": "this value"},278 ],279 )280 cli.create_launch_template(281 LaunchTemplateName="no-tags", LaunchTemplateData={"ImageId": "ami-abc123"}282 )283 resp = cli.describe_launch_templates(284 Filters=[{"Name": "tag:tag1", "Values": ["a value"]}]285 )286 resp["LaunchTemplates"].should.have.length_of(1)287 resp["LaunchTemplates"][0]["LaunchTemplateName"].should.equal("test-template")288 resp = cli.describe_launch_templates(289 Filters=[{"Name": "launch-template-name", "Values": ["no-tags"]}]290 )291 resp["LaunchTemplates"].should.have.length_of(1)292 resp["LaunchTemplates"][0]["LaunchTemplateName"].should.equal("no-tags")293@mock_ec2294def test_create_launch_template_with_tag_spec():295 cli = boto3.client("ec2", region_name="us-east-1")296 cli.create_launch_template(297 LaunchTemplateName="test-template",298 LaunchTemplateData={"ImageId": "ami-abc123"},299 TagSpecifications=[300 {"ResourceType": "instance", "Tags": [{"Key": "key", "Value": "value"}]}301 ],302 )303 resp = cli.describe_launch_template_versions(304 LaunchTemplateName="test-template", Versions=["1"]305 )306 version = resp["LaunchTemplateVersions"][0]307 version["LaunchTemplateData"].should.have.key("TagSpecifications")308 version["LaunchTemplateData"]["TagSpecifications"].should.have.length_of(1)309 version["LaunchTemplateData"]["TagSpecifications"][0].should.equal(310 {"ResourceType": "instance", "Tags": [{"Key": "key", "Value": "value"}]}...
ec2_connector.py
Source:ec2_connector.py
...85 _LOGGER.debug(f'[EC2Connector] terminate_instances response : {response}')86 return response['TerminatingInstances'][0]87 except Exception as e:88 _LOGGER.error(f'[EC2Connector] terminate_instances error: {e}')89 def describe_launch_template_versions(self, lt_id, ver):90 try:91 response = self.ec2_client.describe_launch_template_versions(LaunchTemplateId=lt_id, Versions=[ver])92 _LOGGER.debug(f'[EC2Connector] describe_launch_template_versions response : {response}')93 return response['LaunchTemplateVersions'][0]94 except Exception as e:95 _LOGGER.error(f'[EC2Connector] describe_launch_template_versions error: {e}')96 def describe_spot_price_history(self, instance_types, az):97 try:98 curTime = datetime.datetime.now()99 response = self.ec2_client.describe_spot_price_history(InstanceTypes=instance_types, AvailabilityZone=az, ProductDescriptions=['Linux/UNIX'], StartTime=curTime, EndTime=curTime)100 _LOGGER.debug(f'[EC2Connector] describe_spot_price_history response : {response}')101 return response['SpotPriceHistory']102 except Exception as e:103 _LOGGER.error(f'[EC2Connector] describe_spot_price_history error: {e}')104 def describe_instances(self, instance_id):105 try:...
launch_template.py
Source:launch_template.py
1import argparse2from ami import *3from session import *4def describe_launch_template_versions(template_name, profile):5 client = start_session(profile, 'ec2')6 try:7 response = client.describe_launch_template_versions(8 LaunchTemplateName=template_name,9 )10 except botocore.exceptions.ClientError:11 return None12 else:13 return response['LaunchTemplateVersions']14def create_launch_template_from_latest_ami(ami_name, template_name, profile):15 launch_template_versions = describe_launch_template_versions(template_name, profile)16 images = describe_sorted_images(ami_name, profile)17 latest_image = images[0]['ImageId']18 if latest_image != launch_template_versions[0]['LaunchTemplateData']['ImageId']:19 client = start_session(profile, 'ec2')20 response = client.create_launch_template_version(21 LaunchTemplateData={22 'ImageId': latest_image,23 },24 LaunchTemplateId=launch_template_versions[0]['LaunchTemplateId'],25 SourceVersion=str(launch_template_versions[0]['VersionNumber']),26 )27 return response28 else:29 return None30def change_default_version(template_name, profile):31 client = start_session(profile, 'ec2')32 try:33 describe_response = client.describe_launch_templates(34 LaunchTemplateNames=[template_name],35 )36 except botocore.exceptions.ClientError:37 raise Exception('ä¾å¤ãçºçãã¾ãã')38 else:39 if describe_response['LaunchTemplates'][0]['DefaultVersionNumber'] != describe_response['LaunchTemplates'][0]['LatestVersionNumber']:40 modify_response = client.modify_launch_template(41 LaunchTemplateId=describe_response['LaunchTemplates'][0]['LaunchTemplateId'],42 DefaultVersion=str(describe_response['LaunchTemplates'][0]['LatestVersionNumber']),43 )44 return modify_response['LaunchTemplate']45 else:46 return None47def update_launch_template(args):48 create_response = create_launch_template_from_latest_ami(args.ami_name, args.template_name, args.profile)49 change_default_version_response = change_default_version(args.template_name, args.profile)50 if create_response:51 print(create_response)52 else:53 print('Launch Template is already updated with latest AMI.')54 if change_default_version_response:55 print('You have successfully changed the default version to the latest version of the launch template.')56 print(change_default_version_response)57 else:58 print('Launch Template default version is already latest version.')59def list_launch_templates(args):60 try:61 launch_templates = describe_launch_template_versions(args.template_name, args.profile)62 for launch_template in launch_templates:63 print(64 f"version: {str(launch_template['VersionNumber']).zfill(3)}",65 launch_template['CreateTime'],66 launch_template['LaunchTemplateId'],67 launch_template['LaunchTemplateData']['ImageId'],68 )69 except TypeError:70 print('Please enter the exact launch template name.')71def prune_launch_templates(args):72 launch_template_versions = describe_launch_template_versions(args.template_name, args.profile)73 sorted_images = describe_sorted_images(args.ami_name, args.profile)74 count = 075 for launch_template in launch_template_versions:76 flag = ['True' for sorted_image in sorted_images if launch_template['LaunchTemplateData']['ImageId'] in sorted_image['ImageId']]77 if not flag:78 client = start_session(args.profile, 'ec2')79 response = client.delete_launch_template_versions(80 LaunchTemplateId=launch_template['LaunchTemplateId'],81 Versions=[82 str(launch_template['VersionNumber']),83 ]84 )85 print(response)86 count += 1...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!