Ansible lineinfile 在每行前面添加一个字符串并转换为单行

问题描述 投票:0回答:1

我使用 sed 在行前面添加一个字符串,然后使用 xargs 保持在单行中。我怎样才能在ansible中实现同样的目标?

例如:我有一个如下文件

[root@test]#猫tt

bb

抄送

dd

使用 sed , sed -e 's/^/11 /' tt |xargs

11 aa 11 bb 11 cc 11 dd

如何使用ansible获取这个

sed ansible
1个回答
0
投票

因为复杂的数据操作

...虽然不建议使用 Ansible 作为数据处理/操作工具...

好像是预处理

...使用

sed
在行前添加字符串,然后使用
xargs
保持单行

是最好的方法。因此,

如何使用 Ansible 获取此内容?

可能不推荐。然而,对于

test.file

A
BB
CCC
DDDD
EEEEE
FFFFFF
GGGGGGG

一个最小示例剧本

---
- hosts: localhost
  become: false
  gather_facts: false

  tasks:

  - name: Prefix lines of file (shell)
    shell:
      cmd: sed -e 's/^/1 /' test.file | xargs
    register: result

  - debug:
      var: result

  - name: Prefix lines of file (Ansible)
    slurp:
      src: test.file
    register: test_file

  - name: Prefix lines of file (Ansible)
    debug:
      msg: "{{ [prefix_argument] | product(test_list) | map('join') | list | join(' ') }}"
    vars:
      test_list: "{{ test_file['content'] | b64decode | split }}"
      prefix_argument: '1 '

将产生

的输出
TASK [Prefix lines of file (shell)] *************************
changed: [localhost]

TASK [debug] ************************************************
ok: [localhost] =>
  result:
    changed: true
    cmd: sed -e 's/^/1 /' test.file | xargs
    delta: '0:00:00.017802'
    end: '2023-11-24 08:24:04.478318'
    failed: false
    msg: ''
    rc: 0
    start: '2023-11-24 08:24:04.460516'
    stderr: ''
    stderr_lines: []
    stdout: 1 A 1 BB 1 CCC 1 DDDD 1 EEEEE 1 FFFFFF 1 GGGGGGG
    stdout_lines:
    - 1 A 1 BB 1 CCC 1 DDDD 1 EEEEE 1 FFFFFF 1 GGGGGGG

TASK [Prefix lines of file (Ansible)] **********************
ok: [localhost]

TASK [Prefix lines of file (Ansible)] **********************
ok: [localhost] =>
  msg: 1 A 1 BB 1 CCC 1 DDDD 1 EEEEE 1 FFFFFF 1 GGGGGGG

PLAY RECAP *************************************************
localhost                  : ok=4    changed=1    

Playbook run took 0 days, 0 hours, 0 minutes, 1 seconds
============================================================
Prefix lines of file (shell) ------------------------- 0.47s
Prefix lines of file (Ansible) ----------------------- 0.39s
Prefix lines of file (Ansible) ----------------------- 0.12s
debug ------------------------------------------------ 0.08s

类似问答

  • 如何在 Ansible 中的每个列表元素之前添加参数?
© www.soinside.com 2019 - 2024. All rights reserved.