EC2のWin2025へRDP接続

SSM経由で直接RDPポートを開かず接続する。
```yaml
AWSTemplateFormatVersion: "2010-09-09"
Description: "Deploy Windows Server 2025 on EC2 with AWS Systems Manager (SSM) for remote access"

Resources:
  # IAM Role for SSM
  SSMRole:
    Type: AWS::IAM::Role
    Properties:
      RoleName: !Sub "SSMRole-${AWS::StackName}"
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Effect: Allow
            Principal:
              Service:
                - ec2.amazonaws.com
            Action:
              - sts:AssumeRole
      ManagedPolicyArns:
        - arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore

  # Instance Profile for SSM
  InstanceProfile:
    Type: AWS::IAM::InstanceProfile
    Properties:
      Path: "/"
      Roles:
        - !Ref SSMRole

  # キーペアの作成
  KeyPair:
    Type: AWS::EC2::KeyPair
    Properties:
      KeyName: !Sub "${AWS::StackName}-key"

  # セキュリティグループ (完全クローズ: SSH, RDP 不要)
  EC2SecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupDescription: "No inbound access, managed by SSM"
      VpcId: !Ref VPC

  # Windows Server 2025 の EC2 インスタンス
  WindowsInstance:
    Type: AWS::EC2::Instance
    Properties:
      InstanceType: t3.large
      IamInstanceProfile: !Ref InstanceProfile
      KeyName: !Ref KeyPair # キーペアを追加
      ImageId: !Sub "{{resolve:ssm:/aws/service/ami-windows-latest/Windows_Server-2025-Japanese-Full-Base:1}}"
      NetworkInterfaces:
        - AssociatePublicIpAddress: true
          DeviceIndex: 0
          SubnetId: !Ref PublicSubnet
          GroupSet:
            - !Ref EC2SecurityGroup
      BlockDeviceMappings:
        - DeviceName: "/dev/sda1" # ルートボリューム
          Ebs:
            VolumeType: gp3
            VolumeSize: 128
            Iops: 3000
            DeleteOnTermination: true
      Tags:
        - Key: Name
          Value: "Windows2025-Instance"

  VPC:
    Type: AWS::EC2::VPC
    Properties:
      CidrBlock: "10.0.0.0/16"
      EnableDnsSupport: true
      EnableDnsHostnames: true
      Tags:
        - Key: Name
          Value: "Windows2025-VPC"

  PublicSubnet:
    Type: AWS::EC2::Subnet
    Properties:
      VpcId: !Ref VPC
      CidrBlock: "10.0.1.0/24"
      MapPublicIpOnLaunch: true
      AvailabilityZone: "us-west-2a"
      Tags:
        - Key: Name
          Value: "PublicSubnet"

  InternetGateway:
    Type: AWS::EC2::InternetGateway
    Properties:
      Tags:
        - Key: Name
          Value: "Windows2025-IGW"

  # IGW を VPC にアタッチする
  InternetGatewayAttachment:
    Type: AWS::EC2::VPCGatewayAttachment
    Properties:
      VpcId: !Ref VPC
      InternetGatewayId: !Ref InternetGateway

  # ルートテーブル
  RouteTable:
    Type: AWS::EC2::RouteTable
    Properties:
      VpcId: !Ref VPC
      Tags:
        - Key: Name
          Value: "PublicRouteTable"

  # ルート (IGW のアタッチ後に正しく関連付け)
  Route:
    Type: AWS::EC2::Route
    DependsOn: InternetGatewayAttachment # 依存関係を追加
    Properties:
      RouteTableId: !Ref RouteTable
      DestinationCidrBlock: "0.0.0.0/0"
      GatewayId: !Ref InternetGateway

  # サブネットにルートテーブルを関連付け
  RouteTableAssociation:
    Type: AWS::EC2::SubnetRouteTableAssociation
    Properties:
      SubnetId: !Ref PublicSubnet
      RouteTableId: !Ref RouteTable

Outputs:
  InstanceID:
    Description: "EC2 instance ID for Session Manager"
    Value: !Ref WindowsInstance

  KeyPairName:
    Description: "The name of the created Key Pair"
    Value: !Ref KeyPair

```
## 接続方法
- Fleet Managerで接続する場合（に必要なキーペア）
```bash
aws ec2 describe-key-pairs --filters Name=key-name,Values=win2025-key --query KeyPairs[*].KeyPairId --output text

aws ssm get-parameter --name /ec2/keypair/出力されたキー名 --with-decryption --query Parameter.Value --output text > Windows2025-Key.pem
```

