如何使用 boto3 create_instances() 分配安全组和子网?



我正在尝试为我在python中创建的AWS实例分配安全组列表和子网。

当我指出我分配的安全组在我指定的 VPC 中不存在时,我收到错误:

An error occurred (InvalidGroup.NotFound) when calling the RunInstances The security group 'sg-05ef09508245e56bc, sg-2cad407c, sg-0afa867f9029bb468, sg-0e4b5fc1d40185fc3, sg-031ac185d029cd5fd, sg-0d0ddf3117d23cadb' does not exist in VPC 'vpc-68b1ff12'

但是,正如 CLI 将证明的那样,这并不准确。这些安全组实际上确实存在于我指定的 VPC 中。

aws ec2 describe-security-groups --filters=Name=vpc-id,Values=vpc-68b1ff12 --profile=my-aws-account | jq -r '.SecurityGroups[].GroupId'
sg-031ac185d029cd5fd
sg-05ef09508245e56bc
sg-0afa867f9029bb468
sg-0d0ddf3117d23cadb
sg-0e4b5fc1d40185fc3
sg-2cad407c

您将看到错误中列出的 VPC 中不存在的 SG 位于属于该 VPC 的 SG 列表中。它们是相同的,因此这确认了该 VPC 中存在 SG。

这是我用来创建实例的代码:

image_id = input("Enter an AMI ID: ")
max_count = input("Enter how many EC2 Servers: ")
key_name = input("Enter the key name to use: ")
instance_type = input("Enter the instance type: ")
name_tag = input("Enter the name tag: ")
aws_account = input("Enter the account name: ")
region = input("Enter the region: ")
sg_list = input("Enter a comma separated list of security groups to add: ")
sg_list = str(sg_list)
private_ip_answer = input("Specify an ip address (y/n): ")
if private_ip_answer.lower() == 'y' or private_ip_answer.lower() == 'yes':
private_ip = input("Enter a private ip addres: ")
else:
private_ip = ''
def create_instances(image_id, max_count, key_name, instance_type, name_tag, aws_account, region, subnet_id, sg_list, private_ip):
session = boto3.Session(profile_name=aws_account, region_name=region)
ec2_resource = session.resource("ec2")
instances = ''
instances = ec2_resource.create_instances(
ImageId=image_id,
InstanceType=instance_type,
KeyName=key_name,
MaxCount=max_count,
MinCount=1,
DisableApiTermination=True,
InstanceInitiatedShutdownBehavior='stop',
NetworkInterfaces=[
{
'AssociatePublicIpAddress': False,
'DeleteOnTermination': True,
'DeviceIndex': 0,
'Groups': [
sg_list,
],
'PrivateIpAddress': private_ip,
'SubnetId': subnet_id
}
]
)

那么,为什么 boto3 坚持认为这些 SG 标识符在我选择的 VPC 中不存在呢?我怎样才能让它工作?我需要能够同时指定安全组和子网。

错误指出名为

'sg-05ef09508245e56bc, sg-2cad407c, sg-0afa867f9029bb468, sg-0e4b5fc1d40185fc3, sg-031ac185d029cd5fd, sg-0d0ddf3117d23cadb'

不存在。 Python 需要一个列表,而你向它传递一个列表,该列表由一串逗号分隔的项目组成。 正确的操作是使用 split 创建项目列表:

NetworkInterfaces=[
{
'AssociatePublicIpAddress': False,
'DeleteOnTermination': True,
'DeviceIndex': 0,
'Groups': sg_list.split(','),
'PrivateIpAddress': private_ip,
'SubnetId': subnet_id
}
]

最新更新