我试图通过在代码执行过程中传递变量来在特定vpc内创建安全组,但是当我对变量运行以下命令时,出现以下错误。
./create_sg.py vpc-e79569b2 dev_test_sg testing tcp 22 22 0.0.0.0/0
调用CreateSecurityGroup操作时发生错误(InvalidVpcID.NotFound):vpc ID'VPC_ID'不存在
#!/usr/bin/env python
import sys
import boto3
from botocore.exceptions import ClientError
region = "us-west-1"
VPC_ID=sys.argv[0]
SECURITY_GROUP_NAME=sys.argv[1]
DESCRIPTION=sys.argv[2]
IP_PROTOCOL_1=sys.argv[3]
FROM_PORT_1=sys.argv[4]
TO_PORT_1=sys.argv[5]
CIDR_IP_1=sys.argv[6]
ec2 = boto3.client('ec2')
response = ec2.describe_vpcs()
vpc_id = 'VPC_ID'
try:
response = ec2.create_security_group(GroupName='SECURITY_GROUP_NAME',Description='DESCRIPTION',VpcId=vpc_id)
security_group_id = response['GroupId']
print('Security Group Created %s in vpc %s.' % (security_group_id, vpc_id))
data = ec2.authorize_security_group_ingress(
GroupId=security_group_id,
IpPermissions=[
{'IpProtocol': 'IP_PROTOCOL_1',
'FromPort': FROM_PORT_1,
'ToPort': TO_PORT_1,
'IpRanges': [{'CidrIp': 'CIDR_IP_1'}]}
])
print('Ingress Successfully Set %s' % data)
except ClientError as e:
print(e)
请查看代码,让我知道是否需要在其中进行更改以成功创建安全组。
答案 0 :(得分:3)
这行全错了...
response = ec2.create_security_group(GroupName='SECURITY_GROUP_NAME',Description='DESCRIPTION',VpcId=vpc_id)
IMO应该是:
response = ec2.create_security_group(GroupName=SECURITY_GROUP_NAME,Description=DESCRIPTION,VpcId=VPC_ID)
好的,这是完整的代码,其中包含对字符串文字的更正:
#!/usr/bin/env python
import sys
import boto3
from botocore.exceptions import ClientError
region = "us-west-1"
VPC_ID=sys.argv[0]
SECURITY_GROUP_NAME=sys.argv[1]
DESCRIPTION=sys.argv[2]
IP_PROTOCOL_1=sys.argv[3]
FROM_PORT_1=sys.argv[4]
TO_PORT_1=sys.argv[5]
CIDR_IP_1=sys.argv[6]
ec2 = boto3.client('ec2')
response = ec2.describe_vpcs()
try:
response = ec2.create_security_group(GroupName=SECURITY_GROUP_NAME,Description=DESCRIPTION,VpcId=VPC_ID)
security_group_id = response['GroupId']
print('Security Group Created %s in vpc %s.' % (security_group_id, VPC_ID))
data = ec2.authorize_security_group_ingress(
GroupId=security_group_id,
IpPermissions=[
{'IpProtocol': IP_PROTOCOL_1,
'FromPort': int(FROM_PORT_1),
'ToPort': int(TO_PORT_1),
'IpRanges': [{'CidrIp': CIDR_IP_1}]}
])
print('Ingress Successfully Set %s' % data)
except ClientError as e:
print(e)
答案 1 :(得分:2)
尝试删除'VPC_ID'
周围的引号:
vpc_id = VPC_ID