简体   繁体   中英

Fact access from another role in Ansible

I have set some facts during my ansible play using pre_tasks:

    - name: set site name variables
      set_fact: 
        site_name: '{{ ansible_hostname | regex_replace("^([a-z]{3}[0-9]).*", "\1") }}'
        site_name_upper: '{{ ansible_hostname | regex_replace("^([a-z]{3}[0-9]).*", "\1") | upper }}'

and now I would like to access them from a role I'm developing. When I try to access them directly I get an error that the variable is undefined:

TASK [monitoring-server : debug] ****************************************************************************************************************************************************************************************************
fatal: [hostname]: FAILED! => {"msg": "the field 'args' has an invalid value, which appears to include a variable that is undefined.The error was: 'site_name' is undefined\n\nThe error appears to have been in '/opt/ansible/dv-ansible/roles/linux-monitoring-server/tasks/smokeping.yaml': line 55, column 3, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n- name: debug\n  ^ here\n\nexception type: <class 'ansible.errors.AnsibleUndefinedVariable'>\nexception: 'site_name' is undefined"}
    to retry, use: --limit @/opt/ansible/.ansible-retry/linux_monitoring_server.retry

According to some articles I've read, I need to use hostvars to look up facts set in another playbook, eg:

{{ hostvars[{{ansible_hostname}}]['site_name'] }}

However, there are obvious issues with this (variable inside of a variable). I know I can simply define my facts in every role that needs access to them, but that seems messy and is definitely not DRY.

I just need a way to set and access "global" facts/variables that can be accessed from multiple plays and roles. What is the best way to do this?

Wow, now I feel silly. Just realized you can put dynamically-executed Jinja in group_vars and host_vars files.

The answer, of course, is to just move the site_name definitions to group_vars/all/all.yaml .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM