我正在编写用于创建安全组和ec2-instance的脚本,并附加了先前创建的安全组。但是我看不到带有安全组id
的变量。看我的代码:
import boto3
from botocore.exceptions import ClientError
SECURITY_GROUP_NAME='TEST2'
DESCRIPTION='TEST2'
image_id='MY_AMI'
instance_type='t2.micro'
keypair_name='MY_KEY'
ec2 = boto3.client('ec2')
security_group_id=''
def create_security_group(SECURITY_GROUP_NAME,DESCRIPTION):
response = ec2.describe_vpcs()
vpc_id = response.get('Vpcs', [{}])[0].get('VpcId', '')
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': 'tcp',
'FromPort': 80,
'ToPort': 80,
'IpRanges': [{'CidrIp': '0.0.0.0/0'}]},
{'IpProtocol': 'tcp',
'FromPort': 22,
'ToPort': 22,
'IpRanges': [{'CidrIp': '0.0.0.0/0'}]}
])
print('Ingress Successfully Set %s' % data)
except ClientError as e:
print(e)
print(security_group_id)
print('##################')
def create_ec2_instance(image_id,instance_type,keypair_name,security_group_id):
try:
response = ec2.run_instances(ImageId=image_id,
InstanceType=instance_type,
KeyName=keypair_name,
MinCount=1,
MaxCount=1,
SecurityGroupIds=[security_group_id])
except ClientError as e:
print(e)
return None
return response['Instances'][0]
create_security_group(SECURITY_GROUP_NAME,DESCRIPTION)
print('!!!!!!!!!!!!!!!!!!!')
print(security_group_id)
create_ec2_instance(image_id,instance_type,keypair_name,security_group_id)
在此脚本的输出中,我看到:
Security Group Created MY_SECURITY_GROUP in vpc MY_VPC.
Ingress Successfully Set {'ResponseMetadata': {'RequestId': 'MY_REQUEST_ID', 'HTTPStatusCode': 200, 'HTTPHeaders': {'content-type': 'text/xml;charset=UTF-8', 'content-length': '259', 'date': 'Fri, 12 Jul 2019 10:37:24 GMT', 'server': 'AmazonEC2'}, 'RetryAttempts': 0}}
MY_SECURITY_GROUP
##################
!!!!!!!!!!!!!!!!!!!
An error occurred (MissingParameter) when calling the RunInstances operation: When specifying a security group you must specify one of group id or group name for each item
因此,根据我的代码,我必须在安全组的!!!!!!!!!!!!!!!!!!!
和id
之后收到。但是你怎么看,我看到了空白。我可以做什么,以便在此函数之外接收此变量?