Set Environment Variables with Puppet

可紊 提交于 2019-11-29 03:06:04

If you only need the variables available in the puppet run, whats wrong with :

Exec { environment => [ "foo=$bar" ] }

?

Simplest way to acomplish this is to put your env vars in /etc/environment, this ensures they are available to everything (or pretty much everything).

Something like this:

class example($somevar) {
    file { "/etc/environment":
        content => inline_template("SOMEVAR=${somevar}")
    }
}

Reason for having the class parameterised is so you can target it from hiera with automatic variable lookup (http://docs.puppetlabs.com/hiera/1/puppet.html#automatic-parameter-lookup) ... if you're sticking something in /etc/environment, it's usually best if you actually make it environment specific.

note: I've only tested this on ubuntu

The way I got around it is to also use /etc/profile.d:

$bar = 'bar'
file { "/etc/profile.d/my_test.sh":
  content => "export Foo=${bar}",
  mode    => 755
}

This ensures that everytime you login (ex ssh), the variable $MYVAR gets exported to your environment. After you apply through puppet and login (ex ssh localhost), echo $Foo would return bar

You could try the following, which sets the environment variable for this exec:

class foobar {
   exec { 'foobar' :
     command => "/bin/bash -c \"export Foo=${bar}\"",
   }
}

You can set an environment variable by defining it on a line in /etc/environment and you can ensure a line inside a file using file_line in puppet. Combine these two into the following solution:

file_line { "foo_env_var":
    ensure  => present,
    line    => "Foo=${bar}",
    path    => "/etc/environment",
}

Something like this would work while preserving existing contents of the /etc/environment file:

/code/environments/{environment}/manifests/environment/variable.pp:

define profile::environment::variable (
    $variable_name,
    $value,
    $ensure => present,
) {
    file_line { $variable_name:
        path   => '/etc/environment',
        ensure => $ensure,
        line   => "$variable_name=$value",
        match  => "$variable_name=",
    }
}

Usage (in the body of a node manifest):

profile::environment::variable { 'JAVA_HOME':
    variable_name  => 'JAVA_HOME',
    value => '/usr/lib/jvm/java-1.8.0',
}

I know this is an old question, but I was able to set the PS1 prompt value and add it to my .bashrc file like this:

$PS1 = '\[\e[0;31m\]\u\[\e[m\] \[\e[1;34m\]\w\[\e[m\] \$ '

and within a class:

exec {"vagrant-prompt":
  unless =>  "grep -F 'export PS1=\"${PS1}\"' ${HOME_DIR}/.bashrc",
  command => "echo 'export PS1=\"${PS1}\"' >> ${HOME_DIR}/.bashrc",
  user => "${APP_USER}",
}

The -F makes grep it interpret it as a fixed string. Otherwise it won't find it and keeps adding to the .bashrc file.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!