【问题标题】:How to dynamically set the hosts field in Ansible playbooks with a variable generated during execution?如何使用执行期间生成的变量动态设置 Ansible playbook 中的 hosts 字段?
【发布时间】:2020-02-01 19:53:04
【问题描述】:

我正在尝试使用 Ansible 提供的变量机制在家中测试一些东西,我将在我的一个工作项目中实施该机制。所以,现在已经搜索了一段时间,但似乎我无法让它如此轻松地工作,即使在这里和那里使用其他人的解决方案。

我现在将通过在家中演示我的测试目录和文件结构来代表我的项目逻辑。情况就是这样,我有以下剧本:

main.yaml
pl1.yaml
pl2.yaml

./main.yaml 的内容:

  - import_playbook: /home/martin/ansible/pl1.yaml
  - import_playbook: /home/martin/ansible/pl2.yaml

./pl1.yaml 的内容:

- name: Test playbook 1
  hosts: localhost
  tasks:
  - name: Discovering the secret host
    shell: cat /home/martin/secret
    register: whichHostAd
  - debug:
      msg: "{{ whichHostAd.stdout }}"
  - name: Discovering my hostname
    shell: hostname
    register: myHostnameAd
  - set_fact:
      whichHost: "{{ whichHostAd.stdout }}"
      myHostname: "{{ myHostnameAd.stdout }}"
    cacheable: yes

- name: Test playbook 1 part 2
  hosts: "{{ hostvars['localhost']['ansible_facts']['whichHost'] }}"
  tasks:
  - name: Structuring info
    shell: hostname
    register: secretHostname
  - name: Showing the secret hostname
    debug:
      msg: "{{ secretHostname.stdout }}"

./pl2.yaml 的内容:

- name: Test Playbook 2
  hosts: "{{ whichHost }}"
  tasks:
  - name: Finishing up
    shell: echo "And here am i again.." && hostname
  - name: Showing var myHostname
    debug:
      msg: "{{ myHostname.stdout }}"

整个想法是在两次播放之间的hosts 字段中设置一个on the go 工作变量。我们如何做到这一点?

如果我不将 whichHost 变量定义为额外的 arg,则剧本根本不会运行,没关系,我每次都可以这样做,但 在执行期间 我想让这个变量易于管理和改变。在上面的测试用例中,我希望 whichHost 在 main.yaml 中包含的剧本/剧本中随处使用,特别是反映 pl1.yaml 中第一个任务的输出(或whichHostAd.stdout 变量),所以我可以在 pl2.yaml 中确定我要定位的主机。

根据文档,我至少应该能够使用hostvars 访问它(就像在我的剧本中一样),但这是我在尝试上述示例时得到的输出:

ERROR! The field 'hosts' has an invalid value, which includes an undefined variable. The error was: 'dict object' has no attribute 'whichHost'

The error appears to have been in '/home/martin/ansible/pl1.yaml': line 22, column 3, but may
be elsewhere in the file depending on the exact syntax problem.

The offending line appears to be:


- name: Test playbook 1 part 2
  ^ here

set_fact 似乎也不是很有帮助。任何帮助将不胜感激!

【问题讨论】:

    标签: variables ansible devops ansible-awx


    【解决方案1】:

    好的,其实我很快就想通了。

    所以,我们肯定需要一个事实任务,保存实际的数据/输出:

    - hosts: localhost
      tasks:
      - name: Saving variable
        set_fact:
          whichHost: "{{ whichHostAd.stdout }}"
    

    之后,当你想在其他主机和plays中调用var时,我们必须提供主机和事实:

    "{{ hostvars['localhost']['whichHost'] }}"
    

    就像我上面的测试一样,但没有['ansible_facts']

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-31
      • 1970-01-01
      • 2014-01-14
      • 2017-09-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多