Console9

How to set up Ansible inventory for multiple environments

Organize Ansible inventory files for dev, staging, and production environments with group variables.

How to set up Ansible inventory for multiple environments

Organize Ansible inventory files for dev, staging, and production environments with group variables.

Prerequisites

  • Ansible installed on the control node.
  • SSH access to managed hosts.

Step-by-Step: Set Up Multi-Environment Inventory

  1. Create a directory structure with one inventory file per environment:

    inventories/
      production/
        hosts.ini
        group_vars/
          all.yml
          webservers.yml
      staging/
        hosts.ini
        group_vars/
          all.yml
  2. Define hosts in each environment's hosts.ini:

    [webservers]
    web1.prod.example.com
    web2.prod.example.com
    
    [dbservers]
    db1.prod.example.com
  3. Set environment-specific variables in group_vars/all.yml:

    ---
    env_name: production
    nginx_worker_connections: 4096
  4. Target a specific environment when running playbooks:

    ansible-playbook -i inventories/production/hosts.ini site.yml

How to Verify the Inventory

List all hosts in an inventory:

ansible -i inventories/production/hosts.ini all --list-hosts