Claude
Skills
Sign in
Back

ansible-inventory

Included with Lifetime
$97 forever

Use when managing hosts and groups in Ansible inventory for organizing infrastructure and applying configurations across environments.

General

What this skill does


# Ansible Inventory

Manage hosts and groups in Ansible inventory for organized infrastructure management.

## INI Format Inventory

### Basic Host Definitions

```ini
# Simple host list
mail.example.com
web1.example.com
web2.example.com
db1.example.com

# Hosts with aliases
web1 ansible_host=192.168.1.10
web2 ansible_host=192.168.1.11
db1 ansible_host=192.168.1.20

# Hosts with connection parameters
app1 ansible_host=10.0.1.50 ansible_user=deploy ansible_port=2222
app2 ansible_host=10.0.1.51 ansible_user=deploy ansible_port=2222
```

### Group Definitions

```ini
[webservers]
web1.example.com
web2.example.com
web3.example.com

[databases]
db1.example.com
db2.example.com

[monitoring]
monitor1.example.com

[production:children]
webservers
databases

[staging:children]
staging-web
staging-db

[staging-web]
staging-web1.example.com
staging-web2.example.com

[staging-db]
staging-db1.example.com
```

### Host Variables

```ini
[webservers]
web1.example.com http_port=80 max_connections=1000
web2.example.com http_port=8080 max_connections=2000
web3.example.com http_port=80 max_connections=1500

[databases]
db1.example.com db_role=primary
db2.example.com db_role=replica
```

### Group Variables

```ini
[webservers:vars]
nginx_version=1.21.0
app_environment=production
backup_enabled=true

[databases:vars]
postgresql_version=14
max_connections=200
shared_buffers=256MB

[production:vars]
monitoring_enabled=true
log_level=info
```

## YAML Format Inventory

### Basic YAML Inventory

```yaml
---
all:
  hosts:
    mail.example.com:

  children:
    webservers:
      hosts:
        web1.example.com:
          ansible_host: 192.168.1.10
          http_port: 80
        web2.example.com:
          ansible_host: 192.168.1.11
          http_port: 8080
      vars:
        nginx_version: "1.21.0"
        app_environment: production

    databases:
      hosts:
        db1.example.com:
          ansible_host: 192.168.1.20
          db_role: primary
        db2.example.com:
          ansible_host: 192.168.1.21
          db_role: replica
      vars:
        postgresql_version: "14"
        max_connections: 200

    production:
      children:
        webservers:
        databases:
      vars:
        monitoring_enabled: true
        backup_enabled: true
        log_level: info
```

### Complex YAML Inventory

```yaml
---
all:
  vars:
    ansible_user: ansible
    ansible_become: yes
    ansible_become_method: sudo

  children:
    datacenters:
      children:
        us_east:
          children:
            us_east_web:
              hosts:
                web-us-east-1:
                  ansible_host: 10.10.1.10
                  datacenter: us-east-1
                  rack: A1
                web-us-east-2:
                  ansible_host: 10.10.1.11
                  datacenter: us-east-1
                  rack: A2
              vars:
                region: us-east
                availability_zone: us-east-1a

            us_east_db:
              hosts:
                db-us-east-1:
                  ansible_host: 10.10.1.20
                  db_role: primary
                  datacenter: us-east-1
                db-us-east-2:
                  ansible_host: 10.10.1.21
                  db_role: replica
                  datacenter: us-east-1
              vars:
                region: us-east

        us_west:
          children:
            us_west_web:
              hosts:
                web-us-west-1:
                  ansible_host: 10.20.1.10
                  datacenter: us-west-1
                  rack: B1
                web-us-west-2:
                  ansible_host: 10.20.1.11
                  datacenter: us-west-1
                  rack: B2
              vars:
                region: us-west
                availability_zone: us-west-1a

            us_west_db:
              hosts:
                db-us-west-1:
                  ansible_host: 10.20.1.20
                  db_role: primary
                  datacenter: us-west-1
              vars:
                region: us-west
```

## Host Patterns and Ranges

### Numeric Ranges

```ini
[webservers]
web[1:10].example.com

[databases]
db[01:05].example.com

[application]
app-[a:f].example.com
```

```yaml
---
all:
  children:
    webservers:
      hosts:
        web[1:10].example.com:
    databases:
      hosts:
        db[01:05].example.com:
    application:
      hosts:
        app-[a:f].example.com:
```

### Multiple Groups

```ini
[webservers]
web[1:5].example.com

[loadbalancers]
lb[1:2].example.com

[frontend:children]
webservers
loadbalancers

[frontend:vars]
http_port=80
https_port=443
```

## Dynamic Inventory

### Basic Dynamic Inventory Script

```python
#!/usr/bin/env python3
"""
Dynamic inventory script for Ansible
"""
import json
import sys
import argparse

def get_inventory():
    """Return inventory data structure"""
    inventory = {
        'webservers': {
            'hosts': ['web1.example.com', 'web2.example.com'],
            'vars': {
                'nginx_version': '1.21.0',
                'http_port': 80
            }
        },
        'databases': {
            'hosts': ['db1.example.com', 'db2.example.com'],
            'vars': {
                'postgresql_version': '14',
                'db_port': 5432
            }
        },
        'production': {
            'children': ['webservers', 'databases'],
            'vars': {
                'environment': 'production',
                'monitoring_enabled': True
            }
        },
        '_meta': {
            'hostvars': {
                'web1.example.com': {
                    'ansible_host': '192.168.1.10',
                    'http_port': 80
                },
                'web2.example.com': {
                    'ansible_host': '192.168.1.11',
                    'http_port': 8080
                },
                'db1.example.com': {
                    'ansible_host': '192.168.1.20',
                    'db_role': 'primary'
                },
                'db2.example.com': {
                    'ansible_host': '192.168.1.21',
                    'db_role': 'replica'
                }
            }
        }
    }
    return inventory

def get_host_vars(host):
    """Return variables for a specific host"""
    inventory = get_inventory()
    return inventory['_meta']['hostvars'].get(host, {})

def main():
    """Main execution"""
    parser = argparse.ArgumentParser(description='Dynamic Ansible Inventory')
    parser.add_argument('--list', action='store_true', help='List all groups')
    parser.add_argument('--host', help='Get variables for a specific host')
    args = parser.parse_args()

    if args.list:
        print(json.dumps(get_inventory(), indent=2))
    elif args.host:
        print(json.dumps(get_host_vars(args.host), indent=2))
    else:
        parser.print_help()
        sys.exit(1)

if __name__ == '__main__':
    main()
```

### AWS EC2 Dynamic Inventory

```python
#!/usr/bin/env python3
"""
AWS EC2 dynamic inventory for Ansible
"""
import json
import boto3
from collections import defaultdict

def get_ec2_inventory():
    """Fetch EC2 instances and build inventory"""
    ec2 = boto3.client('ec2')

    inventory = defaultdict(lambda: {'hosts': [], 'vars': {}})
    hostvars = {}

    # Fetch all running instances
    response = ec2.describe_instances(
        Filters=[{'Name': 'instance-state-name', 'Values': ['running']}]
    )

    for reservation in response['Reservations']:
        for instance in reservation['Instances']:
            instance_id = instance['InstanceId']
            private_ip = instance.get('PrivateIpAddress', '')
            public_ip = instance.get('PublicIpAddress', '')

            # Get instance name from tags
            name = instance_id
            for tag in instance.get('Tags', []):
                if tag['Key'] == 'Name':
                    name = tag['Value']
                    break

            # Build host variables
            hostvars[name] = {
 

Related in General