如何在Ansible set_fact中使用fact?

问题描述 投票:0回答:2

我试图避免重复包含文件中的值。我尝试在附带的文件中添加顶级namevarstasks

---
- name: Install Terraform
  vars:
    terraform_base_url: "https://releases.hashicorp.com/terraform/{{ terraform_version }}"
    terraform_package_file: "terraform_{{ terraform_version }}_linux_amd64.zip"
    terraform_package_url: "{{ terraform_base_url }}/{{ terraform_package_file }}"
    terraform_checksum_url: "{{ terraform_base_url }}/terraform_{{ terraform_version }}_SHA256SUMS"
    terraform_package_path: "/tmp/{{ terraform_package_file }}"

  tasks:
  - name: Install unzip package
  …

这导致“在任务中未检测到任何操作”错误。我也尝试删除tasks标题并将所有任务放在顶层,但得到了相同的结果。所以我设置了这样的变量(terraform_version在剧本中定义):

- name: Set Terraform variables
  set_fact:
    terraform_base_url: "https://releases.hashicorp.com/terraform/{{ terraform_version }}"
    terraform_package_file: "terraform_{{ terraform_version }}_linux_amd64.zip"
    terraform_package_url: "{{ terraform_base_url }}/{{ terraform_package_file }}"
    terraform_checksum_url: "{{ terraform_base_url }}/terraform_{{ terraform_version }}_SHA256SUMS"
    terraform_package_path: "/tmp/{{ terraform_package_file }}"

ansible-lint没有抱怨这个,但由于某种原因,第二个变量中的terraform_base_url引用中断:

The task includes an option with an undefined variable. The error was: 'terraform_base_url' is undefined

The error appears to have been in '/vagrant/provisioning/ansible/install-terraform.yml': line 2, column 3, but may
be elsewhere in the file depending on the exact syntax problem.
The offending line appears to be:
---
- name: Set Terraform variables
  ^ here

如果可以为包含的文件设置vars(即文件中所有任务可用的变量而不重复它们),那就更好了。

ansible
2个回答
0
投票

它看起来必须分成两部分才能工作:

- name: Set Terraform variables 1
  set_fact:
    terraform_base_url: "https://releases.hashicorp.com/terraform/{{ terraform_version }}"
    terraform_package_file: "terraform_{{ terraform_version }}_linux_amd64.zip"

- name: Set Terraform variables 2
  set_fact:
    terraform_package_url: "{{ terraform_base_url }}/{{ terraform_package_file }}"
    terraform_checksum_url: "{{ terraform_base_url }}/terraform_{{ terraform_version }}_SHA256SUMS"
    terraform_package_path: "/tmp/{{ terraform_package_file }}"

0
投票

如果以后不需要中间变量,可以使用var语句:

- name: Set Terraform variables
  set_fact:
    terraform_package_url: "{{ terraform_base_url }}/{{ terraform_package_file }}"
    terraform_checksum_url: "{{ terraform_base_url }}/terraform_{{ terraform_version }}_SHA256SUMS"
    terraform_package_path: "/tmp/{{ terraform_package_file }}"
  vars:
    terraform_base_url: "https://releases.hashicorp.com/terraform/{{ terraform_version }}"
    terraform_package_file: "terraform_{{ terraform_version }}_linux_amd64.zip"

此外,你很有可能在这里不需要set_fact。在任何级别使用vars部分(游戏,任务),或者将它们放在role\vars\main.yaml中作为角色。

© www.soinside.com 2019 - 2024. All rights reserved.