- SSM 経由でポートフォワード
```ssh
aws ssm start-session --target <EC2_INSTANCE_ID> --document-name AWS-StartPortForwardingSession --parameters "portNumber=3389,localPortNumber=13389"

```
RDP クライアントで localhost:13389 に接続する。

##### EC2 の管理者 (Administrator) パスワードの取得方法

Windows Server の EC2 インスタンスでは、デフォルトの Administrator のパスワードは EC2 のキーペアを使って復号 する必要があります。

- AWS マネジメントコンソールで取得する場合
AWS マネジメントコンソールにログイン
EC2 インスタンスのページを開く
対象の Windows Server 2025 インスタンスを選択
「アクション」 → 「Windows パスワードの取得」
作成したキーペア (Windows2025-Key-xxxx.pem) をアップロード
パスワードが表示される
<br>

- AWS CLI で取得する場合
```bash
aws ec2 get-password-data --instance-id <インスタンスID> --priv-launch-key Windows2025-Key.pem
```

NoSSM
```yaml
AWSTemplateFormatVersion: "2010-09-09"
Description: "Deploy Windows Server 2025 on EC2 with RDP access (no SSM)"

Resources:
  # ----------------------------------------------------
  # VPCおよびインターネットアクセス関連リソース
  # ----------------------------------------------------
  VPC:
    Type: AWS::EC2::VPC
    Properties:
      CidrBlock: "10.0.0.0/16"
      EnableDnsSupport: true
      EnableDnsHostnames: true
      Tags:
        - Key: Name
          Value: "Windows2025-VPC"

  PublicSubnet:
    Type: AWS::EC2::Subnet
    Properties:
      VpcId: !Ref VPC
      CidrBlock: "10.0.1.0/24"
      MapPublicIpOnLaunch: true
      AvailabilityZone: "us-west-2a"
      Tags:
        - Key: Name
          Value: "PublicSubnet"

  InternetGateway:
    Type: AWS::EC2::InternetGateway
    Properties:
      Tags:
        - Key: Name
          Value: "Windows2025-IGW"

  InternetGatewayAttachment:
    Type: AWS::EC2::VPCGatewayAttachment
    Properties:
      VpcId: !Ref VPC
      InternetGatewayId: !Ref InternetGateway

  RouteTable:
    Type: AWS::EC2::RouteTable
    Properties:
      VpcId: !Ref VPC
      Tags:
        - Key: Name
          Value: "PublicRouteTable"

  Route:
    Type: AWS::EC2::Route
    DependsOn: InternetGatewayAttachment
    Properties:
      RouteTableId: !Ref RouteTable
      DestinationCidrBlock: "0.0.0.0/0"
      GatewayId: !Ref InternetGateway

  RouteTableAssociation:
    Type: AWS::EC2::SubnetRouteTableAssociation
    Properties:
      SubnetId: !Ref PublicSubnet
      RouteTableId: !Ref RouteTable

  # ----------------------------------------------------
  # キーペア
  # ----------------------------------------------------
  KeyPair:
    Type: AWS::EC2::KeyPair
    Properties:
      KeyName: !Sub "${AWS::StackName}-key"

  # ----------------------------------------------------
  # セキュリティグループ (RDP 接続を許可)
  # ----------------------------------------------------
  EC2SecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupDescription: "Allow RDP from anywhere"
      VpcId: !Ref VPC
      SecurityGroupIngress:
        - IpProtocol: tcp
          FromPort: 3389
          ToPort: 3389
          CidrIp: 0.0.0.0/0
      SecurityGroupEgress:
        - IpProtocol: -1
          CidrIp: 0.0.0.0/0

  # ----------------------------------------------------
  # Windows Server 2025 の EC2 インスタンス (RDP 接続)
  # ----------------------------------------------------
  WindowsInstance:
    Type: AWS::EC2::Instance
    Properties:
      InstanceType: t3.large
      # IAMインスタンスプロファイルを削除 (SSM を使わないため)
      KeyName: !Ref KeyPair
      ImageId: !Sub "{{resolve:ssm:/aws/service/ami-windows-latest/Windows_Server-2025-Japanese-Full-Base:1}}"
      NetworkInterfaces:
        - AssociatePublicIpAddress: true
          DeviceIndex: 0
          SubnetId: !Ref PublicSubnet
          GroupSet:
            - !Ref EC2SecurityGroup
      BlockDeviceMappings:
        - DeviceName: "/dev/sda1"
          Ebs:
            VolumeType: gp3
            VolumeSize: 128
            Iops: 3000
            DeleteOnTermination: true
      Tags:
        - Key: Name
          Value: "Windows2025-Instance-RDP"

Outputs:
  InstanceID:
    Description: "EC2 instance ID for RDP"
    Value: !Ref WindowsInstance

  KeyPairName:
    Description: "The name of the created Key Pair"
    Value: !Ref KeyPair

```

