其他分享
首页 > 其他分享> > ansible使用各主机不同变量

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

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