下面是一个示例代码,演示了如何使用Ansible读取文件并将变量连接到每一行:
---
- name: Read file and concatenate variable to each line
hosts: localhost
tasks:
- name: Read file
slurp:
src: /path/to/file.txt
register: file_contents
- name: Convert file contents to string
set_fact:
file_string: "{{ file_contents.content | b64decode | decode('utf-8') }}"
- name: Define variable
set_fact:
variable: "Variable Value"
- name: Concatenate variable to each line
set_fact:
modified_lines: "{{ file_string.split('\n') | map('regex_replace', '(.+)', '\\1 - {{ variable }}') | list }}"
- name: Print modified lines
debug:
var: modified_lines
在这个示例中,我们首先使用slurp
模块读取文件的内容,并将其存储在file_contents
变量中。然后,我们使用set_fact
模块将文件内容转换为字符串,并存储在file_string
变量中。
接下来,我们使用set_fact
模块定义一个名为variable
的变量,并将其设置为"Variable Value"。
然后,我们使用set_fact
模块将file_string
中的每一行与variable
连接起来,并将结果存储在modified_lines
变量中。在这里,我们使用split
过滤器将file_string
拆分为行的列表,然后使用map
过滤器和regex_replace
过滤器将variable
连接到每一行,最后使用list
过滤器将结果转换为列表。
最后,我们使用debug
模块打印修改后的行。
请注意,上述示例假设文件内容是Base64编码的。如果文件内容不是Base64编码的,可以直接使用file_contents.content
代替file_contents.content | b64decode | decode('utf-8')
。
此外,还可以根据实际需求进行修改和调整。