재형이의 성장통 일지
  • EC2 윈도우 서버 SSH 설정 배포 자동화하기 (feat.AWS SSM)
    2024년 10월 15일 17시 15분 06초에 업로드 된 글입니다.
    작성자: 재형이
    반응형
    • 기본적으로 EC2 윈도우 서버에는 ssh 서버가 설치되어 있지 않기 때문에 설치를 해줘야 한다
    • 추가로 키파일도 설정을 해주어야 하는데 ec2 생성 시 키페어를 설정해주었다면 ec2 imdsv2를 통해서 키파일 정보를 가져올 수 있다
    • 정리하자면 openSSH 설치 → 키파일 가져오기 → 키파일 설정 을 해주어야 하는데 다수의 EC2가 있을 경우 하나씩 들어가서 설정해주기가 까다롭기 때문에 AWS Systems Manager Run Command를 사용하려고 한다

    AWS Systems Manager Run Command

    • 명령 실행 탭에 들어가서 RunPowershellScript를 선택해준다

     
    • 하단의 명령 파라미터에 다음 스크립트를 넣어주고 실행해주면 자동으로 실행이된다
    # openSSH 설치
    $ErrorActionPreference = 'Stop'
    
    Write-Host 'Installing and starting sshd'
    Add-WindowsCapability -Online -Name OpenSSH.Server~~~~0.0.1.0
    Set-Service -Name sshd -StartupType Automatic
    Start-Service sshd
    
    Write-Host 'Installing and starting ssh-agent'
    Add-WindowsCapability -Online -Name OpenSSH.Client~~~~0.0.1.0
    Set-Service -Name ssh-agent -StartupType Automatic
    Start-Service ssh-agent
    
    Write-Host 'Set PowerShell as the default SSH shell'
    New-ItemProperty -Path "HKLM:\SOFTWARE\OpenSSH" -Name DefaultShell -Value (Get-Command powershell.exe).Path -PropertyType String -Force
    
    # 키파일 가져오기 및 설정
    # Userdata script to enable SSH access as user Administrator via SSH keypair.
    # This assumes that
    # 1. the SSH service (sshd) has already been installed, configured, and started during AMI creation;
    # 2. a valid SSH key is selected when the EC2 instance is being launched; and
    # 3. IMDSv2 is selected when launching the EC2 instance.
    
    # Save the private key from instance metadata.
    $ImdsToken = (Invoke-WebRequest -Uri 'http://169.254.169.254/latest/api/token' -Method 'PUT' -Headers @{'X-aws-ec2-metadata-token-ttl-seconds' = 2160} -UseBasicParsing).Content
    $ImdsHeaders = @{'X-aws-ec2-metadata-token' = $ImdsToken}
    $AuthorizedKey = (Invoke-WebRequest -Uri 'http://169.254.169.254/latest/meta-data/public-keys/0/openssh-key' -Headers $ImdsHeaders -UseBasicParsing).Content
    $AuthorizedKeysPath = 'C:\ProgramData\ssh\administrators_authorized_keys'
    New-Item -Path $AuthorizedKeysPath -ItemType File -Value $AuthorizedKey -Force
    
    # Set appropriate permissions on administrators_authorized_keys by copying them from an existing key.
    Get-ACL C:\ProgramData\ssh\ssh_host_dsa_key | Set-ACL $AuthorizedKeysPath
    
    # Ensure the SSH agent pulls in the new key.
    Set-Service -Name ssh-agent -StartupType "Automatic"
    Restart-Service -Name ssh-agent
    • 명령 실행이 끝나고 나면 ssh로 접속이 가능해진다
    ssh -i ~/.ssh/my-keypair Administrator@ec2_IP
    • EC2 User data에 해당 스크립트를 넣으려면 하단 이미지처럼 <powershell></powershell> 태그를 넣어주어야한다
    • <persist>true</persist> 태그는 true로 하게 될 경우 ec2를 재부팅하거나 중지했다가 시작할 때도 해당 스크립트를 실행하게 해준다

     

    반응형
    댓글