i have written a code to create CloudFormation template using troposphere where i am creating EC2 instance and assiging SG and EIP but getting error while running python code. Code is below:
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())```
This line needs a trailing (closing) paren: Change this:
MyEIP = ec2.EIP("MyEIP", InstanceId=Ref(MyEC2Intsance)
to this:
MyEIP = ec2.EIP("MyEIP", InstanceId=Ref(MyEC2Intsance))
And there are other issues with the SecurityGroupIngress/SecurityGroupRules but don't know how to guide since not sure what you're attempting.