ansible_playbook template模块获取ip
时间: 2024-01-26 10:04:55 浏览: 34
在 `Ansible` 的 `template` 模块中,可以使用 `hostvars` 变量获取其他主机的 IP 地址。`hostvars` 变量是一个字典,其中包含了所有主机的变量信息,可以通过主机名或组名来访问。
例如,假设你有一个 `webserver` 主机组和一个 `database` 主机组,你可以通过以下方式在 `template` 中获取 `webserver` 组中每个主机的 IP 地址:
```
{% for host in groups['webserver'] %}
{{ hostvars[host]['ansible_host'] }}
{% endfor %}
```
这段代码会遍历 `webserver` 组中的每个主机,并使用 `hostvars` 变量来获取每个主机的 `ansible_host` 变量,该变量包含了主机的 IP 地址。你可以将这段代码插入到 `template` 文件中,以便在模板中使用这些 IP 地址。
相关问题
编写playbook,实现安装配置httpd服务,使用模板生成httpd的主页文件/var/www/html/index.html主页显示的内容是Welcome to {{ ansible_fqdn }} on {{ ansible_default_ipaddress }}。
以下是一个实现安装配置httpd服务并使用模板生成主页文件的Playbook:
```yaml
---
- name: Install and configure httpd
hosts: all
become: true
tasks:
- name: Install httpd
yum:
name: httpd
state: present
- name: Start httpd and enable at boot
service:
name: httpd
state: started
enabled: yes
- name: Configure firewall for httpd
firewalld:
service: http
permanent: true
state: enabled
immediate: true
- name: Generate index.html file
template:
src: templates/index.html.j2
dest: /var/www/html/index.html
```
在此Playbook中,我们首先使用`yum`模块安装httpd。然后,我们使用`service`模块启动httpd并将其设置为开机启动。接下来,我们使用`firewalld`模块配置防火墙以允许http流量。最后,我们使用`template`模块从模板文件`index.html.j2`生成主页文件,并将其放置在`/var/www/html/index.html`位置。
以下是`index.html.j2`模板文件的内容:
```html
<html>
<head>
<title>Welcome to {{ ansible_fqdn }} on {{ ansible_default_ipv4.address }}</title>
</head>
<body>
<h1>Welcome to {{ ansible_fqdn }} on {{ ansible_default_ipv4.address }}</h1>
</body>
</html>
```
该模板文件中,我们使用了`{{ ansible_fqdn }}`和`{{ ansible_default_ipv4.address }}`变量,这些变量分别对应主机的完全域名和IP地址,并将它们插入到HTML文件中。
用ansible-playbook 安装Nginx搭建httpf集群
以下是一个简单的 Ansible playbook,用于在多个服务器上安装 Nginx 并搭建 Httpf 集群:
```yaml
---
- name: Install Nginx and set up Httpf cluster
hosts: webservers
become: true
vars:
httpf_port: 8080
httpf_backend_servers:
- 192.168.1.1
- 192.168.1.2
- 192.168.1.3
tasks:
- name: Install Nginx
apt:
name: nginx
state: present
- name: Configure Httpf upstream
template:
src: templates/httpf_upstream.j2
dest: /etc/nginx/conf.d/httpf_upstream.conf
notify: Reload Nginx
- name: Configure Nginx to listen on port 80
template:
src: templates/nginx_http.j2
dest: /etc/nginx/sites-enabled/default
notify: Reload Nginx
handlers:
- name: Reload Nginx
service:
name: nginx
state: reloaded
```
在上面的 playbook 中,我们首先定义了一些变量:
- `httpf_port`:Httpf 服务器运行的端口号。
- `httpf_backend_servers`:Httpf 服务器的后端服务器 IP 地址列表。
然后我们定义了一些任务:
- `Install Nginx`:通过 Ansible 的 `apt` 模块安装 Nginx。
- `Configure Httpf upstream`:使用 Ansible 的 `template` 模块生成 Httpf upstream 配置文件。
- `Configure Nginx to listen on port 80`:使用 Ansible 的 `template` 模块生成 Nginx 配置文件。
- `Reload Nginx`:使用 Ansible 的 `service` 模块重新加载 Nginx 服务。
最后,我们定义了一个 handler,当任何一个任务修改了 Nginx 配置文件时,就会触发这个 handler,重新加载 Nginx 服务。