• 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
    
  • 相关阅读:
    mysql对字段分割内容查询
    vue相关报错
    java多线程面试题
    java的消息队列
    电子商务大数据平台实训系统业务数据仓库总结
    电子商务大数据平台实训用户行为数仓业务总结
    电子商务大数据平台实训第一阶段总结
    Java 并发基础常见面试题总结
    window 平台 安装MongoDB
    java知识汇总(第六天)
  • 原文地址:https://www.cnblogs.com/wt11/p/16389934.html
Copyright © 2020-2023  润新知