【问题标题】:Ansible populate variable for global useAnsible 填充变量以供全局使用
【发布时间】:2020-07-24 01:07:25
【问题描述】:

这周我遇到了 Ansible 变量地狱。我需要在运行时动态填充一个变量,然后它需要可用于多个任务。

myplaybook.yml

---
- hosts: Healthcheck_Host 
  gather_facts: no
  become: "{{ True if deploy_user != '{{ deploy_user }}' else False }}"
  become_user: "{{ deploy_user }}"
  tasks:

    - name: "Get latest installed CL on groups['Healthcheck_Host'][0]"
      shell: |
        grep -oP '(?<=\:)(.*?)(?=\-)' {{ latest_deployed_build_dir.stdout }}/thebuildinfo.txt
      register: latest_stable_cl

    - debug:
        var: latest_stable_cl.stdout

    - name: Assign CL value from HC host
      set_fact:
        stable_cl_to_deploy: "{{ latest_stable_cl.stdout }}"
        cacheable: yes

- hosts: Appserver
  gather_facts: no
  become: "{{ True if deploy_user != '{{ deploy_user }}' else False }}"
  become_user: "{{ deploy_user }}"
  tasks:

    - debug:
        var: stable_cl_to_deploy

在 /etc/ansible/ansible.cfg 我确实有这个设置:fact_caching = memory

调试输出按预期从第一个块返回值,但是一旦执行第二个块,我就会收到此错误:

"msg": "The task includes an option with an undefined variable. The error was: 'stable_cl_to_deploy' is undefined\n\nThe error appears to have been in '/some/path/here/to/my/myplaybook.yml': line 30, 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: Set variables for tools package if deploying stable CL\n  ^ here\n\nexception type: <class 'ansible.errors.AnsibleUndefinedVariable'>\nexception: 'stable_cl_to_deploy' is undefined"

任何帮助表示赞赏。谢谢

【问题讨论】:

    标签: variables scope ansible


    【解决方案1】:

    set_fact 设置特定于主机的事实。在示例中,stable_cl_to_deploy 被添加到 Healthcheck_Host 的事实中并在 Appserver 中引用,因此出现错误。

    使用 ansible 的 special variable hostvars 访问其他主机的变量,例如:

    - debug:
        var: hostvars['Healthcheck_Host'].stable_cl_to_deploy
    

    【讨论】:

    • 不幸的是,这仍然给出:2020 年 7 月 24 日星期五 16:38:48 +0000 (0:00:00.313) 0:00:05.378 *********** 好的: [localhost] => { "hostvars['Healthcheck_Host'].stable_cl_to_deploy": "变量未定义!" } 我复制并粘贴了你写的内容。
    • 这行得通! - 调试:var: hostvars['groups['Healthcheck_Host']'].stable_cl_to_deploy 谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-28
    • 1970-01-01
    • 2023-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多