Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Get a variable value from another variable #50

Open
chemi0213 opened this issue Mar 19, 2020 · 1 comment
Open

Get a variable value from another variable #50

chemi0213 opened this issue Mar 19, 2020 · 1 comment

Comments

@chemi0213
Copy link

The example playbook is below:

$ cat test.yml
- hosts: localhost
  gather_facts: false
  tasks:
  - name: print
    debug:
      msg: "{{ policy }}"
    vars:
      name: checkpolicy_1
      policy: "{{ checkpolicy_1 | default('Policy_A') }}"

Goal:
When user specify checkpolicy_1 via --extra-var. the value of the variable "policy" will be "Policy_B". If not specify, will be "Policy_A"

However the number of checkpolicy might be a lot and vary, I want to write something like below, and achieve the same result:

$ cat test.yml
- hosts: localhost
  gather_facts: false
  tasks:
  - name: print
    debug:
      msg: "{{ policy }}"
    vars:
      name: checkpolicy_1
      policy: "{{ vars['name'] | default('Policy_A') }}"

Is it possible to do that?

@maple52046
Copy link

maple52046 commented May 26, 2021

vars is a Python dictionary, so you can use setdefault method to get data from vars with a default value.

E.g.:

- hosts: localhost
  vars:
    default_policy: "policy_a"

  tasks:
  - name: test
    debug:
      msg: "{{ vars.setdefault('checkpolicy_1', default_policy) }}"

  - name: set var
    set_fact:
      policy: "{{ vars.setdefault('checkpolicy_1', default_policy) }}"

  - name: test again
    debug:
      msg: "{{ policy }}"

However, setdefault didn't update vars in Ansible. So, I use set_fact to store the data into a new variable.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants