简体   繁体   中英

Ansible Unable to assign variable the value to another variable

If the user does not pass dest_path parameter or if dest_path is EMPTY ie contains only whitespaces then dest_path should be the same as source_file value.

Below is my playbook:

---

- 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 }}"

This is how you run this playbook:

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

In the above example when the user does not specify any value for dest_path I m expecting dest_path should be source_file ie /web/bea_apps/CURRENT

However, as you can see in the output below that is not the case:

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

Can you please suggest?

The extra variable that you pass as parameter is overriding the variable in set_fact variable dest_path. Below is the working code. In set_fact instead of dest_path I replaced with 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 }}"

输出

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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