So far you have typed -i inventory/ in every command and let Ansible use its defaults for everything else: 5 forks, Python discovery with warnings, a standard SSH connection… Ansible has hundreds of settings, and the professional way to pin them down is an ansible.cfg file inside the project itself, versioned in git alongside the inventory. That way, anyone who clones aurora-infra will work with exactly the same configuration. In this lesson you will learn where Ansible looks for its configuration, create a complete, commented ansible.cfg for Aurora Store, get to know the ANSIBLE_* environment variables and use ansible-config to generate, inspect and debug the configuration. From this lesson onward you will no longer need -i.
Contents
- What
ansible.cfgcontrols - Where Ansible looks for its configuration
- The world-writable directory warning
- Aurora Store's
ansible.cfg - Revisiting the decision about connection data
ANSIBLE_*environment variables and order of precedence- The
ansible-configtool - Saving your work in git
- What
ansible.cfg controls
ansible.cfg controlsansible.cfg defines Ansible's behavior on the control node: which inventory to use by default, which user to connect as, how many hosts to process in parallel, how to display output, how to escalate privileges, how to use SSH… It doesn't describe your infrastructure (that's the inventory's job) or what you want to configure on it (that will be the playbooks' job).
It's a file in INI format, divided into sections:
| Section | What it groups |
|---|---|
[defaults] |
General settings: inventory, user, forks, output, interpreter… |
[privilege_escalation] |
How to become another user (usually root with sudo) |
[ssh_connection] |
Options for the SSH connection plugin |
[persistent_connection], [colors], [galaxy], [inventory]… |
More specific settings |
- Where Ansible looks for its configuration
Ansible looks for a configuration file in this order and uses the first one it finds, ignoring the rest:
| Order | Location | Typical use |
|---|---|---|
| 1 | ANSIBLE_CONFIG environment variable (path to a file) |
Forcing a specific configuration (in CI, for example) |
| 2 | ansible.cfg in the current directory |
Project configuration (our case) |
| 3 | ~/.ansible.cfg (in your home directory) |
The user's personal preferences |
| 4 | /etc/ansible/ansible.cfg |
System-wide configuration |
flowchart TD
A{"ANSIBLE_CONFIG set?"} -- Yes --> U1["Use that file"]
A -- No --> B{"./ansible.cfg exists?"}
B -- Yes --> U2["Use ./ansible.cfg"]
B -- No --> C{"~/.ansible.cfg exists?"}
C -- Yes --> U3["Use ~/.ansible.cfg"]
C -- No --> D{"/etc/ansible/ansible.cfg?"}
D -- Yes --> U4["Use /etc/ansible/ansible.cfg"]
D -- No --> U5["Defaults only"]
Two important consequences:
- Files are not combined. If
./ansible.cfgexists, Ansible completely ignores~/.ansible.cfg, even if the latter has settings the former doesn't define (for those, Ansible's default value applies, not the one in your personal file). - It depends on the directory you run from. That's why, in this course, we always run from
~/aurora-infra. If you launchansiblefrom another directory, it won't load the project's configuration.
To find out which file is being used, look at the second line of ansible --version:
None means that, for now, there is no configuration file: Ansible uses only its default values.
- The world-writable directory warning
If the current directory is writable by any user (world-writable), Ansible refuses to read the ansible.cfg it contains and shows:
[WARNING]: Ansible is being run in a world writable directory (/vagrant/aurora-infra),
ignoring it as an ansible.cfg source.It's a security measure: another user on the system could drop in a malicious ansible.cfg (one that loads plugins from a path they control, for example) and get you to run it. It usually shows up in:
- Vagrant or VirtualBox shared folders (
/vagrant). - Windows drives mounted in WSL (
/mnt/c/...). - Directories created with
777permissions by mistake.
Solutions, in order of preference:
- Work in a directory of your own with normal permissions (such as
~/aurora-infra). - Fix the permissions:
chmod o-w ~/aurora-infra. - If you can't change the permissions, point explicitly to the file with
export ANSIBLE_CONFIG=$PWD/ansible.cfg(knowing why the warning exists).
- Aurora Store's
ansible.cfg
ansible.cfg4.1 Generating a complete reference
Ansible can generate a file with every available option, commented out and showing its default value:
initgenerates a configuration file.--disabledleaves each option commented out (with;), so nothing would change if you used it as is.- Adding
-t allwould also include the options for every plugin (it's huge).
That file has hundreds of lines: it's a good reference to consult, but don't use it as the project's ansible.cfg. A useful configuration is short and explicit: only what you actually want to change, with a comment explaining why. Take a look and delete it (or keep it outside the repository):
4.2 The project file
Create ~/aurora-infra/ansible.cfg:
# =====================================================================
# ansible.cfg - Configuration for the aurora-infra project (Aurora Store)
# Always run commands from the root of the repository.
# =====================================================================
[defaults]
# Default inventory (path relative to this file).
# This way there's no need to type "-i inventory/" in every command.
inventory = inventory
# Default remote user and SSH key (Vagrant lab).
# The -u command-line option can override them for a single run.
remote_user = vagrant
private_key_file = ~/.ssh/aurora_ed25519
# Check the servers' SSH fingerprint against ~/.ssh/known_hosts.
# This is the default; we make it explicit so nobody disables it
# "temporarily" and forgets about it. Disabling it exposes you to spoofing attacks.
host_key_checking = True
# Number of hosts processed in parallel (default: 5).
forks = 10
# Automatically discover the servers' Python without showing warnings.
interpreter_python = auto_silent
# Playbook output: default callback with results in YAML,
# much more readable than single-line JSON.
stdout_callback = default
callback_result_format = yaml
# Don't create .retry files after a failure (also the default).
retry_files_enabled = False
[privilege_escalation]
# Don't escalate privileges unless asked to (--become or "become: true").
become = False
# Escalation method: sudo (the vagrant user has passwordless sudo).
become_method = sudo
# Don't ask for the sudo password (not needed in the lab).
become_ask_pass = False
[ssh_connection]
# Reuse SSH connections for 60 s (ControlPersist) and compress
# traffic (-C). Greatly speeds up runs with many tasks.
ssh_args = -C -o ControlMaster=auto -o ControlPersist=60s
# Pipelining cuts SSH operations even further, but has requirements
# (sudo without "requiretty"). Covered in "Performance Tuning" (Module 9).
pipelining = FalseLet's go over each decision:
| Option | Value | Why |
|---|---|---|
inventory |
inventory |
Points to the directory you created in 2.1. Relative paths are resolved against the location of ansible.cfg |
remote_user |
vagrant |
The lab's default user |
private_key_file |
~/.ssh/aurora_ed25519 |
The key created in lesson 1.3 (only the path, never the key itself) |
host_key_checking |
True |
Security: prevents connecting to a spoofed server |
forks |
10 |
With 3 hosts you won't notice, but it's a sensible value to grow into |
interpreter_python |
auto_silent |
Ubuntu 24.04 has /usr/bin/python3; Ansible finds it on its own and the warning isn't needed |
stdout_callback + callback_result_format |
default + yaml |
Readable results in playbooks |
retry_files_enabled |
False |
Avoids .retry files (they're also in .gitignore) |
become* |
False/sudo/False |
Privileges only when explicitly requested |
ssh_args |
ControlPersist 60 s | Connection reuse (you saw it in lesson 1.4) |
pipelining |
False |
It will be enabled after studying it in Module 9 |
Comments in
ansible.cfg: put them on their own lines starting with#or;. Avoid placing comments at the end of a line with a value, because they could be read as part of the value.
About YAML output: the
yamlformat affects playbooks. Ad hoc commands (ansible ...) use a more compact callback of their own by default (minimal), so their output doesn't change.
4.3 Checking that it's being used
And now, without -i:
If all three hosts respond, the configuration works. From here on, every command in the course is written without -i.
- Revisiting the decision about connection data
The user and key are now defined twice: in ansible.cfg (remote_user, private_key_file) and in inventory/group_vars/all/connection.yml (ansible_user, ansible_ssh_private_key_file). We need to pick a single place. Which one?
| Criterion | ansible.cfg |
The inventory's group_vars/all/ |
|---|---|---|
| Nature | The project's default preference | Data for a specific environment |
Can be overridden with -u |
Yes | No (the inventory variable wins) |
| Different per environment | No (a single file) | Yes (each inventory has its own) |
For Aurora we settle on this convention:
- Lab: connection data lives in
ansible.cfg, because it's the project's default and that way-uworks the way anyone new to the team would expect. - Future environments: when an environment needs a different user (
production, for example), it will define it withansible_userin its owngroup_vars/all/, which will take precedence overansible.cfg.
So remove the duplicate file:
Check that everything still works and that the case from lesson 1.5 now behaves "the way you'd expect":
web1 | UNREACHABLE! => {
"changed": false,
"msg": "Failed to connect to the host via ssh: [email protected]: Permission denied (publickey).",
"unreachable": true
}Now -u does take effect, because there's no longer any inventory variable overriding it.
ANSIBLE_* environment variables and order of precedence
ANSIBLE_* environment variables and order of precedenceAlmost every option in ansible.cfg has an equivalent environment variable with the ANSIBLE_ prefix. You already used one in lesson 1.5 (ANSIBLE_FORKS).
Option in ansible.cfg |
Environment variable |
|---|---|
inventory |
ANSIBLE_INVENTORY |
remote_user |
ANSIBLE_REMOTE_USER |
forks |
ANSIBLE_FORKS |
host_key_checking |
ANSIBLE_HOST_KEY_CHECKING |
stdout_callback |
ANSIBLE_STDOUT_CALLBACK |
become |
ANSIBLE_BECOME |
pipelining (in [ssh_connection]) |
ANSIBLE_PIPELINING |
It isn't always "ANSIBLE_ + the name in uppercase": look up the exact name with ansible-config list (section 7).
Environment variables are handy for one-off changes without touching the file:
The order of precedence for configuration settings is, from lowest to highest:
graph LR
A["Ansible<br/>default value"] --> B["ansible.cfg"]
B --> C["Environment variable<br/>ANSIBLE_*"]
C --> D["Command-line<br/>option (-f, -u...)"]
D --> E["Playbook keywords<br/>(Module 3)"]
E --> F["Connection variables<br/>(ansible_user...)"]
In other words: whatever is written closer to run time, and more specifically, wins. The last link is what you saw in the previous lesson: variables such as ansible_user beat everything else.
- The
ansible-config tool
ansible-config toolansible-config is your tool for answering "what configuration do I have, and where does it come from?".
| Subcommand | What it does |
|---|---|
ansible-config init --disabled |
Generates a file with every option commented out |
ansible-config list |
Lists every possible option with its description, default value, INI section and environment variable |
ansible-config view |
Shows the contents of the configuration file in use |
ansible-config dump |
Shows the effective value of every option and its origin |
ansible-config dump --only-changed |
Only those that differ from the default value |
7.1 Seeing what you've changed
CONFIG_FILE() = /home/student/aurora-infra/ansible.cfg
DEFAULT_FORKS(/home/student/aurora-infra/ansible.cfg) = 10
DEFAULT_HOST_LIST(/home/student/aurora-infra/ansible.cfg) = ['/home/student/aurora-infra/inventory']
DEFAULT_PRIVATE_KEY_FILE(/home/student/aurora-infra/ansible.cfg) = /home/student/.ssh/aurora_ed25519
DEFAULT_REMOTE_USER(/home/student/aurora-infra/ansible.cfg) = vagrant
INTERPRETER_PYTHON(/home/student/aurora-infra/ansible.cfg) = auto_silent
...(The exact output may vary slightly between versions.) Each line has the format INTERNAL_NAME(origin) = value. Notice:
- The internal name (
DEFAULT_FORKS,DEFAULT_HOST_LIST) doesn't always match the one inansible.cfg(forks,inventory). - The origin in parentheses tells you whether the value comes from the file, from an environment variable (
env: ANSIBLE_FORKS) or is the default (default). - Paths already appear resolved:
inventoryhas become an absolute path and~has been expanded.
Try combining it with an environment variable:
7.2 Looking up an option
ansible-config list produces extremely long YAML output; filter it:
You will see the description, the default value (5), the INI key ([defaults] forks) and the environment variable (ANSIBLE_FORKS). It's the most reliable way to find out what an option is called in each place.
7.3 Viewing the file in use
It shows the literal contents of the ansible.cfg being used. Useful when you're not sure whether Ansible is reading the file you think it is.
- Saving your work in git
Current structure:
aurora-infra/
├── .gitignore
├── ansible.cfg
├── inventory/
│ ├── hosts.yml
│ ├── group_vars/
│ │ ├── all/
│ │ │ └── aurora.yml
│ │ ├── dbservers.yml
│ │ └── webservers.yml
│ └── host_vars/
│ ├── db1.yml
│ ├── web1.yml
│ └── web2.yml
└── lab/
└── VagrantfileCommon Mistakes and Tips
config file = Nonewhile inside the project: you're in another directory, the file has a different name (ansible.conf,Ansible.cfg) or the directory is world-writable (look for the corresponding warning).- Changes to
~/.ansible.cfgthat "do nothing": there's a./ansible.cfgin the project, and files aren't combined. - Made-up or misspelled option names (
fork = 10,host_key_check = False): Ansible ignores them without an error. Verify withansible-config dump --only-changedthat they show up. - An option in the wrong section:
pipeliningin[defaults]instead of[ssh_connection], orbecomeoutside[privilege_escalation]. Look up the correct section withansible-config list. - Disabling
host_key_checking"to make it work": it hides the real problem (a changed fingerprint after recreating a VM, which you fix withssh-keygen -R), and in real environments it exposes you to man-in-the-middle attacks. If you ever disable it in a throwaway lab, do it as a one-off withANSIBLE_HOST_KEY_CHECKING=False, never in the versioned file. - Storing secrets in
ansible.cfg: never. Only paths to keys, never keys or passwords. - Tip: after any change to
ansible.cfg, runansible-config dump --only-changedand check that the value and its origin are what you expect.
Exercises
Exercise 1: Where does each value come from?
Run these commands and state, for each one, how many forks are used and where the value comes from:
ansible-config dump --only-changed | grep FORKSANSIBLE_FORKS=3 ansible-config dump --only-changed | grep FORKScd /tmp && ansible-config dump --only-changed | grep FORKS; cd ~/aurora-infra
Exercise 2: A personal configuration without breaking the project's
You want commands launched from outside any project to use forks = 15, only on your machine. Where do you configure it? Will it affect aurora-infra?
Exercise 3: Finding an option
Use ansible-config to find out the names of the environment variable and the ansible.cfg key that control the SSH connection timeout (in seconds), what its default value is and which section it goes in.
Solutions
Exercise 1.
10, origin/home/student/aurora-infra/ansible.cfg.3, originenv: ANSIBLE_FORKS: the environment variable beats the file.- Nothing: there's no
ansible.cfgin/tmp(nor, in principle,~/.ansible.cfg), soforkstakes its default value of5and doesn't appear among the changed options.
Exercise 2. In ~/.ansible.cfg:
It doesn't affect aurora-infra: when you run from the project, Ansible finds ./ansible.cfg first and doesn't read ~/.ansible.cfg (files aren't combined). Check it with ansible --version | grep 'config file' inside and outside the project.
Exercise 3.
The option is DEFAULT_TIMEOUT: key timeout in the [defaults] section, environment variable ANSIBLE_TIMEOUT, default value 10 seconds.
Conclusion
Aurora Store now has its versioned ansible.cfg: a default inventory, the lab's user and key, SSH fingerprint checking, 10 forks, silent Python discovery, YAML output, on-demand privilege escalation and SSH connection reuse. You know the order in which Ansible looks for its configuration, why it ignores world-writable directories, how to use ANSIBLE_* variables for one-off changes and how to debug any setting with ansible-config. You have also settled on a convention: default connection data goes in ansible.cfg and is only overridden in the inventory when an environment needs it. With the configuration sorted out, it's time to act on the servers: in the next lesson, Ad Hoc Commands, you will check the state of the machines, install packages and manage services and users with one-line commands, and learn when they're the right tool and when a playbook is better.
Ansible Course: From Beginner to Advanced
Module 1: Introduction to Ansible
- What Is Ansible?
- Installing Ansible
- Setting Up the Practice Lab
- Ansible Architecture
- Basic Ansible Commands
Module 2: Ansible Fundamentals
- Inventory Files
- Inventory Variables: group_vars and host_vars
- Configuring Ansible (ansible.cfg)
- Ad Hoc Commands
- Ansible Modules
- Collections and Fully Qualified Names (FQCN)
Module 3: Playbooks
- Introduction to Playbooks
- Essential YAML for Ansible
- Writing Your First Playbook
- Playbook Structure
- Variables and Facts
- Conditionals and Loops
- Registering Results and Debugging Playbooks
Module 4: Roles
- Introduction to Roles
- Creating Roles
- Role Directory Structure
- Using Roles in Playbooks
- Reusing Tasks: include and import
- Role Dependencies and Argument Validation
Module 5: Advanced Playbook Techniques
- Handlers
- Jinja2 Templates
- Filters and Lookups
- Ansible Vault
- Error Handling
- Tags and Selective Execution
- Rolling Deployments and Delegation
- Optimizing Playbooks
Module 6: Ansible Galaxy
- What Is Ansible Galaxy?
- Using Ansible Galaxy
- Managing Dependencies with requirements.yml
- Creating and Sharing Roles
- Creating Your Own Collections
Module 7: Ansible Tower, AWX and Automation Platform
- Introduction to Ansible Tower and AWX
- Installing AWX
- Using AWX: Job Templates and Jobs
- Managing Projects and Inventories
- Credentials, Permissions (RBAC) and Workflows
- Execution Environments and ansible-navigator
Module 8: Ansible for DevOps
- Ansible and Docker
- Ansible and Kubernetes
- CI/CD with Ansible
- Ansible in Cloud Environments
- Ansible and Terraform
Module 9: Ansible Best Practices
- Code Organization
- Security Best Practices
- Performance Tuning
- Code Quality: ansible-lint and yamllint
- Testing Ansible Code with Molecule
Module 10: Advanced Ansible Topics
- Custom Modules
- Dynamic Inventory
- Ansible Plugins
- The Ansible API and ansible-runner
- Event-Driven Ansible
