ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

ansible使用各主机不同变量

2022-06-19 09:31:24  阅读:173  来源: 互联网

标签:busi item.1 变量 vars 主机 dc host ansible ip


首先需要创建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

标签:busi,item.1,变量,vars,主机,dc,host,ansible,ip
来源: https://www.cnblogs.com/wt11/p/16389934.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有