Jef Practice: preserving needed environment variables when using sudo with assets

Disclaimer
For the rest of this discussion, I’m going to assume you’ve done your due diligence and have made the determination that the asset you want to use in a privileged manner meets your internal security requirements. The security implications of using assets with sudo are important, so I don’t want to give anyone the notion that you should make a common habit of using sudo for all your checks comnands. You’ll definitely want to evaluate for yourself when its appropriate to escalate privs.

The sudo environment gotcha
So an small technical issue came up in a troubleshooting conversation in the community slack and I thought I’d expand on it here.

Some check commands on linux requires enhanced permissions to run and its common to use sudo as a way to escalate the sensu user’s privileges in a targeted fashion. Using assets for check commands that will involve sudo can have a little gotcha depending on your default sudo configuration.

Sudo can configured to reset the environment or preseve a subset of the calling user’s environment.
This means that if you use sudo in a check command it may wipe out the PATH and LD_LIBRARY_PATH changes that the sensu-agent has done when setting up the asset configured to be used as part of the check… leading to errors associated with trying to run the command provided by the asset.

Not to worry, you can explicitly tell sudo you want to preserve additional environment variables a number of ways.

First try:
sudo -E command
this will preserve the running user’s environment.

If that doesn’t work try something like this:
sudo PATH=$PATH LD_LIBRARY_PATH=$LD_LIBRARY_PATH command
this will ensure the path variables used by assets are passed into the sudo environment.

I always find its good when setting up a new check command that uses assets to first create the check with a simple diagnostic command to ensure the paths are what i expect.

For example:

sensuctl check info --format yaml sudo_test
type: CheckConfig
api_version: core/v2
metadata:
  created_by: admin
  labels:
    sensu.io/managed_by: sensuctl
  name: sudo_test
  namespace: default
spec:
  check_hooks: null
  command: sudo -E echo "PATH:$PATH \nLD:$LD_LIBRARY_PATH \n"
  env_vars: null
  handlers: []
  high_flap_threshold: 0
  interval: 10
  low_flap_threshold: 0
  output_metric_format: ""
  output_metric_handlers: null
  proxy_entity_name: ""
  publish: true
  round_robin: false
  runtime_assets:
  - sensu/system-profile-linux
  secrets: null
  stdin: false
  subdue: null
  subscriptions:
  - test
  timeout: 0
  ttl: 0

event output should list both paths prepended with an obvious asset directory uder the configured sensu-agent cache directory.