NoSSM&S3
```yaml
AWSTemplateFormatVersion: "2010-09-09"
Description: "Deploy Windows Server 2025 on EC2 with RDP access (no SSM) + S3FullAccess"

Resources:
  # ----------------------------------------------------
  # VPCおよびインターネットアクセス関連リソース
  # ----------------------------------------------------
  VPC:
    Type: AWS::EC2::VPC
    Properties:
      CidrBlock: "10.0.0.0/16"
      EnableDnsSupport: true
      EnableDnsHostnames: true
      Tags:
        - Key: Name
          Value: "Windows2025-VPC"

  PublicSubnet:
    Type: AWS::EC2::Subnet
    Properties:
      VpcId: !Ref VPC
      CidrBlock: "10.0.1.0/24"
      MapPublicIpOnLaunch: true
      AvailabilityZone: "us-west-2a"
      Tags:
        - Key: Name
          Value: "PublicSubnet"

  InternetGateway:
    Type: AWS::EC2::InternetGateway
    Properties:
      Tags:
        - Key: Name
          Value: "Windows2025-IGW"

  InternetGatewayAttachment:
    Type: AWS::EC2::VPCGatewayAttachment
    Properties:
      VpcId: !Ref VPC
      InternetGatewayId: !Ref InternetGateway

  RouteTable:
    Type: AWS::EC2::RouteTable
    Properties:
      VpcId: !Ref VPC
      Tags:
        - Key: Name
          Value: "PublicRouteTable"

  Route:
    Type: AWS::EC2::Route
    DependsOn: InternetGatewayAttachment
    Properties:
      RouteTableId: !Ref RouteTable
      DestinationCidrBlock: "0.0.0.0/0"
      GatewayId: !Ref InternetGateway

  RouteTableAssociation:
    Type: AWS::EC2::SubnetRouteTableAssociation
    Properties:
      SubnetId: !Ref PublicSubnet
      RouteTableId: !Ref RouteTable

  # ----------------------------------------------------
  # キーペア
  # ----------------------------------------------------
  KeyPair:
    Type: AWS::EC2::KeyPair
    Properties:
      KeyName: !Sub "${AWS::StackName}-key"

  # ----------------------------------------------------
  # セキュリティグループ (RDP 接続許可)
  # ----------------------------------------------------
  EC2SecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupDescription: "Allow RDP from my IP"
      VpcId: !Ref VPC
      SecurityGroupIngress:
        - IpProtocol: tcp
          FromPort: 3389
          ToPort: 3389
          # 必要に応じて自分のグローバルIPに置き換えてください (例: 203.0.113.25/32)
          CidrIp: "0.0.0.0/0"
      SecurityGroupEgress:
        - IpProtocol: -1
          CidrIp: "0.0.0.0/0"

  # ----------------------------------------------------
  # IAM Role (EC2用) + S3FullAccess
  # ----------------------------------------------------
  EC2Role:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Effect: Allow
            Principal:
              Service:
                - ec2.amazonaws.com
            Action:
              - sts:AssumeRole
      ManagedPolicyArns:
        - arn:aws:iam::aws:policy/AmazonS3FullAccess

  EC2InstanceProfile:
    Type: AWS::IAM::InstanceProfile
    Properties:
      Path: "/"
      Roles:
        - !Ref EC2Role

  # ----------------------------------------------------
  # Windows Server 2025 の EC2 インスタンス (RDP 接続)
  # ----------------------------------------------------
  WindowsInstance:
    Type: AWS::EC2::Instance
    Properties:
      InstanceType: t3.large
      KeyName: !Ref KeyPair
      ImageId: !Sub "{{resolve:ssm:/aws/service/ami-windows-latest/Windows_Server-2025-Japanese-Full-Base:1}}"
      IamInstanceProfile: !Ref EC2InstanceProfile
      NetworkInterfaces:
        - AssociatePublicIpAddress: true
          DeviceIndex: 0
          SubnetId: !Ref PublicSubnet
          GroupSet:
            - !Ref EC2SecurityGroup
      BlockDeviceMappings:
        - DeviceName: "/dev/sda1"
          Ebs:
            VolumeType: gp3
            VolumeSize: 128
            Iops: 3000
            DeleteOnTermination: true
      Tags:
        - Key: Name
          Value: "Windows2025-Instance-RDP"

Outputs:
  InstanceID:
    Description: "EC2 instance ID for RDP"
    Value: !Ref WindowsInstance

  KeyPairName:
    Description: "The name of the created Key Pair"
    Value: !Ref KeyPair

```

