Try this
script starts as X
script then does SSH to other system as Y using private key as follows...
Code:
echo this is running as X here
ssh -i identity Y@other <<EOF
echo this script part will run as Y on the other machine
EOF
echo this is back running as X here