Ansible, How to modify a variable during a loop?

让人想犯罪 __ 提交于 2021-02-10 19:38:23

问题


I am using Ansible 2.3.0.0 and I have tested in Ansible 2.4.0.0, obtaining the same result. My problem is simple. I have the following list:

vars:
     password_text_to_encrypt:
          - { line: "{{truststore_pass }}" , result: }
          - { line: "{{ keystore_pass }}" , result: }
          - { line: "{{ gp_pass }}" , result: }
          - { line: "{{ datasource_password }}" , result: }
          - { line: "{{ server_password }}" , result: }
          - { line: "{{ sftp_password }}" , result: }
          - { line: "{{ db_userpassword }}" , result: }
     roles:
       - basic_role

I want to encrypt the line value for every item of the list and save it in its results attribute. I am trying with this Ansible code but it fails in the task assignation:

- name: "Encrypt password"
  uri: 
     url: http://122.81.10.1:8910/Cloud/encrypt
     method: POST
     body: "{{ item.line}}"
     return_content: yes
  register: "r"
  with_items:
    - "{{password_text_to_encrypt}}"


- name: "Replace var in result"
  set_fact: item['0']['result']="{{ item.1.content}}"
    #replace: '{{ item.1.content}}'
  with_nested:
    - "{{password_text_to_encrypt}}"
    - "{{r.results}}"
  when: item.1.item.line==item.0.line

- name: "print Results"
  debug: 
      msg: "The Item is :{{item.result}}"
  with_items: 
    - "{{password_text_to_encrypt}}"

The output message is:

"msg": "The variable name 'item['0']['result']' is not valid. Variables must start with a letter or underscore character, and contain only letters, numbers and underscores."}

I have tested with other possibilities but I do not achieve that every item.results save its encrypted value


回答1:


Finally, the set_fact method must be used in this way:

Instead of using the same variable, I have created another one with the same structure.

- name: "Replace var in result"
  set_fact: 
    encrypted: "{{encrypted|default([]) + [ {'line': item.1.content, 'regexp': item.0.regexp} ]}}"
  with_nested:
    - "{{password_text_to_encrypt}}"
    - "{{r.results}}"
  when: item.1.item.line==item.0.line

But I cannot rewrite a field inside a object



来源:https://stackoverflow.com/questions/47882281/ansible-how-to-modify-a-variable-during-a-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!