Ansible - Host (system)

> Infrastructure as code > Ansible

1 - About

A host may have zero or more than one group (ie webserver and a dbserver).

Advertising

3 - Management

3.1 - Definition

3.1.1 - Inventory file

inventory.ini
hostName

; With regexp, you can add a lot of hosts
www[01:50].example.com
db-[a:f].example.com

3.1.2 - playbook

  • as playbook variable. Example
- name: Wait 300 seconds for port 22 to become open and contain "OpenSSH"
  wait_for:
    port: 22
    host: '{{ (ansible_ssh_host|default(ansible_host))|default(inventory_hostname) }}'
    search_regex: OpenSSH
    delay: 10
  connection: local

3.2 - List

ansible-playbook playbook.yml --list-hosts

3.3 - Variable

Variable that are defined on the group level can be defined:

Advertising

3.3.1 - Inventory Variable

Example:

host.ini
host1 http_port=80 maxRequestsPerChild=808
host2 http_port=303 maxRequestsPerChild=909

3.3.2 - Variable file (host_vars directory)

Variables for a host may be defined in one file or in multiple file under a directory.

The location of this file is relative to the inventory file path or playbook file path.

Order of precedence if both paths exist:

  • playbook directory (higher priority - chosen first )
  • inventory directory

Syntax:

($INVENTORY_DIR|$PLAYBOOK_DIR)/host_vars/host1.yml # can optionally end in '.yaml', or '.json' or no file extension
# or in a directory structure
($INVENTORY_DIR|$PLAYBOOK_DIR)/host_vars/host1/db_settings.yml
($INVENTORY_DIR|$PLAYBOOK_DIR)/host_vars/host1/cluster_settings

Example with the default inventory location: /etc/ansible/hosts, the structure would be

/etc/ansible/group_vars/host1.yml
# or in a directory structure
/etc/ansible/group_vars/host1/db_settings.yml
/etc/ansible/group_vars/host1/cluster_settings

with the file

host1.yml
---
ntp_server: acme.example.org
database_server: storage.example.org
Advertising

3.4 - Built-in hostvars variable

At runtime, you can access the variable with the hostvars variable

Example:

{{ hostvars.alias.ansible_host }}

3.5 - Built-in variable

  • inventory_hostname is the name of the hostname as configured in Ansible’s inventory host file
  • inventory_hostname_short - the part up to the first period, without the rest of the domain.
[group]
inventory_hostname blablabla