ansible使用各主机不同变量
首先需要创建host_vars.yml文件(可以根据需要建在任意位置)
/home/ops/ansible/vars/host_vars.yml
---
# vars file for node_exporter
hosts:
- busi: zhudong
machines:
- ip: '10.96.19.'
dc: jiangsu
- ip: '12.76.242.'
dc: shanxi1
- ip: '11.84.27.'
dc: chongqing
- ip: '1.1.238.'
dc: guangxi
一、只使用playbook
playbook.yml
---
- hosts: all
remote_user: root
gather_facts: no
vars_files:
- "/home/ops/ansible/vars/host_vars.yml"
serial:
- "10%" # 第一次执行10%,成功后再同时执行20%,最后100%
- "20%"
- "100%"
tasks:
- name: set fact
set_fact:
ip: "{{item.1.ip}}"
dc: "{{item.1.dc}}"
busi: "{{item.0.busi}}"
# 判断字符串是否包含用“in”,精确匹配用“==”
when: ("{{item.1.ip}}" in "{{ (ansible_ssh_host|default(ansible_host))|default(inventory_hostname) }}")
with_subelements:
- "{{hosts}}"
- machines
# 变量ip、dc、busi可以直接在模板或下边的task中使用
- name: send the telegraf config
template:
src: "{{ telegraf_conf_template }}"
dest: /tmp/telegraf.conf
owner: root
group: root
mode: 0644
- name: create expoters folder
file:
path: /tmp/{{dc}}
state: directory
二、在roles中使用
playbook.yml
---
- hosts: all
remote_user: root
gather_facts: no
vars_files:
- "/home/ops/ansible/vars/host_vars.yml"
serial:
- "10%" # 第一次执行10%,成功后再同时执行20%,最后100%
- "20%"
- "100%"
roles:
- roles/test
roles/install.yml
---
- name: set fact
set_fact:
ip: "{{item.1.ip}}"
dc: "{{item.1.dc}}"
busi: "{{item.0.busi}}"
when: ("{{item.1.ip}}" in "{{ (ansible_ssh_host|default(ansible_host))|default(inventory_hostname) }}")
with_subelements:
- "{{hosts}}"
- machines
- debug:
msg: "busi: {{item.0.busi}}
dc: {{item.1.dc}}
ip: {{item.1.ip}}"
with_subelements:
- "{{hosts}}"
- machines
- name: send the telegraf config
template:
src: "{{ telegraf_conf_template }}"
dest: /tmp/telegraf.conf
owner: root
group: root
mode: 0644
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· .NET Core 中如何实现缓存的预热?
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 如何调用 DeepSeek 的自然语言处理 API 接口并集成到在线客服系统
· 【译】Visual Studio 中新的强大生产力特性