Ansible,如何在循环期间修改变量? [英] Ansible, How to modify a variable during a loop?

查看:44
本文介绍了Ansible,如何在循环期间修改变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是 Ansible 2.3.0.0 并且我已经在 Ansible 2.4.0.0 中进行了测试,获得了相同的结果.我的问题很简单.我有以下列表:

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

我想加密列表中每个项目的行值并将其保存在其结果属性中.我正在尝试使用此 Ansible 代码,但在任务分配中失败:

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

输出信息为:

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

我已经用其他可能性进行了测试,但我没有实现每个 item.results 都保存其加密值

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

推荐答案

最后,set_fact方法必须这样使用:

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

这篇关于Ansible,如何在循环期间修改变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