Ansible 使用循环将结果命令写入本地文件
Posted
技术标签:
【中文标题】Ansible 使用循环将结果命令写入本地文件【英文标题】:Ansible write result command to local file with loop 【发布时间】:2019-10-28 05:32:10 【问题描述】:我编写了 ansible-playbook 来收集来自许多网络设备的结果。下面的剧本工作正常。但是如果我必须用很多命令来收集结果。假设有 20 个命令,我必须创建许多任务来将结果写入我的剧本中的文件。
目前,我手动创建要写入日志文件的任务。以下是 3 个命令的示例。
- name: run multiple commands and evaluate the output
hosts: <<network-host>>
gather_facts: no
connection: local
vars:
datetime: " lookup('pipe', 'date +%Y%m%d%H') "
backup_dir: "/backup/"
cli:
host: " ansible_host "
username: <<username>>
password: <<password>>
tasks:
- sros_command:
commands:
- show version
- show system information
- show port
provider: " cli "
register: result
- name: Writing output
local_action:
module: lineinfile
dest: " backup_dir / inventory_hostname - datetime .txt"
line: " inventory_hostname :# show version\n result.stdout[0] "
create: yes
changed_when: False
- name: Writing output
local_action:
module: lineinfile
dest: " backup_dir / inventory_hostname - datetime .txt"
line: " inventory_hostname :# show system information\n result.stdout[1] "
create: yes
changed_when: False
- name: Writing output
local_action:
module: lineinfile
dest: " backup_dir / inventory_hostname - datetime .txt"
line: " inventory_hostname :# show port\n cmd_result.stdout[2] "
create: yes
changed_when: False
是否可以在一个任务中循环命令和结果?
请多多指教。
谢谢
【问题讨论】:
【参考方案1】:在以上三个任务中单独尝试这一项任务..
- name: Writing output
local_action:
module: lineinfile
dest: " backup_dir / inventory_hostname - datetime .txt"
line: " inventory_hostname :# show item.command \n cmd_result.stdout item.outnum "
create: yes
changed_when: False
with_items:
- command: version, outnum: [0]
- command: system information, outnum: [1]
- command: port, outnum: [2]
【讨论】:
嗨阿普,谢谢你的帮助我收到错误“致命:[Network1]:失败!=> “msg”:“模板字符串时模板错误:预期令牌'打印语句结束' , 拿到 ''。字符串: inventory_hostname :# show item.command \n cmd_result.stdout item.outnum "" 谢谢它对我很有帮助。【参考方案2】:下面的剧本对我有用
- name: Writing output
local_action:
module: lineinfile
dest: " backup_dir / inventory_hostname - datetime .txt"
line: " inventory_hostname :# show item.command \n item.cmdoutput"
create: yes
changed_when: False
with_items:
- command: "version", cmdoutput: " cmd_result.stdout[0] "
- command: "system information", cmdoutput: " cmd_result.stdout[1] "
- command: "port", cmdoutput: " cmd_result.stdout[2] "
【讨论】:
以上是关于Ansible 使用循环将结果命令写入本地文件的主要内容,如果未能解决你的问题,请参考以下文章
jmeter-beanshell本地文件写入多列数据--for循环