我需要在 Ansible 中创建一个包含单个事实内容的单个文件。我目前正在做这样的事情:
- template: src=templates/git_commit.j2 dest=/path/to/REVISION
我的模板文件如下所示:
{{ git_commit }}
显然,这样做更有意义:
- inline_template: content={{ git_revision }} dest=/path/to/REVISION
Puppet 提供了类似的东西。 Ansible 有办法做到这一点吗?
lineinfile模块的另一个选项(由udondan的answer给出)是使用copy模块并指定内容而不是Ansible主机本地的源。
示例任务如下所示:
- name: Copy commit ref to file
copy:
content: "{{ git_commit }}"
dest: /path/to/REVISION
我个人更喜欢这个而不是
lineinfile
,对我来说,lineinfile
应该是对已经存在的文件进行轻微的更改,而copy
是为了确保文件位于某个位置并且看起来完全像你想要的那样。它还具有处理多行的好处。
实际上,尽管我很想将其设为模板任务,并且只需将模板文件设置为:
"{{ git_commit }}"
此任务创建的:
- name: Copy commit ref to file
template:
src: path/to/template
dest: /path/to/REVISION
它更干净,并且它使用的模块正是它们的用途。
lineinfile
模块。
- lineinfile:
dest=/path/to/REVISION
line="{{ git_commit }}"
regexp=".*"
create=yes
lineinfile
模块通常用于确保文件中包含特定行。如果文件不存在,create=yes
选项将创建该文件。 regexp=.*
选项可确保在 git_commit
更改时不向文件添加内容,因为默认情况下它只是确保将新内容添加到文件中,而不是替换以前的内容。
这仅适用于您的文件中只有一行。如果您有更多行,这显然不适用于此模块。
这个问题似乎已经解决了。但是,如果模板文件有多个变量,即 json 文件,则可以使用带有内容参数的复制模块,并带有 lookup,即:
# playbook.yml
---
- name: deploy inline template
copy:
content: '{{ lookup("template", "inlinetemplate.yml.j2") }}'
dest: /var/tmp/inlinetempl.yml
# inlinetemplate.yml.j2
---
- name: {{ somevar }}
abc: def
如果需要将模板插入到已有文件中,可以通过lineinfile模块插入。
- name: Insert jinja2 template to the file
lineinfile:
path: /path/file.conf
insertafter: "after this line"
line: "{{ lookup('template', 'template.conf.j2') }}"