Ansible Inventory 清单变量详解 使你的 playbook 更加强大!

在 Ansible中,我们可以使用hosts文件来定义服务器列表和组。一旦我们确信这部分功能正常运行,我们可以使用 Ansible inventory 来扩展和定义清单变量。

在inventory文件中,我们可以为每个主机定义不同的变量,例如 IP 地址、主机名、SSH 用户名等。这些变量可以在playbook中使用,以执行不同的命令和操作。

在inventory文件中,我们可以使用 YAML 或 INI 格式来定义主机和组。

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:

在以上这个文件中,定义了两个服务器(web1 和 web2)和一个名为 webservers 的组。我们为每个服务器指定了不同的变量,包括 IP 地址、web 服务器类型和 HTTP 端口。

要使用这些变量,在 Ansible playbook 中可以使用 Jinja2 模板语言来访问这些变量,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

在上述 playbook 示例中,可以使用 when 关键字来检查主机的 web_server 是否设置为 true。如果是,则执行任务。其中还使用了 template 模块来复制 Apache 配置文件,并将其修改为要求的状态。

猜你喜欢

转载自blog.csdn.net/qq_34185638/article/details/131088886