Ansible - Host (system)

About

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

Management

Definition

Inventory file

hostName

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

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

List

ansible-playbook playbook.yml --list-hosts

Variable

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

Inventory Variable

Example:

host1 http_port=80 maxRequestsPerChild=808
host2 http_port=303 maxRequestsPerChild=909

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

---
ntp_server: acme.example.org
database_server: storage.example.org

Built-in hostvars variable

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

Example:

{{ hostvars.alias.ansible_host }}

Built-in variable

Inventory

  • 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

Connection

Connection:

  • ansible_host : the name to connect to

Fact

Fact

You can see them by running the setup module with the ansible command line

ansible -i inventories.yml -m setup all

Extract the domain

Example if you define the ansible_host with the following full qualified name hostname.example.com

{{ ansible_host.split('.', 1)[1] }}

With ansible

ansible -i inventory.yml -m debug -a "msg={{ ansible_host.split('.', 1)[1] }}" all
example.com

Extract the hostname

Example if you define the ansible_host with the following full qualified name hostname.example.com

{{ ansible_host.split('.', 1)[0] }}

With ansible

ansible -i inventory.yml -m debug -a "msg={{ ansible_host.split('.', 1)[0] }}" all
example.com

Powered by ComboStrap