Ansible readfile and concatenate a variable to each line

别来无恙 提交于 2020-12-15 05:29:58

问题


Hi I have a file with list of filenames .I want to read each line and add a variable {{version}} to the end and pass it to another task which will download the artifact .

MY_File

cat file/branches.txt
mhr-
mtr-
tsr

I want to get each line add {{version}} to it

mhr-1.1-SNAPSHOT
mtr-1.1-SNAPSHOT
tsr-1.1-SNAPSHOT

I couldn't get the file names and append them. below is a failed attempt by me .

---
- name: get file names
  shell: echo {{item}}{{version}}
  register: result
  with_lines: cat files/branches.txt

- include_tasks: 2main.yml
  with_items: "{{result.results}}"


回答1:


I think what you need a new variable which contains text like mhr-1.1-SNAPSHOT depending on the source file. You can use set_fact to achieve this.

Example:

vars:
  file_versions: []
  version: "1.1-SNAPSHOT"

tasks:
- set_fact:
    file_versions: "{{ file_versions }} + [ '{{ item }}{{ version }}' ]"
  with_lines: cat file/branches.txt
- debug:
    msg: "{{ item }}"
  with_items: "{{ file_versions }}"
- include_tasks: 2main.yml
  with_items: "{{ file_versions }}"

Gives below debug output:

TASK [debug] ************************************************************************************************************************
ok: [localhost] => (item=mhr-1.1-SNAPSHOT) => {
    "msg": "mhr-1.1-SNAPSHOT"
}
ok: [localhost] => (item=mtr-1.1-SNAPSHOT) => {
    "msg": "mtr-1.1-SNAPSHOT"
}
ok: [localhost] => (item=tsr-1.1-SNAPSHOT) => {
    "msg": "tsr-1.1-SNAPSHOT"
}



回答2:


In a nutshell:

---
- name: append version to names found in a local text file line by line
  hosts: localhost
  gather_facts: false

  vars:
    # This is the version we want to append
    version: 1.1-SNAPSHOT

    # This is the file on local controller containing the names
    my_file: /tmp/my_file.txt

    # This var will contain a list of each name in file with appended version
    file_version: "{{ lookup('file', my_file).splitlines() | map('regex_replace', '^(.*)$', '\\g<1>' + version) | list }}"

 
  tasks:
    - name: Show the result
      debug:
        var: file_version

    - name: Loop on var with an include (the passed var is item in this case)
      include_tasks: some_other_tasks_working_on_item.yml
      loop: "{{ file_version }}"



来源:https://stackoverflow.com/questions/65180477/ansible-readfile-and-concatenate-a-variable-to-each-line

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