Launch and configure an ec2 instance with the given properties.
(
*,
key_name: str | None,
instance_type: str,
ami: str,
ami_user: str,
tags: dict[str, str],
display_name: str | None = None,
size_gb: int,
security_group_name: str,
instance_profile: str | None,
nonce: str,
delete_after: datetime.datetime,
)
| 389 | |
| 390 | |
| 391 | def launch( |
| 392 | *, |
| 393 | key_name: str | None, |
| 394 | instance_type: str, |
| 395 | ami: str, |
| 396 | ami_user: str, |
| 397 | tags: dict[str, str], |
| 398 | display_name: str | None = None, |
| 399 | size_gb: int, |
| 400 | security_group_name: str, |
| 401 | instance_profile: str | None, |
| 402 | nonce: str, |
| 403 | delete_after: datetime.datetime, |
| 404 | ) -> Instance: |
| 405 | """Launch and configure an ec2 instance with the given properties.""" |
| 406 | |
| 407 | if display_name: |
| 408 | tags["Name"] = display_name |
| 409 | tags["scratch-delete-after"] = str(delete_after.timestamp()) |
| 410 | tags["nonce"] = nonce |
| 411 | tags["git_ref"] = git.describe() |
| 412 | tags["ami-user"] = ami_user |
| 413 | |
| 414 | ec2 = boto3.client("ec2") |
| 415 | groups = ec2.describe_security_groups() |
| 416 | security_group_id = None |
| 417 | for group in groups["SecurityGroups"]: |
| 418 | if group["GroupName"] == security_group_name: |
| 419 | security_group_id = group["GroupId"] |
| 420 | break |
| 421 | |
| 422 | if security_group_id is None: |
| 423 | vpcs = ec2.describe_vpcs() |
| 424 | vpc_id = None |
| 425 | for vpc in vpcs["Vpcs"]: |
| 426 | if vpc["IsDefault"]: |
| 427 | vpc_id = vpc["VpcId"] |
| 428 | break |
| 429 | if vpc_id is None: |
| 430 | default_vpc = ec2.create_default_vpc() |
| 431 | vpc_id = default_vpc["Vpc"]["VpcId"] |
| 432 | securitygroup = ec2.create_security_group( |
| 433 | GroupName=security_group_name, |
| 434 | Description="Allows all.", |
| 435 | VpcId=vpc_id, |
| 436 | ) |
| 437 | security_group_id = securitygroup["GroupId"] |
| 438 | ec2.authorize_security_group_ingress( |
| 439 | GroupId=security_group_id, |
| 440 | CidrIp="0.0.0.0/0", |
| 441 | IpProtocol="tcp", |
| 442 | FromPort=22, |
| 443 | ToPort=22, |
| 444 | ) |
| 445 | |
| 446 | network_interface: InstanceNetworkInterfaceSpecificationTypeDef = { |
| 447 | "AssociatePublicIpAddress": True, |
| 448 | "DeviceIndex": 0, |