Ansible-将多行输出写入文件 [英] Ansible - Write multiple line output to file
问题描述
我正在使用ansible从远程节点收集信息,然后将使用此信息来更新相关的RPM.
I am using ansible to gather information from remote nodes and will then use this information to update relevant RPMs.
我遇到的问题是各种应用程序的集合版本号并将它们写入文件.
The issue I am having is collection version number of various applications and writing them to a file.
剧本:
---
- name: Check Application Versions
hosts: kubernetes
tasks:
- name: Check K8S version.
shell: kubectl --version
register: k8s_version
- debug: msg="{{ k8s_version.stdout }}"
库存文件:
[kubernetes]
172.29.219.102
172.29.219.105
172.29.219.104
172.29.219.103
输出:
TASK [debug] *******************************************************************
ok: [172.29.219.102] => {
"msg": "Kubernetes v1.4.0"
}
ok: [172.29.219.103] => {
"msg": "Kubernetes v1.4.0"
}
ok: [172.29.219.105] => {
"msg": "Kubernetes v1.4.0"
}
ok: [172.29.219.104] => {
"msg": "Kubernetes v1.4.0"
}
以上部分很简单且有效.现在我想将输出写入文件.
The above portion is simple and works. Now I want to write the output to file.
现在我正在尝试将此信息写入文件.我想要类似的东西:
Now im trying to write this information to a file.I want something like:
Kubernetes v1.4.0 Kubernetes v1.4.0 Kubernetes v1.4.0 Kubernetes v1.4.0
Kubernetes v1.4.0 Kubernetes v1.4.0 Kubernetes v1.4.0 Kubernetes v1.4.0
所以我添加了以下行:
- local_action: copy content={{ k8s_version.stdout_lines }} dest=/tmp/test
我的/tmp/test
看起来像:
# cat /tmp/test
["Kubernetes v1.4.0"]
这里只有一个值.
那时我试图做一些不同的事情.
I tried to do something different then.
- local_action: lineinfile dest=/tmp/foo line="{{ k8s_version.stdout }}" insertafter=EOF
结果是:
# cat /tmp/foo
Kubernetes v1.4.0
我试图弄清楚为什么我只看到一个值,而我应该看到清单文件中每个节点的版本.我究竟做错了什么?
Im trying to figure out why I only see one value whereas I should see the versions of every node in my inventory file. What am I doing wrong?
推荐答案
我在做什么错了?
What am I doing wrong ?
lineinfile
模块不执行向文件添加行"操作,而是确保文件中存在给定的行.如果所有目标节点都具有相同的版本,则不会多次添加同一行.
lineinfile
module does not perform the action "add a line to a file", instead it ensures a given line is present in the file. If all your target nodes have the same version, it won't add the same line multiple times.
另一方面,copy
模块正在覆盖文件.
On the other hand, copy
module was overwriting the file.
如果需要注册所有主机的值,则可以例如创建一个模板,该模板将循环遍历kubernetes
组中的主机:
If you need to register values for all hosts, you can for example create a template which will loop over hosts in the kubernetes
group:
- copy:
content: "{% for host in groups.kubernetes %}{{ hostvars[host].k8s_version }}\n{% endfor %}"
dest: /tmp/test
delegate_to: localhost
run_once: true
另一种方法是从hostvars
中使用map
提取值,但是鉴于您只想从kubernetes
主机组中提取值,我不确定它是否更漂亮.并且在模板中包含for
可使您轻松添加主机名.
Another way would be to extract the values with map
from hostvars
, but given you want the values from kubernetes
host group only, I'm not sure it would be prettier. And having a for
in the template allows you to easily add host names.
这篇关于Ansible-将多行输出写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!