最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to use ansible.builtin.copy with content and ensure resulting file ends with a new line? - Stack Overflow

programmeradmin3浏览0评论

I am ensuring a file with a specific content is present on a Linux machine.

Neither of the tasks below resulted in a file that ends with with a newline:

- name: Write a file with content
  ansible.builtin.copy:
    content: "{{ files_content }}"
    dest: /tmp/foo.txt

- name: Write a file with content
  ansible.builtin.copy:
    content: "{{ files_content }}\\n"
    dest: /tmp/bar.txt

- name: Write a file with content
  ansible.builtin.copy:
    content: "{{ files_content }}\n"
    dest: /tmp/foobar.txt"

How can I make sure that the file ends with a newline character?

If there is no other way I guess I could use the task below.

- name: Write a file with content
  ansible.builtin.copy:
    content: | 
             {{ files_content }}
    dest: /tmp/foobar.txt"

But I am curious if I have to.

I am ensuring a file with a specific content is present on a Linux machine.

Neither of the tasks below resulted in a file that ends with with a newline:

- name: Write a file with content
  ansible.builtin.copy:
    content: "{{ files_content }}"
    dest: /tmp/foo.txt

- name: Write a file with content
  ansible.builtin.copy:
    content: "{{ files_content }}\\n"
    dest: /tmp/bar.txt

- name: Write a file with content
  ansible.builtin.copy:
    content: "{{ files_content }}\n"
    dest: /tmp/foobar.txt"

How can I make sure that the file ends with a newline character?

If there is no other way I guess I could use the task below.

- name: Write a file with content
  ansible.builtin.copy:
    content: | 
             {{ files_content }}
    dest: /tmp/foobar.txt"

But I am curious if I have to.

Share Improve this question edited Jan 20 at 20:32 U880D 12k6 gold badges32 silver badges63 bronze badges asked Jan 20 at 19:09 HumanHuman 8561 gold badge12 silver badges33 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

Q: "How can I make sure that the file ends with a newline character?"

A: Just add the character to the variable content, the string during Templating (Jinja2).

A minimal example playbook

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

  vars:

    CONTENT: 'test'

  tasks:

    - name: Write a file with content
      ansible.builtin.copy:
        content: "{{ CONTENT ~ '\n' }}"
        dest: test.txt

will result into an outfile test.txt with the requested content.

$ cat test.txt
test
$
发布评论

评论列表(0)

  1. 暂无评论