boto3:创建Spot实例

2024-05-14 05:58:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用boto3创建一个spot实例。尽管我遵循API documentation,但我收到了一个无法解决的异常。我使用的代码是:

import boto3
import datetime
client = boto3.client('ec2')
response = client.request_spot_instances(
    DryRun=False,
    SpotPrice='0.10',
    ClientToken='string',
    InstanceCount=1,
    Type='one-time',
    LaunchSpecification={
        'ImageId': 'ami-fce3c696',
        'KeyName': 'awskey.pem',
        'SecurityGroups': ['sg-709f8709'],
        'InstanceType': 'm4.large',
        'Placement': {
            'AvailabilityZone': 'us-east-1a',
        },
        'BlockDeviceMappings': [
            {
                'Ebs': {
                    'SnapshotId': 'snap-f70deff0',
                    'VolumeSize': 100,
                    'DeleteOnTermination': True,
                    'VolumeType': 'gp2',
                    'Iops': 300,
                    'Encrypted': False
                },
            },
        ],

        'EbsOptimized': True,
        'Monitoring': {
            'Enabled': True
        },
        'SecurityGroupIds': [
            'sg-709f8709',
        ]
    }
)

我收到以下异常:

botocore.exceptions.ClientError: An error occurred (InvalidParameterValue) when calling the RequestSpotInstances operation: Value () for parameter groupId is invalid. The value cannot be empty

问题是API documentation中的请求中没有groupId参数。

我遗漏了什么吗?


Tags: 实例代码importclientapifalsetruedatetime
2条回答

尝试使用安全组ID,它工作正常。

#!/usr/bin/python3.6
import boto3

session=boto3.session.Session(profile_name="*****")
ec2instances=session.resource('ec2',region_name="********")
new_instance = ec2instances.create_instances(
        ImageId = 'ami-04125d804acca5692',
        MinCount = 1,
        MaxCount = 1,
        InstanceType = 't2.micro',
        KeyName ='xxxxxxxxxxxxxxxxx',
        SecurityGroupIds=['sg-05dec40ce8b91a8c8'],
        SubnetId = 'subnet-01ca807d148d9e328'
)
print(new_instance)

虽然API文档中没有指定,但显然“security groups”参数需要安全组的名称,而不是ID。

更改组名解决了问题。

谢谢有人第一时间费心阅读这个问题。

相关问题 更多 >