---------------------------------------
- 踏み台利用しssm使用しない
```yaml
AWSTemplateFormatVersion: "2010-09-09"
Description: >
  Create a Windows Server 2022 (Japanese Full Base) instance in us-west-2d and
  an Amazon Linux bastion in us-west-2a, with secure RDP via the bastion.
  SSMやNATゲートウェイは使用しません。

Parameters:
  BastionAMI:
    Type: AWS::SSM::Parameter::Value<AWS::EC2::Image::Id>
    Description: Amazon Linux 2 の最新 AMI (us-west-2)
    Default: /aws/service/ami-amazon-linux-latest/amzn2-ami-hvm-x86_64-gp2

  WindowsAMI:
    Type: AWS::SSM::Parameter::Value<AWS::EC2::Image::Id>
    Description: Windows Server 2022 Japanese Full Base の最新 AMI (us-west-2)
    Default: /aws/service/ami-windows-latest/Windows_Server-2022-Japanese-Full-Base

Resources:

  # -------------------------------------------------------
  # キーペア作成 (自動)
  # -------------------------------------------------------
  KeyPair:
    Type: AWS::EC2::KeyPair
    Properties:
      KeyName: !Sub "${AWS::StackName}-key"
      KeyType: rsa
      KeyFormat: pem
      Tags:
        - Key: Name
          Value: !Sub "${AWS::StackName}-KeyPair"

  # -------------------------------------------------------
  # VPC and Networking
  # -------------------------------------------------------
  VPC:
    Type: AWS::EC2::VPC
    Properties:
      CidrBlock: 10.0.0.0/16
      EnableDnsSupport: true
      EnableDnsHostnames: true

  InternetGateway:
    Type: AWS::EC2::InternetGateway

  VPCGatewayAttachment:
    Type: AWS::EC2::VPCGatewayAttachment
    Properties:
      VpcId: !Ref VPC
      InternetGatewayId: !Ref InternetGateway

  PublicRouteTable:
    Type: AWS::EC2::RouteTable
    Properties:
      VpcId: !Ref VPC
      Tags:
        - Key: Name
          Value: !Sub "${AWS::StackName}-PublicRouteTable"

  PublicRoute:
    Type: AWS::EC2::Route
    DependsOn: VPCGatewayAttachment
    Properties:
      RouteTableId: !Ref PublicRouteTable
      DestinationCidrBlock: 0.0.0.0/0
      GatewayId: !Ref InternetGateway

  PublicSubnetA:
    Type: AWS::EC2::Subnet
    Properties:
      VpcId: !Ref VPC
      AvailabilityZone: us-west-2a
      CidrBlock: 10.0.1.0/24
      MapPublicIpOnLaunch: true

  PublicSubnetARouteTableAssociation:
    Type: AWS::EC2::SubnetRouteTableAssociation
    Properties:
      SubnetId: !Ref PublicSubnetA
      RouteTableId: !Ref PublicRouteTable

  PublicSubnetD:
    Type: AWS::EC2::Subnet
    Properties:
      VpcId: !Ref VPC
      AvailabilityZone: us-west-2d
      CidrBlock: 10.0.2.0/24
      MapPublicIpOnLaunch: true

  # -------------------------------------------------------
  # セキュリティグループ
  # -------------------------------------------------------
  BastionSG:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupDescription: Allow SSH from all
      VpcId: !Ref VPC
      SecurityGroupIngress:
        - IpProtocol: tcp
          FromPort: 22
          ToPort: 22
          CidrIp: 0.0.0.0/0
      SecurityGroupEgress:
        - IpProtocol: -1
          CidrIp: 0.0.0.0/0

  WindowsSG:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupDescription: Allow RDP from Bastion
      VpcId: !Ref VPC
      SecurityGroupIngress:
        - IpProtocol: tcp
          FromPort: 3389
          ToPort: 3389
          SourceSecurityGroupId: !Ref BastionSG
      SecurityGroupEgress:
        - IpProtocol: -1
          CidrIp: 0.0.0.0/0

  # -------------------------------------------------------
  # IAM Role for Windows (S3アクセス用)
  # -------------------------------------------------------
  WindowsInstanceRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Effect: Allow
            Principal:
              Service: ["ec2.amazonaws.com"]
            Action: "sts:AssumeRole"
      Policies:
        - PolicyName: S3MyFileTransferAccess
          PolicyDocument:
            Version: "2012-10-17"
            Statement:
              - Effect: Allow
                Action: "s3:*"
                Resource:
                  - !Sub "arn:aws:s3:::hogefiletransfer"
                  - !Sub "arn:aws:s3:::hogefiletransfer/*"

  WindowsInstanceProfile:
    Type: AWS::IAM::InstanceProfile
    Properties:
      Roles:
        - !Ref WindowsInstanceRole

  # -------------------------------------------------------
  # EC2 Instances
  # -------------------------------------------------------
  BastionHost:
      Type: AWS::EC2::Instance
      Properties:
        InstanceType: t3.micro
        KeyName: !Ref KeyPair
        ImageId: !Ref BastionAMI
        NetworkInterfaces:
          - AssociatePublicIpAddress: true
            DeviceIndex: 0
            SubnetId: !Ref PublicSubnetA
            GroupSet:
              - !Ref BastionSG
        Tags:
          - Key: Name
            Value: !Sub "${AWS::StackName}-BastionHost"
  WindowsServer:
    Type: AWS::EC2::Instance
    Properties:
      InstanceType: t3.large
      KeyName: !Ref KeyPair
      ImageId: !Ref WindowsAMI
      IamInstanceProfile: !Ref WindowsInstanceProfile
      BlockDeviceMappings:
        - DeviceName: /dev/sda1
          Ebs:
            VolumeType: gp3
            VolumeSize: 128
            Iops: 3000
            DeleteOnTermination: true
      NetworkInterfaces:
        - AssociatePublicIpAddress: false  # Windows ServerにはパブリックIPを付与しない
          DeviceIndex: 0
          SubnetId: !Ref PublicSubnetD
          GroupSet:
            - !Ref WindowsSG
      Tags:
        - Key: Name
          Value: !Sub "${AWS::StackName}-WindowsServer"

Outputs:
  BastionPublicIP:
    Description: Public IP of the bastion host (SSH接続先)
    Value: !GetAtt BastionHost.PublicIp

  WindowsPrivateIP:
    Description: Private IP of the Windows server (踏み台経由でRDP接続)
    Value: !GetAtt WindowsServer.PrivateIp

  IAMRoleForWindows:
    Description: IAM Role attached to Windows Server (S3アクセス用)
    Value: !Ref WindowsInstanceRole

```

キーペアからキー？出力
```bash
aws ec2 describe-key-pairs --filters Name=key-name,Values=useBastionNossm2-key --query KeyPairs[*].KeyPairId --output text
```
pemファイル作成
```bash
aws ssm get-parameter --name /ec2/keypair/<出力されたキー> --with-decryption --query Parameter.Value --output text > useBastionNossm2022.pem
```
.pemファイルは chmod 400 にする。（Windowsの場合はWSLのシステムディレクトリでやる）

踏み台にSSH
```bash
ssh -i /path/to/your/key.pem -L [ローカルポート]:[EC2インスタンスのプライベートIP]:[リモートポート] [踏み台サーバのユーザー名]@[踏み台サーバのIP]
```

- RDP接続用のEC2のWInパスはコンソールで.pem食わせて表示させる