Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

ansible variable name is itself a variable. How to read? Need syntax

I have an ansible variable defined in a variable file like below:

cat myvarsfile.yml
newpass1: oldpass3
newpass2: oldpass9
newpass3: oldpass5
…

In my host playbook I load the variable file like below:

   - name: Load password variable file
     include_vars: "{{ playbook_dir }}/myvarsfile.yml"

When the user passes a parameter say newpass2 I should consider it as variable and load its value from the myvarsfile.yml file.

ansible-playbook -i /var/test.hosts test.yml -e mypass="newpass2"

I tried the below code considering old_pass is not defined; but it does not work.

   - debug:
       msg: "The old value for {{ mypass }} is {{ old_pass | default( vars[mypass] ) }}"

Getting the below error:

"msg": "The task includes an option with an undefined variable. The error was: 'dict object' has no attribute u'newpass2'

The error appears to have been in ….
question from:https://stackoverflow.com/questions/65940528/ansible-variable-name-is-itself-a-variable-how-to-read-need-syntax

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Assuming myvarsfile.yml as in your question, given this playbook:

- hosts: localhost
  gather_facts: false
  tasks:
    - include_vars: myvarsfile.yml

    - debug:
        msg: "given mypass={{ mypass }}, old password={{old_pass|default(vars[mypass])}}"

Running this command:

ansible-playbook playbook.yml -e mypass=newpass1

Produces:


PLAY [localhost] **********************************************************************************************************************************************************

TASK [include_vars] *******************************************************************************************************************************************************
ok: [localhost]

TASK [debug] **************************************************************************************************************************************************************
ok: [localhost] => {
    "msg": "given mypass=newpass1, old password=oldpass3"
}

PLAY RECAP ****************************************************************************************************************************************************************
localhost                  : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

I believe that's the behavior you're looking for.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...