Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.1k views
in Technique[技术] by (71.8m points)

ansible - How can I set the value of a variable being passed to a role based on ansible_facts?

I'm using geerlingguy's NTP role to set up NTP client software on a collection of hosts. I'd like to point this play at a hostgroup and have Ansible figure out on the fly whether or not each machine is a VM (an important thing to note here is that all of our VMs are running on KVM hypervisors). If the host is a VM, ntp_tinker_panic should be set to true. Otherwise, it should be set to false. Here's the play I wrote:

- name: Set up NTP or chronyd on Linux hosts
  hosts: ntp
  tasks:
    - name: Print the value of ntp_tinker_panic
      debug:
        var: ntp_tinker_panic
    - name: Ensure time sync software is installed and configured
      include_role:
        name: geerlingguy.ntp
  vars:
    ntp_enabled: true
    ntp_manage_config: true
    ntp_timezone: America/New_York
    ntp_servers:
      - "time.google.com"
    ntp_tinker_panic: "{{ ansible_facts['ansible_product_name'] == 'KVM' }}"
  tags:
    - ntp

However, even though the play executes without errors, the debug message states that ntp_tinker_panic is not defined:

TASK [Print the value of ntp_tinker_panic] *****************************************************************************
ok: [hostname] => {
    "ntp_tinker_panic": "VARIABLE IS NOT DEFINED!"
}

Is there a way for me to set the value of that variable on a per-host basis as the play is running instead of defining separate hostgroups for VMs and physical hosts?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It seems like you would like to set the value of ntp_tinker_panic conditionally. Whereas your definition of the variable in the vars section is not going to set it to true. And it does not take into consideration each host of the ntp group.

You should use set_fact task in the play to set this variable to true if ansible_product_name matches KVM for that host.

Example:

# ntp_tinker_panic not specified here in vars as it is target specific
  vars:
    ntp_enabled: true
    ntp_manage_config: true
    ntp_timezone: America/New_York
    ntp_servers:
      - "time.google.com"

  tasks:
    - name: Set ntp_tinker_panic for KVM
      set_fact:
        ntp_tinker_panic: true
      when: ansible_product_name == "KVM"
    - name: Print the value of ntp_tinker_panic
      debug:
        var: ntp_tinker_panic

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...