'Error: 'you must have a tty to run sudo' while using sshpass

I have gitlab CI job which had a script execution like below:

  stage: permissions
  script: 
    sshpass -p "${PASSWORD}" ssh ${USER}@${HOST} sudo chown -cv user_a:user_a ${directory}/test.txt

The above gives me following error:

sudo: sorry, you must have a tty to run sudo

If i add -t with ssh i get:

Pseudo-terminal will not be allocated because stdin is not a terminal.
sudo: sorry, you must have a tty to run sudo

If i add -tt with ssh, the job keeps waiting for me to enter the password.

My requirement is to execute a remote command using ssh and text password i.e. sshpass, is there a way i can achieve this without change any sudoers permissions over the server?



Solution 1:[1]

Use somethinc like:

sshpass -p "${PASSWORD}" ssh ${USER}@${HOST} sh -c "echo ${PASSWORD} | sudo chown -cv user_a:user_a ${directory}/test.txt"

Example for write password from not tty to sudo:

echo ${PASSWORD} | sudo -S command

p.s. For configure servers use Ansible, he handles such tasks very easily.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 rollsover