简体   繁体   English

使用CloudFormation模板的基于IAM的SSH到EC2实例

[英]IAM based ssh to EC2 instance using CloudFormation template

I am using an AWS CloudFormation template for IAM role-based access to an EC2 instance. 我正在使用AWS CloudFormation模板对IAM实例进行基于IAM角色的访问。

I getting permission denied error while running the template, and I am not able to access the EC2 machine with a username without a pem file. 我在运行模板时遇到permission denied error ,并且我无法使用没有pem文件的用户名访问EC2计算机。

  Instance:
    Type: 'AWS::EC2::Instance'
    Metadata:
      'AWS::CloudFormation::Init':
        config:
          files:
            /opt/authorized_keys_command.sh:
              content: >
                #!/bin/bash -e

                if [ -z "$1" ]; then
                  exit 1
                fi
                SaveUserName="$1"
                SaveUserName=${SaveUserName//"+"/".plus."}
                SaveUserName=${SaveUserName//"="/".equal."}
                SaveUserName=${SaveUserName//","/".comma."}
                SaveUserName=${SaveUserName//"@"/".at."}
                aws iam list-ssh-public-keys --user-name "$SaveUserName" --query
                "SSHPublicKeys[?Status == 'Active'].[SSHPublicKeyId]" --output
                text | while read KeyId; do
                  aws iam get-ssh-public-key --user-name "$SaveUserName" --ssh-public-key-id "$KeyId" --encoding SSH --query "SSHPublicKey.SSHPublicKeyBody" --output text
                done
              mode: '000755'
              owner: root
              group: root
            /opt/import_users.sh:
              content: >
                #!/bin/bash
                aws iam list-users --query "Users[].[UserName]" --output text |
                while read User; do
                  SaveUserName="$User"
                  SaveUserName=${SaveUserName//"+"/".plus."}
                  SaveUserName=${SaveUserName//"="/".equal."}
                  SaveUserName=${SaveUserName//","/".comma."}
                  SaveUserName=${SaveUserName//"@"/".at."}
                  if id -u "$SaveUserName" >/dev/null 2>&1; then
                    echo "$SaveUserName exists"
                  else
                    #sudo will read each file in /etc/sudoers.d, skipping file names that end in ?~? or contain a ?.? character to avoid causing problems with package manager or editor temporary/backup files.
                    SaveUserFileName=$(echo "$SaveUserName" | tr "." " ")
                    /usr/sbin/adduser "$SaveUserName"
                    echo "$SaveUserName ALL=(ALL) NOPASSWD:ALL" > "/etc/sudoers.d/$SaveUserFileName"
                  fi
                done
              mode: '000755'     owner: root      group: root
            /etc/cron.d/import_users:
              content: |
                */10 * * * * root /opt/import_users.sh
              mode: '000644'    owner: root
              group: root
            /etc/cfn/cfn-hup.conf:
              content: !Sub |
                [main]
                stack=${AWS::StackId}
                region=${AWS::Region}
                interval=1
              mode: '000400'  owner: root        group: root
            /etc/cfn/hooks.d/cfn-auto-reloader.conf:
              content: !Sub >
                [cfn-auto-reloader-hook]
                triggers=post.update
                path=Resources.Instance.Metadata.AWS::CloudFormation::Init
                action=/opt/aws/bin/cfn-init --verbose
                --stack=${AWS::StackName}  --region=${AWS::Region} 
                --resource=Instance
                runas=root
          commands:
            a_configure_sshd_command:
              command: >-
                sed -i 's:#AuthorizedKeysCommand none:AuthorizedKeysCommand
                /opt/authorized_keys_command.sh:g' /etc/ssh/sshd_config
            b_configure_sshd_commanduser:
              command: >-
                sed -i 's:#AuthorizedKeysCommandUser
                nobody:AuthorizedKeysCommandUser nobody:g' /etc/ssh/sshd_config
            c_import_users:
              command: ./import_users.sh
              cwd: /opt
          services:
            sysvinit:
              cfn-hup:
                enabled: true
                ensureRunning: true
                files:
                  - /etc/cfn/cfn-hup.conf
                  - /etc/cfn/hooks.d/cfn-auto-reloader.conf
              sshd:
                enabled: true
                ensureRunning: true
                commands:
                  - a_configure_sshd_command
                  - b_configure_sshd_commanduser
      'AWS::CloudFormation::Designer':
        id: 85ddeee0-0623-4f50-8872-1872897c812f
    Properties:
      ImageId: !FindInMap 
        - RegionMap
        - !Ref 'AWS::Region'
        - AMI
      IamInstanceProfile: !Ref InstanceProfile
      InstanceType: t2.micro      
      UserData:
        'Fn::Base64': !Sub >
          #!/bin/bash -x
          /opt/aws/bin/cfn-init --verbose --stack=${AWS::StackName}
          --region=${AWS::Region} --resource=Instance
          /opt/aws/bin/cfn-signal --exit-code=$? --stack=${AWS::StackName}
          --region=${AWS::Region}  --resource=Instance

This User Data script will configure a Linux instance to use password authentication. 该用户数据脚本将配置Linux实例以使用密码身份验证。

While the password here is hard-coded, you could obtain it in other ways and set it to the appropriate value. 虽然此处的密码是硬编码的,但您可以通过其他方式获得密码并将其设置为适当的值。

#!
echo 'secret-password' | passwd ec2-user --stdin
sed -i 's|[#]*PasswordAuthentication no|PasswordAuthentication yes|g' /etc/ssh/sshd_config
systemctl restart sshd.service

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM