DEV Community

Lasantha Sanjeewa Silva
Lasantha Sanjeewa Silva

Posted on • Edited on

Provisioning an EC2 instance with CloudFormation

AWS CloudFormation performs the crazy party trick of enabling you to manage your complete AWS infrastructure and resources from a text file. The formatted YAML or JSON code you write in the AWS CloudFormation template describes your AWS infrastructure and the resources you need. CloudFormation does the rest, provisioning, configuring and deploying everything for you.

1st of all we want to configure AWS CLI using aws configure command.

After that create ec2.yaml and add following code.

AWSTemplateFormatVersion: 2010-09-09
Description: EC2 Instance Create Using CloudFormation

Resources:
  WebAppInstance:
    Type: AWS::EC2::Instance
    Properties:
      ImageId: ami-002068ed284fb165b #AMI ID Unique to Region
      InstanceType: t2.micro
      KeyName: ohio-key #Add keypair name
      SecurityGroupIds:
        - !Ref WebAppSecurityGroup

  WebAppSecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupName: !Join [ '-', [ webapp-security-group, dev ] ]
      GroupDescription: 'Allow HTTP/HTTPS and SSH inbound and outbound traffic'
      SecurityGroupIngress:
        - IpProtocol: tcp
          FromPort: 80
          ToPort: 80
          CidrIp: 0.0.0.0/0
        - IpProtocol: tcp
          FromPort: 443
          ToPort: 443
          CidrIp: 0.0.0.0/0
        - IpProtocol: tcp
          FromPort: 22
          ToPort: 22
          CidrIp: 0.0.0.0/0

  WebAppEIP:
    Type: AWS::EC2::EIP
    Properties:
      Domain: vpc
      InstanceId: !Ref WebAppInstance
      Tags:
        - Key: Name
          Value: !Join [ '-', [ webapp-eip, dev ] ]

Outputs:
  WebsiteURL:
    Value: !Sub http://${WebAppEIP}
    Description: WebApp URL
Enter fullscreen mode Exit fullscreen mode

After that run following command for create CloudFormation Stack.
aws cloudformation create-stack --stack-name ec2-stack --template-body file://ec2.yaml --output yaml

Go to AWS console and search CloudFormation and you can see the newly created stack and you can see output details.
Image description

After that go to EC2 Service and you can see the newly created EC2 instance.

Image description

If you want you can update stack details using following command.
aws cloudformation update-stack --stack-name ec2-stack --template-body file://ec2.yaml --output yaml

Finally, you can destroy AWS Infrastructure using the following command. Please remind that if you destroy you will lose created infrastructure.

aws cloudformation delete-stack --stack-name ec2-stack --output yaml

Image description

After that go to AWS Console and you can see Your EC2 Instance is terminated.

Image description

Thanks for reading the Article.

Top comments (0)