【问题标题】:Ansible: copying the value from one file to other based on a conditionAnsible:根据条件将值从一个文件复制到另一个文件
【发布时间】:2020-06-28 13:22:46
【问题描述】:

我已经尝试了很多方法来在 Ansible 中完成这项工作,但我仍然卡住了:/

所以,我必须从一个文件中读取凭据(用户名和密码):

file1: (dest: /home/usr/Desktop/file1.txt)

#this is a cred file
number= 8910334
user= xyz  #(this maybe username=xyz also)
password= abc

读取文件内容后,我需要根据以下内容在找到带有“用户”和“密码”的 ('=') 符号的位置进行拆分:

用户密钥=用户

用户价值= xyz

密码键=密码

密码值= abc

file2: (dest: /home/usr/Desktop/file2.txt)

#Hi, I need credentials
school= spsg
user =         #(this value may be blank or may be filled with some other entry or it may be xyz.user.name=   )
password=    #(this value may be blank or may be filled with some other entry or it may be xyz.password.value= )

现在,在文件 2 中,我希望将用户 =________ 值和密码 =________ 值替换为从文件 1 中提取的用户值和密码值。 (用户和密码的行号可能会有所不同,所以不要将行号分别固定为[1]和[2])

另外,除了file2,还有一些文件需要file1中的值,所以如果这个任务用循环来完成会更好。

请建议我使用可能的 YAML 代码来完成这项工作。谢谢:)

【问题讨论】:

    标签: loops split ansible


    【解决方案1】:

    如果文件不是本地的fetch 它。然后下面的任务

      vars:
        file_name: file1.txt
      tasks:
        - set_fact:
            my_vars: "{{ my_vars|default([]) +
                         [{'key': item, 'value': my_value}] }}"
          loop: "{{ lookup('pipe', my_cat).splitlines()|
                    select('match', my_regex_comment)|
                    map('regex_replace', my_regex, my_replace)|
                    map('trim')|
                    list }}"
          vars:
            my_regex_comment: '^(?!\s*\#).*$'  # filter commented line
            my_regex_any_comment: '(\s*\#.*)'  # match comment in value
            my_regex: '^(.*?)=(.*)$'           # match key and value
            my_replace: '\1'                   # replace with key
            my_replace_empty: ""               # delete
            my_cat: "{{ 'cat ' ~ file_name }}"
            my_ini: "{{ item ~ ' type=properties file=' ~ file_name }}"
            my_value: "{{ lookup('ini', my_ini)|
                          regex_replace(my_regex_any_comment, my_replace_empty) }}"
        - debug:
            var: my_vars
    

    给予

      my_vars:
      - key: number
        value: '8910334'
      - key: user
        value: xyz
      - key: password
        value: abc
    

    使用template 写入文件。例如下面的任务和模板

        - template:
            src: file2.txt.j2
            dest: file2.txt
    
    shell> cat file2.txt.j2
    {% for item in my_vars %}
    {{ item.key }}={{ item.value }}
    {% endfor %}
    

    shell> cat file2.txt
    number=8910334
    user=xyz
    password=abc
    

    下一个选项是使用lineinfile 来添加或替换循环中的变量

        - lineinfile:
            path: file2.txt
            regex: '^\s*{{ item.key }}\s*=(.*)$'
            line: '{{ item.key }}={{ item.value }}'
          loop: "{{ my_vars }}"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-30
      • 1970-01-01
      • 2011-08-22
      相关资源
      最近更新 更多