繁体   English   中英

Ansible 无法将变量值分配给另一个变量

[英]Ansible Unable to assign variable the value to another variable

如果用户没有传递dest_path参数或者dest_path为 EMPTY 即仅包含空格,则dest_path应该与source_file值相同。

以下是我的剧本:

---

- name: "Play 1"

  hosts: localhost
  any_errors_fatal: false
  gather_facts: false

  tasks:

   - set_fact:
       dest_path: "{{ dest_path | default(source_file) }}"

   - set_fact:
       dest_path: "{{ source_file }}"
     when: dest_path | length == 0

   - debug:
       msg: "DESTINATION PATH IS: {{ dest_path }} and the SOURCE PATH is: {{ source_file }}"

这就是你运行这个剧本的方式:

ansible-playbook -i /web/playbooks/allmwhosts.hosts /web/playbooks/test.yml -e '{ source_file: /web/bea_apps/CURRENT }' -e dest_path=

在上面的示例中,当用户没有为dest_path指定任何值时,我期望dest_path应该是source_file/web/bea_apps/CURRENT

但是,正如您在下面的 output 中看到的那样,情况并非如此:

Output:

PLAY [Play 1] *******************

TASK [set_fact] **************************************************************************************
ok: [localhost]

TASK [set_fact] **************************************************************************************
ok: [localhost]

TASK [debug] *****************************************************************************************
ok: [localhost] => {
    "msg": "DESTINATION PATH IS:  and the SOURCE PATH is: /web/bea_apps/CURRENT"
}

PLAY RECAP *******************************************************************************************
localhost                  : ok=3    changed=0    unreachable=0    failed=0

你能建议吗?

您作为参数传递的额外变量将覆盖 set_fact 变量 dest_path 中的变量。 下面是工作代码。 在 set_fact 而不是 dest_path 我用路径替换。

---
- name: "Play 1"
  hosts: localhost
  any_errors_fatal: false
  gather_facts: false
  tasks:
   - set_fact:
       path: "{{ source_file }}"
     when: (dest_path is not defined) or (dest_path | length == 0)

   - set_fact:
       path: "{{ dest_path }}"
     when: (dest_path is defined) or (dest_path | length != 0)

   - debug:
       msg: "DESTINATION PATH IS: {{ path }} and the SOURCE PATH is: {{ source_file }}"

输出

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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