我已经编写了一个代码来使用对流层创建 CloudFormation 模板,我在其中创建 EC2 实例并分配 SG 和 EIP,但在运行 python 代码时出错。代码如下:
from troposphere import Ref, Template, join, GetAtt, Parameter
import troposphere.ec2 as ec2
template = Template()
#Creating Security Group
SSHSecurityGroup = ec2.SecurityGroup('SSHSecurityGroup')
SSHSecurityGroup.GroupDescription = "Enable SSH access bia port 22"
SSHSecurityGroup.SecurityGroupIngress = [
ec2.SecurityGroupRule(
CidrIP="0.0.0.0/0",
FromPort="22",
IpProtocol="tcp",
ToPort="22",
)]
ServerSecurityGroup = ec2.SecurityGroup('ServerSecurityGroup')
ServerSecurityGroup.GroupDescription("Allow access from specified CIDR range")
ServerSecurityGroup.SecurityGroupIngress = [
ec2.SecurityGroupRule(
IpProtocol="tcp",
FromPort="80",
ToPort="80",
CidrIp="0.0.0.0/0",
IpProtocol="tcp",
FromPort="22",
ToPort="22",
CidrIP="192.168.1.1/32",
)]
template.add_resource(SSHSecurityGroup)
template.add_resource(ServerSecurityGroup)
#Creating EC2 Instance
ec2_instance = template.add_resource(ec2.Instance("MyEC2Intsance",
ImageId="ami-i23df45832",
AvailabilityZone="us-east-2",
InstanceType="t2.micro",
EIP=Ref(MyEIP),
SecurityGroups=[Ref(SSHSecurityGroup),Ref(ServerSecurityGroup)],
))
#Creating EIP
MyEIP = ec2.EIP("MyEIP", InstanceId=Ref(MyEC2Intsance)
#template.add_resource(MyEIP)
print(template.to_yaml())```