只有在文件不存在的情况下,Ansible模块才会创建文件并写入一些数据。

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

我需要使用Anisble模块来检查文件是否存在,如果不存在,则创建它并向其中写入一些数据。

如果文件存在,那么检查我要写的内容是否存在于该文件中。

如果内容不存在,就把内容写进去。如果内容是存在的,那么就什么都不做。

我下面的演算本不能用。有什么建议吗?

- hosts: all
    tasks:
  - name: check for file
    stat:
      path: "{{item}}"
    register: File_status
    with_items:
      - /etc/x.conf
      - /etc/y.conf
  - name: Create file
    file:
      path: "{{item}}"
      state: touch
    with_items:
      - /etc/x.conf
      - /etc/y.conf
    when: not File_status.stat.exists
  - name: add content
    blockinfile:
      path: /etc/x.conf
      insertafter:EOF
      block: |
        mydata=something

你能帮我提供模块和条件,可以达到我想要的输出吗?

ansible
1个回答
1
投票

下面将。

  • 如果文件不存在,就创建文件,然后报告。changed
  • 如果不存在,则在文件末尾添加块,并报告。changed
    # BEGIN ANSIBLE MANAGED BLOCK
    mydata=something
    mydata2=somethingelse
    # END ANSIBLE MANAGED BLOCK
    
  • 如果内容发生变化,更新文件中任何地方的块,并报告 changed (见 marker 选择权 如果您在同一个文件中需要管理多个区块,并且不要忘记 {mark} 在那里,如果你改变它)。)
  • 如果该块在文件中的任何地方都是最新的,就什么都不要做,并报告说 ok.

请阅读 模块文件 更多信息

---
- name: blockinfile example
  hosts: localhost
  gather_facts:false

  tasks:
    - name: Update/create block if needed. Create file if not exists
      blockinfile:
        path: /tmp/testfile.conf
        block: |
          mydata=something
          mydata2=somethingelse
        create: true

0
投票

这里是实现你的要求的可能方法。

- hosts: localhost
  tasks:
  - name: Create file
    copy:
      content: ""
      dest: "{{item}}"
      force: no
    with_items:
      - /etc/x.conf
      - /etc/y.conf

  - name: add content
    blockinfile:
      path: "{{ item.file_name }}"
      insertafter: EOF
      block: |
        "{{ item.content }}"
    loop:
      - { file_name: '/etc/x.conf', content: 'mydata=something' }
      - { file_name: '/etc/y.conf', content: 'mydata=hey something' }
© www.soinside.com 2019 - 2024. All rights reserved.