Search code examples
amazon-web-servicesamazon-ec2boto3boto

How to create spot instance with boto3 with required instance attributes instead of instance type


I am able to create spot instance with below code

import boto3
import datetime, random, string, json
client = boto3.client('ec2')
response = client.request_spot_instances(
    DryRun=False,
    ClientToken=''.join(random.choices(string.ascii_uppercase + string.digits, k=10)),
    InstanceCount=1,
    Type='one-time',
    LaunchSpecification={
        'ImageId': 'ami-053ebee0bc662f9b3',
        'SecurityGroups': ['default'],
        'InstanceType': 't3.medium',
        'Placement': {
            'AvailabilityZone': 'us-east-1a',
        },
        'BlockDeviceMappings': [
            {
            },
        ],
        'EbsOptimized': True,
        'Monitoring': {
            'Enabled': True
        },
        'SecurityGroupIds': [
            'sg-03432e1f',
        ]
    }
)

print(json.dumps(response))

I am fine with any instances with at least 2 vCPUs and not just t3.medium, how can I change the requirement to that?


Solution

  • You have to use create_fleet instead of request_spot_instances. Only create_fleet allows you to specify VCpuCount and MemoryMiB.