Setting Up an AWS EC2 Windows Instance in an Existing VPC with IAM Role for S3 Bucket Read/Write Permissions using CloudFormation

This guide outlines the procedure for deploying an AWS EC2 Windows instance using CloudFormation, situated within an existing VPC. The EC2 instance is associated with an IAM role that grants read and write permissions to a specific S3 bucket. Using CloudFormation for the setup process ensures a smooth, automated, and repeatable deployment, effectively managing your AWS resources.

Parameters:

  MyVPC:
    Description: The ID of the existing VPC
    Type: String

  MySubnet:
    Description: The ID of the existing Subnet
    Type: String

Resources:

  MySecurityGroup:
    Type: 'AWS::EC2::SecurityGroup'
    Properties:
      GroupDescription: Security Group for EC2 instance
      VpcId: !Ref MyVPC
      SecurityGroupIngress:
        - IpProtocol: tcp
          CidrIp: '0.0.0.0/0'
          FromPort: 80
          ToPort: 80
        - IpProtocol: tcp
          CidrIp: '0.0.0.0/0'
          FromPort: 443
          ToPort: 443
        - IpProtocol: tcp
          CidrIp: '0.0.0.0/0'
          FromPort: 22
          ToPort: 22

  MyIAMRole:
    Type: 'AWS::IAM::Role'
    Properties:
      RoleName: MyIAMRole
      AssumeRolePolicyDocument:
        Version: 2012-10-17
        Statement:
          - Effect: Allow
            Principal:
              Service: ec2.amazonaws.com
            Action: 'sts:AssumeRole'
      Policies:
        - PolicyName: S3BucketReadWrite
          PolicyDocument:
            Version: 2012-10-17
            Statement:
              - Effect: Allow
                Action:
                  - 's3:PutObject'
                  - 's3:GetObject'
                Resource: 'arn:aws:s3:::bucket-name/*'  # Replace 'bucket-name' with your S3 bucket name

  InstanceProfile:
    Type: 'AWS::IAM::InstanceProfile'
    Properties:
      Roles:
        - !Ref MyIAMRole
      
  MyEC2Instance:
    Type: 'AWS::EC2::Instance'
    Properties:
      ImageId: ami-0b898040803850657  # This is an example ID for a Windows Server 2019 in us-east-1. Change it to your AMI ID.
      InstanceType: t2.micro
      KeyName: MyKeyPair  # Use your key pair name
      IamInstanceProfile: !Ref InstanceProfile
      NetworkInterfaces:
        - DeviceIndex: 0
          SubnetId: !Ref MySubnet
          GroupSet:
            - !Ref MySecurityGroup
          AssociatePublicIpAddress: false

Outputs:
  InstanceId:
    Description: The Instance ID
    Value: !Ref MyEC2Instance
ALSO READ  How to Tackle CORS Errors in Your Lambda API: A Comprehensive Guide

Abhay Singh

I'm Abhay Singh, an Architect with 9 Years of It experience. AWS Certified Solutions Architect.

More Reading

Post navigation

Leave a Comment

Leave a Reply

Your email address will not be published. Required fields are marked *