【问题标题】:Find file and add lines ansible查找文件并添加行 ansible
【发布时间】:2021-07-12 11:43:44
【问题描述】:

如何找到给定文件,然后在其末尾添加几行?现在我有类似的东西

---
- name: Ansible find file and add some lines
  hosts: localhost
  tasks:
    - name: find file
      find:
        paths: /etc
        patterns: 'somefile.conf'

Ansible 找到了那个文件。下一步是什么?

【问题讨论】:

  • 既然已经有了路径,为什么还要找文件呢?只需使用lineinfile。如果您有问题edit 提出问题并提出minimal reproducible example
  • 这个playbook要经过很多服务器,不知道路径会不会像“/etc/thisFile”一样

标签: ansible yaml


【解决方案1】:

给定文件

shell> cat etc/somefile.conf
line1
line2

注册查找模块的结果并选择路径

- name: Ansible find file and add some lines
  hosts: localhost
  tasks:
    - name: find file
      find:
        paths: etc
        patterns: 'somefile.conf'
      register: result
    - debug:
        msg: "{{ result.files|map(attribute='path')|list }}"

给出文件列表(可能还有更多)

  msg:
  - etc/somefile.conf

使用lineinfile添加行

    - lineinfile:
        path: "{{ item }}"
        line: "last line"
        insertafter: EOF
      loop: "{{ result.files|map(attribute='path')|list }}"

给予

shell> cat etc/somefile.conf
line1
line2
last line

下一个选项是 blockinfile。例如

    - blockinfile:
        path: "{{ item }}"
        block: |
          last line -2
          last line -1
          last line
        insertafter: EOF
      loop: "{{ result.files|map(attribute='path')|list }}"

给予

shell> cat etc/somefile.conf
line1
line2
# BEGIN ANSIBLE MANAGED BLOCK
last line -2
last line -1
last line
# END ANSIBLE MANAGED BLOCK

【讨论】:

    猜你喜欢
    • 2013-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多