Allow a user to restart a service

I am trying to restart a service without being root. Here is the code snippet where the command being used

template {
  source      = "{{vault_template_dir}}/agent.crt.tpl"
  destination = "{{vault_tls_dir}}/agent.crt"
  command     = "/usr/bin/systemctl restart vault.service"
}

after researching and reading similar issues, I've tried to give a limited sudo command for the group I an using (user=vault, group=vault) by editing the /etc/sudoers file and adding the following line:

%vault ALL=(root) NOPASSWD: /usr/bin/systemctl restart vault.service

However, I am still getting an error when I try and run the command. error log file:

Apr  4 23:27:41 xxxxxx vault[133973]: Failed to restart vault.service: Interactive authentication required.

vault.service

[Unit]
After=network.service hostname.service consul-init.service consul.service
Description="Hashicorp Vault - A tool for managing secrets"
Documentation=https://www.vaultproject.io/docs/
StartLimitInterval=200
StartLimitBurst=5

[Service]
User=vault
Group=vault
ExecStart=/usr/bin/vault server -config="{{vault_server_config_file}}"
ExecReload=/usr/bin/kill -HUP $MAINIP
CapabilityBoundingSet=CAP_SYSLOG CAP_IPC_LOCK
LimitNOFILE=65536
LimitMEMLOCK=infinity
Restart=always
RestartSec=30

[Install]
WantedBy=multi-user.target

can someone please help me with this issue?


Solution 1:

You need to use sudo to execute command, so your template needs to look like this:

template {
  source      = "{{vault_template_dir}}/agent.crt.tpl"
  destination = "{{vault_tls_dir}}/agent.crt"
  command     = "sudo /usr/bin/systemctl restart vault.service"
}

For future, make sure to edit sudoers file with visudo program. If you directly edit /etc/sudoers, a mistake can lock you out of the system.