Salt Grains: Core Grains, Custom Grains, Static Grains and Dynamic Python Grains

SaltStack 24 min min read Updated: Nov 17, 2026 Intermediate
Salt Grains: Core Grains, Custom Grains, Static Grains and Dynamic Python Grains
Intermediate Topic 1 of 3

What Are Grains?

Grains are facts about a minion: operating system, CPU, memory, IP addresses, virtualisation, and more. The minion collects them when it starts and keeps them. You use grains to target minions and to make states adapt (for example, 'if Debian, install apache2').

bash salt 'web1' grains.items # all grains salt 'web1' grains.ls # only the names of grains salt 'web1' grains.item os osrelease # a few grains salt 'web1' grains.get os_family # one value salt 'web1' grains.get ip4_interfaces:eth0 # nested value with colons salt 'web1' grains.get roles # a custom grain salt-call --local grains.items | less # on the minion itself

Core Grains You Will Use

GrainExample
id, host, fqdn, domainweb1, web1.example.com
os, os_family, osrelease, osmajorrelease, oscodenameUbuntu, Debian, 24.04, 24, noble
kernel, kernelrelease, cpuarchLinux, 6.8.0, x86_64
num_cpus, cpu_model, mem_total4, Intel..., 7954 (MB)
ipv4, ipv6, ip4_interfaces, fqdn_ip4, hwaddr_interfacesLists and dictionaries of addresses
virtual, virtual_subtypekvm, physical, container
init, pythonversion, saltversionsystemd, [3, 11, ...], 3008.2
selinux, shell, pathSettings
master, server_id, productname, biosversionHardware and Salt information
osfingerUbuntu-24.04, a unique OS string, great for matching
ec2, gce, azure (when present)Cloud metadata grains

Targeting with Grains

bash salt -G 'os:Ubuntu' test.ping salt -G 'kernel:Linux' cmd.run 'uname -r' salt -G 'virtual:kvm' test.ping salt -C 'G@os_family:RedHat and G@osmajorrelease:9' pkg.upgrade

Custom Grains: Three Ways

MethodWhereGood for
Static, in the minion config/etc/salt/minion.d/grains.confRoles and labels set by an admin
Static, in the grains file/etc/salt/grainsValues set with grains.setval
Dynamic, in Python_grains/ folder on the masterFacts you must compute (installed app version, rack location)

1. Static Grains in the Minion Config

yaml # /etc/salt/minion.d/grains.conf grains: roles: - webserver - monitoring env: production datacenter: mumbai owner: payments-team
bash sudo systemctl restart salt-minion # grains are read at start # or refresh without a restart: salt 'web1' saltutil.refresh_grains salt 'web1' grains.get roles

2. grains.setval / grains.append (The /etc/salt/grains File)

bash salt 'web1' grains.setval env production salt 'web1' grains.setval datacenter mumbai salt 'web1' grains.append roles webserver # add to a list grain salt 'web1' grains.remove roles webserver # remove a value from a list salt 'web1' grains.delkey datacenter # remove a key (value becomes None, use destructive=True to delete) cat /etc/salt/grains
Where is the value saved? grains.setval writes to /etc/salt/grains on the minion, and the value survives restarts. Values written in the minion config are re-created from config at each start. Use one place per grain, to avoid confusion.

Grains from a State

yaml set_role_grain: grains.present: - name: roles - value: - webserver - force: True env_grain: grains.present: - name: env - value: production remove_old_grain: grains.absent: - name: oldkey - destructive: True

3. Dynamic Python Grains

Put a Python file in /srv/salt/_grains/ on the master. Each function that returns a dictionary adds grains. Sync them to minions with saltutil.sync_grains (also done during state.apply and saltutil.sync_all).

python # /srv/salt/_grains/app_info.py import os import socket def app_version(): """Return the version of the installed app, if any.""" grains = {} path = '/opt/myapp/VERSION' if os.path.exists(path): with open(path) as f: grains['app_version'] = f.read().strip() return grains def rack(): """Derive the rack from the hostname, for example web-r12-03 gives r12.""" name = socket.gethostname() parts = name.split('-') return {'rack': parts[1]} if len(parts) > 2 else {}
bash salt '*' saltutil.sync_grains salt '*' saltutil.refresh_grains # recompute grains now salt '*' grains.get app_version salt -G 'app_version:1.4.0' test.ping
Keep Python grains fast: They run at every minion start and every refresh. Avoid slow network calls and big file scans. Return an empty dictionary when something is unavailable instead of raising an error.

Using Grains in States

yaml {% if 'webserver' in salt['grains.get']('roles', []) %} include: - nginx {% endif %} /etc/app/env.conf: file.managed: - contents: | environment={{ salt['grains.get']('env', 'dev') }} datacenter={{ salt['grains.get']('datacenter', 'unknown') }} cpus={{ grains['num_cpus'] }}

Grains in the Top File: Role Assignment

yaml base: 'roles:webserver': - match: grain - nginx - app 'roles:database': - match: grain - postgresql

A common design: a machine gets its role grain at build time (cloud-init, Terraform or a bootstrap script). The top file then maps roles to states. No hostnames in the top file.

Grains vs Pillar: Which One?

GrainsPillar
Defined onThe minionThe master
Who controls the valueThe minion (or the machine's admin)The master admin
Trust levelLower. A compromised minion can change its own grainsHigher. Minions cannot change pillar
Good forFacts, roles for convenience, targetingSecrets, settings, per-environment data
Visible to other minionsMaster has them cachedOnly the minion it was assigned to
Do not use grains for security decisions: If a minion can set its own roles grain to database, it could ask for database secrets. Use grains for convenience and pillar (assigned on the master) for anything sensitive. A safer way is to assign pillar by minion id.

Grains Cache and Refresh

ActionCommand
Recompute grains nowsalt '*' saltutil.refresh_grains
Sync custom grain filessalt '*' saltutil.sync_grains
Sync all custom modulessalt '*' saltutil.sync_all
Grains cached on the mastersalt-run cache.grains tgt='*'
Slow grainsDisable some in the minion config: enable_fqdns_grains: False, enable_gpu_grains: False
Grain file/etc/salt/grains and /var/cache/salt/minion/

Practice Tasks

  1. Set roles: [web] and env: dev using the minion config, restart, and read them with grains.get
  2. Use grains.setval to set datacenter and check /etc/salt/grains
  3. Write a Python grain that reports the contents of /etc/app_version, sync it and target with -G
  4. Create a role-based top file with roles:webserver and test with state.show_top
  5. Explain why a grain is a poor place for a database password

Conclusion

Grains are facts about minions. Use core grains for OS and hardware logic, static grains for roles and labels, and Python grains for computed facts. Use grains for targeting and convenience, but never for secrets or security decisions.

Quick Summary: grains.items/get; static in minion.d or grains.setval; _grains python + sync_grains; roles via top.sls match grain; not for security.

Get Newsletter

Subscibe to our newsletter and we will notify you about the newest updates on Edugators