0
votes

I am using an AWS CloudFormation template for IAM role-based access to an EC2 instance.

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.

  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
1
That's a lot of code you're listing, so people probably aren't doing to spend the time to figure out what it is doing. Can you clarify what you are actually wanting to do, and what problem you are experiencing? For example, are you wanting to configure the instance so that people can SSH into the instance by using a password instead of a Keypair?John Rotenstein
@JohnRotenstein - it appears to be rebuilding the .ssh/authorized_keys file on a regular basis by reading the public keys used with CodeCommit.kdgregory
@piyushraj - most people do this by storing the authorized_keys file on S3. Alternatively, if you want regular updates, use Systems Manager to push out changes. If you still want to be clever, and generate it by reading the users' keys, then I recommend writing (and fully debugging!) a single script, and then retrieving that script from S3 when the system starts. Right now you're conflating the tasks of system initialization and runtime configuration, and doing it in a very convoluted way.kdgregory
@JohnRotenstein yes all iam trying is to SSH into the instance by using a password instead of a Keypair and using cloud formation once ec2 is ready i am not able to access it . getting no supported authentication methods available (server sent: publickey)piyush raj

1 Answers

1
votes

This User Data script will configure a Linux instance to use password authentication.

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