首页 > 解决方案 > 读取所有变量和事实并将它们设置为 linux 环境变量

问题描述

[已解决] 这个问题解决了。我稍后会发布解决方案。谢谢

我有这样的变量:

mycompany_package1_key1: ...
mycompany_package1_key2: ...
mycompany_package2_key1: ...
mycompany_package2_key2: ...
mycompany_package3_key1: ...

好消息是它们在剧本中可见。我可以像这样直接引用它们:{{ mycompany_package1_key1 }}.

问题是这些密钥在测试中不可用,因为我没有将它们作为 ansible 的一部分运行。为了克服这个问题,我想运行一个剧本,在运行我的测试之前将它们设置为 linux 环境变量。然后我将能够在 Ruby 中读取这些环境变量。

如果我能够阅读它们,那么我想我将能够在剧本本身中编写一些逻辑,仅当变量以mycompany_.

我被困在阅读部分本身:

- name: Read All Ansible variables.
  debug:
    var=hostvars[item]
  loop: "{{ hostvars }}"

我也试过这个:

- name: "Ansible | List all known variables and facts"
    debug:
      var: hostvars[inventory_hostname]

hostvars 或 hostvars[inventory_hostname] 将所有内容捆绑在一起,而不是给我单独的键/值。

标签: ansible

解决方案


基本上我是分三个步骤完成的:

  • name: 读取所有变量 debug: var: hostvars[inventory_hostname] register: myallthevariables
- name: Store them in a text file
  with_dict "{{ myallthevariables['hostvars[inventory_hostname]'] }}"
  shell: "printf {{ item.key }}={{ item.value}}'\n' >> /path/to/file.txt"

第三步是在我的测试中读取文本文件并将值存储在 Map(Ruby 中的哈希)中,然后继续或将它们设置为 Linux ENV 变量。

我不能通过 ansible 做到这一点,因为 ENV 变量适用于设置了这些 ENV 变量的子进程,并且由于我的测试在不同的进程中运行,所以它对我没有锻炼。


推荐阅读