Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pass ENV VAR to exec.Command?

Tags:

go

I'm writing a go wrapper for a popular command line tool (ansible-playbook) and I need to pass a parameter through with the exec.Command call. The bash equivalent would be:

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

Previously I was just exporting MY_VAR using os.Setenv, but that causes problems for parallel executions of the playbook. So I want to pass the var in front of the command so that each call has it's own value for this var.

I'm not really sure how to do this with exec.Command since the first parameter to that function is "command". Any tips?

edit: I have tried using the Env field of the Cmd struct but that overrides all environment variables. I have a significant amount of configuration set and I would just like to override this one specific environment variable. Is this not possible??

like image 229
user18007 Avatar asked Dec 14 '16 01:12

user18007


People also ask

How do I pass an environment variable in Bash?

In order to set a permanent environment variable in Bash, you have to use the export command and add it either to your “. bashrc” file (if this variable is only for you) or to the /etc/environment file if you want all users to have this environment variable.

How do you pass an environment variable?

In the User variables section, select the environment variable you want to modify. Click Edit to open the Edit User Variable dialog box. Change the value of the variable and click OK. The variable is updated in the User variables section of the Environment Variables dialog box.

How do I reference an environment variable from the command line?

To list all the environment variables, use the command " env " (or " printenv "). You could also use " set " to list all the variables, including all local variables. To reference a variable, use $varname , with a prefix '$' (Windows uses %varname% ).

How do I set an environment variable in one command?

We can set variables for a single command using this syntax: VAR1=VALUE1 VAR2=VALUE2 ... Command ARG1 ARG2...


1 Answers

For those wondering for the solution:

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

Will preserve the existing environment and then write the one value that you want.

Thank goodness for godoc and open source!!

like image 181
user18007 Avatar answered Sep 30 '22 09:09

user18007