Ansible Inventory list variable detailed explanation makes your playbook more powerful!

In Ansible, we can use the hosts file to define server lists and groups. Once we're sure this part is working, we can use Ansible inventory to extend and define inventory variables.

In the inventory file, we can define different variables for each host, such as IP address, hostname, SSH username, etc. These variables can be used in playbooks to execute different commands and actions.

In the inventory file, we can use YAML or INI format to define hosts and groups.

example


all:
  hosts:
    web1:
      ansible_host: 192.168.1.101
      web_server: true
      http_port: 80
    web2:
      ansible_host: 192.168.1.102
      web_server: true
      http_port: 8080
  children:
    webservers:
      hosts:
        web1:
        web2:

In the above file, two servers (web1 and web2) and a group called webservers are defined. We specified different variables for each server, including IP address, web server type, and HTTP port.

To use these variables, you can use the Jinja2 templating language to access these variables in Ansible playbooks, example:


- name: Install Apache
  hosts: webservers
  become: yes
  tasks:
    - name: Install Apache web server
      yum:
        name: httpd
        state: present
      when: web_server == true

    - name: Configure Apache web server
      template:
        src: /path/to/httpd.conf.j2
        dest: /etc/httpd/conf/httpd.conf
      when: web_server == true

    - name: Start Apache web server
      service:
        name: httpd
        state: started
      when: web_server == true

In the playbook example above, whenthe keyword can be used to check whether the host's web_server is set to true. If yes, execute the task. It also uses templatethe module to copy the Apache configuration file and modify it to the required state.

Guess you like

Origin blog.csdn.net/qq_34185638/article/details/131088886