是否可以使用内联模板?
Is it possible to use inline templates?
我需要在 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
模块是可能的。
- lineinfile:
dest=/path/to/REVISION
line="{{ git_commit }}"
regexp=".*"
create=yes
lineinfile
模块通常用于确保特定行包含在文件中。如果文件不存在,create=yes
选项将创建该文件。 regexp=.*
选项确保您不会在 git_commit
更改时向文件添加内容,因为默认情况下它只会确保将新内容添加到文件中,而不是替换以前的内容。
这只适用于您的文件中只有一行。如果你有更多行,这显然不适用于此模块。
lineinfile module (as given by udondan's ) would be to use the 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
它更简洁,而且它使用的模块正是它们的用途。
这个问题似乎已经解决了。但是,如果模板文件有多个变量,即 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') }}"
我需要在 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
模块是可能的。
- lineinfile:
dest=/path/to/REVISION
line="{{ git_commit }}"
regexp=".*"
create=yes
lineinfile
模块通常用于确保特定行包含在文件中。如果文件不存在,create=yes
选项将创建该文件。 regexp=.*
选项确保您不会在 git_commit
更改时向文件添加内容,因为默认情况下它只会确保将新内容添加到文件中,而不是替换以前的内容。
这只适用于您的文件中只有一行。如果你有更多行,这显然不适用于此模块。
lineinfile module (as given by udondan's
示例任务类似于:
- 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
它更简洁,而且它使用的模块正是它们的用途。
这个问题似乎已经解决了。但是,如果模板文件有多个变量,即 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') }}"