How you set an environment variable in a Chef recipe depends on who needs to see it. It might be the running chef-client process, a single execute command, every login shell, a systemd service, or Windows system-wide. This guide explains when to use each method shown above and when its timing matters. It also gives tested replacements for the outdated magic_shell and Chef::Util::FileEdit examples.
Method #1
If you need an env var set strictly within the Chef process, you can use ENV['foo'] = 'bar' since it's a ruby process.
Method #2
If you need to set one for an execute provider, Chef exposes an environment hash:
execute 'Bootstrap the database' do
cwd "#{app_dir}/current"
command "#{env_cmd} rake db:drop db:create db:schema:load RAILS_ENV=#{rails_env}"
environment 'HOME' => "/home/#{app_user}"
user app_user
action :run
not_if %[psql -U postgres -c "\\l" | grep #{db_name}]
endCode language: PHP (php)
Choose the method by scope and persistence
Chef recipes are Ruby, so an environment variable can live in several places. Before you write any code, answer two questions. Which processes must see the variable? Must it still be there after the Chef run ends? The table maps the methods above (including the extra ones from the embedded gist) to those answers.
| Method | Who sees the variable | Persists after the run? |
|---|---|---|
ENV['FOO'] = 'bar' | The chef-client process and every child process it starts later in the run | No |
environment property on execute, bash, script | Only that one command | No |
File in /etc/profile.d/ | New login shells (SSH sessions, bash -l) | Yes |
/etc/environment | New PAM sessions (logins, su -, many desktop sessions) | Yes |
systemd Environment= | Only that service | Yes |
windows_env | New Windows processes (machine or user scope) | Yes |
Note: No method changes the environment of a shell that is already open. You must log in again, start a new shell, or restart the service before the new value shows up.
Setting variables for the Chef run with ENV
Method #1 assigns to Ruby's ENV hash. Every child process that chef-client starts after the assignment inherits the variable. That covers execute commands, guards and package managers. The catch is timing. Chef compiles all recipes first and converges resources afterwards. A bare ENV[...] = ... at the top level of a recipe runs during compile, before any resource has run. That is usually fine. If the value depends on something a resource creates, set it at converge time inside a ruby_block instead.
# Compile time: set as soon as the recipe file is loaded
ENV['APP_ENV'] = 'production'
# Converge time: set when this resource is reached in the run
ruby_block 'export JAVA_HOME for the rest of the run' do
block do
ENV['JAVA_HOME'] = ::File.realpath('/usr/lib/jvm/default-java')
end
end
execute 'show inherited variables' do
command 'env | grep -E "APP_ENV|JAVA_HOME" > /tmp/chef-env-check.txt'
endCode language: PHP (php)
ENV changes are global to the process and last until chef-client exits. They can leak into unrelated resources, so use them only for values the whole run needs, such as proxy settings.
Passing variables to execute, bash and script resources
For most cases, the environment property (alias env) from Method #2 is the cleanest option. It takes a Ruby hash and applies only to that command. The example below is a self-contained version of the database bootstrap above. The variables are defined, and RAILS_ENV is passed through the environment instead of as a rake argument.
app_user = 'deploy'
app_dir = '/srv/myapp'
db_name = 'myapp_production'
execute 'Bootstrap the database' do
cwd "#{app_dir}/current"
command 'bundle exec rake db:create db:schema:load'
user app_user
environment(
'HOME' => "/home/#{app_user}",
'RAILS_ENV' => 'production',
'PATH' => "/usr/local/bin:#{ENV['PATH']}"
)
not_if "psql -U postgres -Atc \"SELECT 1 FROM pg_database WHERE datname='#{db_name}'\" | grep -q 1"
action :run
endCode language: PHP (php)
- Setting
userdoes not resetHOME. Without theenvironmententry, tools such as Bundler or Git can try to write into root's home directory and fail with permission errors. - If you set
PATHin the hash, it replaces the inherited value completely. AppendENV['PATH']as shown so that system binaries can still be found. - The
db:dropfrom the original was removed. Even with the guard, a destructive drop does not belong in a bootstrap step that runs repeatedly. - A string guard can take its own options, for example
not_if 'some-check', environment: { 'PGPASSWORD' => pw }, user: 'postgres'. Pass them explicitly when the guard needs the same variables as the command.
The bash, script, powershell_script and batch resources accept the same environment property.
Persistent variables on Linux: profile.d, /etc/environment and systemd
Method #3 suggests writing to /etc/profile.d. You can do that with Chef's built-in file resource. The resource is idempotent and reports changes correctly, and it replaces the community magic_shell cookbook from Method #4, which is old and no longer necessary.
file '/etc/profile.d/myapp.sh' do
content <<~EOS
export APP_ENV=production
export JAVA_HOME=/usr/lib/jvm/java-17-openjdk-amd64
EOS
owner 'root'
group 'root'
mode '0644'
endCode language: JavaScript (javascript)
Only login shells source /etc/profile.d. Cron jobs, Ruby system() calls, the Chef run itself and systemd services do not read it, which is the gotcha the gist mentions. For a long-running service, set the variable in the service's unit file instead.
systemd_unit 'myapp.service' do
content(
Unit: { Description: 'My application', After: 'network.target' },
Service: {
User: 'deploy',
Environment: 'APP_ENV=production RAILS_ENV=production',
ExecStart: '/srv/myapp/current/bin/start'
},
Install: { WantedBy: 'multi-user.target' }
)
action [:create, :enable]
endCode language: JavaScript (javascript)
Note: /etc/environment is not a shell script. pam_env reads it as plain NAME=value lines, so export, $VAR expansion and command substitution do not work there.
Corrected /etc/environment example
Method #5 has several problems. It runs Chef::Util::FileEdit directly in the recipe body, so the file is edited at compile time and Chef never reports the change. It calls write_file on every pass through the loop. insert_line_if_no_match never updates a variable that already exists with an old value. The Java 7 path is also out of date. The version below runs at converge time, updates or inserts each line, writes the file once, and skips the work when the file is already correct.
env_vars = {
'JAVA_HOME' => '/usr/lib/jvm/java-17-openjdk-amd64'
}
ruby_block 'manage variables in /etc/environment' do
block do
fe = Chef::Util::FileEdit.new('/etc/environment')
env_vars.each do |name, val|
line = "#{name}=\"#{val}\""
fe.search_file_replace_line(/^#{name}=/, line)
fe.insert_line_if_no_match(/^#{name}=/, line)
end
fe.write_file
end
not_if do
current = ::File.read('/etc/environment')
env_vars.all? { |n, v| current.include?("#{n}=\"#{v}\"") }
end
endCode language: PHP (php)
The original also set LD_LIBRARY_PATH to the JDK library directory. The Java launcher finds its own libraries, so this is not needed. Setting it system-wide can also make unrelated programs load the wrong shared libraries, so it has been left out.
Setting variables on Windows with windows_env
windows_env is built into Chef Infra Client. By default it writes a machine-level variable. Set the user property to target a specific account, and use delim to add an entry to a list-style variable such as PATH without overwriting it.
windows_env 'APP_ENV' do
value 'production'
action :create
end
windows_env 'PATH' do
value 'C:\\tools\\bin'
delim ';'
action :modify
endCode language: JavaScript (javascript)
Note: The gist uses CHEF_LICENSE as its example, but a recipe cannot accept the license for the run that is executing it. Accept the license before the first run with chef-client --chef-license accept or by setting CHEF_LICENSE=accept in the bootstrap environment.
Verifying the result and common errors
# Run a single recipe locally
sudo chef-client -z -o 'recipe[myapp::env]'
# Check a new login shell picks up profile.d
bash -lc 'echo $APP_ENV'
# Check a systemd service
systemctl show myapp.service -p Environment
# Windows (PowerShell): machine-level value
[Environment]::GetEnvironmentVariable('APP_ENV', 'Machine')Code language: PHP (php)
| Symptom | Cause | Fix |
|---|---|---|
| Variable is empty in your current SSH session | Existing shells never reload their environment | Log out and back in, or start bash -l |
| Service does not see the variable from profile.d | systemd does not source shell profiles | Use Environment= in the unit and restart the service |
execute with user fails writing to /root | HOME is still root's home directory | Set HOME in the environment hash |
Command not found after setting environment | PATH in the hash replaced the inherited value | Append ENV['PATH'] to your value |
| ENV value is missing or stale in a later resource | The variable was set at compile time from data that only exists at converge time | Move the assignment into a ruby_block |
Frequently asked questions
Does ENV['VAR'] = 'value' in a Chef recipe persist after chef-client finishes?
No. It changes only the environment of the running chef-client process and its child processes. To make a variable persistent, write it to /etc/profile.d, /etc/environment, a systemd unit or, on Windows, use windows_env.
What is the difference between environment and env on the execute resource?
There is no difference. env is an alias for environment, and both take a hash of variable names and values that applies only to that command.
Why does my systemd service not see a variable I added to /etc/profile.d?
Only login shells read /etc/profile.d. Services started by systemd do not, so set the variable with Environment= or EnvironmentFile= in the unit file and restart the service.
How do I add a directory to PATH on Windows with Chef?
Use the windows_env resource with key_name PATH, the directory as value, delim ';' and action :modify. This appends the entry instead of replacing the whole PATH.
Do I still need the magic_shell cookbook to set environment variables?
No. A built-in file or template resource that writes a script to /etc/profile.d does the same job without an external cookbook dependency.
Related tutorials
- More Chef tutorials
- What is Chef and use cases of Chef?
- Chef Tutorials: knife command line reference
- Top 50 Chef interview questions and answers
I’m Rajesh Kumar, a DevOps, SRE, DevSecOps, Cloud, and Platform Engineering expert passionate about sharing practical knowledge, real-world experiences, and industry best practices. I have worked at Cotocus and regularly write about technology, travel, investing, health, product reviews, and digital marketing through my various platforms.
I publish technical articles at DevOps School, travel stories at Holiday Landmark, stock market insights at Stocks Mantra, health and fitness guidance at My Medic Plus, product reviews at TrueReviewNow, and SEO and digital marketing strategies at Wizbrand.
Find Trusted Cardiac Hospitals
Compare heart hospitals by city and services โ all in one place.
Explore Hospitals