Pass ENV VAR to exec.Command?

I am writing a wrapper for a popular command line tool (ansible-playbook) and I need to pass a parameter by calling exec.Command. Equivalent to bash:

MY_VAR=some_value ansible-playbook -i custom-inventory playbook.yml 

I used to just export MY_VAR using os.Setenv, but this creates problems for parallel executions of the playbook. Therefore, I want to pass var before the command so that each call has its own value for this var.

I am not sure how to do this with exec.Command, since the first parameter to this function is "command". Any tips?

edit: I tried to use the Env field of the Cmd structure, but this overrides all environment variables. I have a large set of settings, and I just would like to override this particular environment variable. Is it impossible?

+5
source share
1 answer

For those who are wondering about a solution:

  cmd := exec.Command("ansible-playbook", args...) cmd.Env = os.Environ() cmd.Env = append(cmd.Env, "MY_VAR=some_value") 

Saves the existing environment and then writes the single value you want.

Thank you for Godoc and open source!

+8
source

Source: https://habr.com/ru/post/1261232/


All Articles