3

I need to generate ssh-keys(public/private pair) for a user say helen. This user is already in all my salt minions. How do I generate ssh keys for this user from my salt master?

For root user I generated the keys using this command and it worked fine:

salt '*application-server-*' cmd.run "ssh-keygen -q -N '' -f /root/.ssh/id_rsa"

I can issue the following command which can generate ssh-keys for helen; but the permissions and ownerships will be different; so need to issue commands again to correct permissions and ownerships:

salt '*application-server-*' cmd.run "ssh-keygen -q -N '' -f /home/helen/.ssh/id_rsa"

Is there any way in salt to run this command as user helen instead of root?

In general, is there a way in salt to run a command as a non root user?

Ajo Augustine
  • 1,252
  • 4
  • 16
  • 21

1 Answers1

4

Using the salt command

salt '*application-server-*' cmd.run \
    "ssh-keygen -q -N '' -f /home/helen/.ssh/id_rsa" \
    runas=helen

http://docs.saltstack.com/en/latest/ref/modules/all/salt.modules.cmdmod.html#salt.modules.cmdmod.run

Using a state

You can specify the user when using the cmd state by setting the runas to the user name to run the command as:

generate_ssh_key_helen:
  cmd.run:
    - name: ssh-keygen -q -N '' -f /home/helen/.ssh/id_rsa
    - runas: helen
    - unless: test -f /home/helen/.ssh/id_rsa

http://docs.saltstack.com/en/latest/ref/states/all/salt.states.cmd.html#salt.states.cmd.run

Roald Nefs
  • 426
  • 5
  • 13
Christophe Drevet
  • 1,962
  • 2
  • 17
  • 25
  • 1
    I look at the salt state of your answer. AFAIK this generates a new key every time this state gets called. Is there a way to create they key only if it does not exist yet? – guettli Jul 29 '16 at 12:21
  • You're absolutely right. You need to make sure this state is executed only once, by setting a specific grain, for example. You can set a grain with another state that depends on this one, then check if the grain exists in your sls file to enable or disable the state. – Christophe Drevet Aug 01 '16 at 19:02
  • In versions prior than 2016.3, the state parameter wasn't `runas` but `user`. – Christophe Drevet Oct 04 '16 at 06:39
  • You can also do: `- creates: /home/helen/.ssh/id_rsa` – OrangeDog Feb 26 '21 at 17:33