# ansible / provisioning / variables
Provision Users dynamically with variables
A clean example of making playbooks reusable. Instead of hardcoding names and paths, this playbook uses Jinja2 variables to define the user and target directory, making it highly adaptable for future runs.
Why variables matter
Hardcoding values directly into tasks creates rigid, fragile playbooks. By lifting the data into a vars block, the logic becomes a template. You can now use this exact same file to provision 50 different users just by overriding the variables.
Write Once, Run Anywhere
Need to create a different user? You don't have to rewrite the tasks. Just update the vars dictionary or pass them at runtime using the CLI.
Eliminate Typos
Because the directory path, owner, and group all reference the exact same {{ username }} variable, it is impossible for them to mismatch.
The full task list
--- - name: create user with variable hosts: localhost become: yes vars: username: shannn dirname: avalothan tasks: - name: user with variable user: name: "{{ username }}" state: present create_home: yes - name: create directory file: path: "/home/{{ username }}/{{ dirname }}" state: directory owner: "{{ username }}" group: "{{ username }}" mode: '0755'
Run order
- define
Declares the variables at the play level, making them available to all subsequent tasks.
vars - identity
Creates the system user, relying on Jinja2 templating to inject the name.
user - scaffold
Constructs the full directory path dynamically by concatenating variables and static text.
file
Check the templated output
To ensure the variables evaluated correctly, you can check both the user's system record and the directory ownership properties.
Lessons from running this in production
Notice how "{{ username }}" has quotes around it? If a YAML value starts with a variable curly brace, you must wrap it in quotes, or Ansible will throw a syntax error thinking it's a dictionary.
You don't have to edit the file to change the user! Run the playbook with -e "username=newuser dirname=newdir" to override these variables at execution time.
The variable username is safely reused three times in the file module (path, owner, group). This completely prevents copy-paste errors.