How to modify the linux user's UID before the Packer build?

I’m trying the build the new AMI along with swapping the amazon-linux user’s UID before the packer build.

Scenario:

  • Should have two users inside the AMI ec2-user and custom-user
  • Should run the packer build as ec2-user
  • But before all the above steps, I need to modify the UID of the user ec2-user from 1000 to 1001 and custom-user to 1000

What I tried so far

  • Ran the below cloud-init script to update the UID
#cloud-config

runcmd:
  - [ sh, -c, "pkill -u 1000 && usermod -u 1001 ec2-user && groupmod -g 1001 ec2-user" ]
  - [ sh, -c, "chown -R 1001:1001 /home/ec2-user" ]
  - [ sh, -c, "usermod -u 1000 custom-user && groupmod -g 1000 custom-user" ]
  - [ sh, -c, "chown -R 1000:1000 /home/custom-user" ]
 
users:
  - default
  - name: custom-user
    gecos: Custom-User info
    uid: 1000

The above script modifies the UID. But the problem is it could not connect to the temporary instance created via SSH

2023/02/13 18:57:58 packer-builder-amazon-ebs plugin: Using host value: 10.x.x.x
2023/02/13 18:57:58 packer-builder-amazon-ebs plugin: [INFO] Attempting SSH connection to 10.x.x.x:22...
2023/02/13 18:57:58 packer-builder-amazon-ebs plugin: [DEBUG] reconnecting to TCP connection for SSH
2023/02/13 18:57:58 packer-builder-amazon-ebs plugin: [DEBUG] handshaking with SSH
2023/02/13 18:57:59 packer-builder-amazon-ebs plugin: [DEBUG] SSH handshake err: ssh: handshake failed: ssh: unable to authenticate, attempted methods [none publickey], no supported methods remain
2023/02/13 18:57:59 packer-builder-amazon-ebs plugin: [DEBUG] Detected authentication error. Increasing handshake attempts.

==> amazon-ebs: Error waiting for SSH: Packer experienced an authentication error when trying to connect via SSH. This can happen if your username/password are wrong. You may want to double-check your credentials as part of your debugging process. original error: ssh: handshake failed: ssh: unable to authenticate, attempted methods [none publickey], no supported methods remain

Is there a way we can achieve this scenario?