Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...