是否有可能在ansible中更改变量的值?

时间:2017-07-28 21:04:01

标签: sed ansible

我写了一本阅读两个文件内容的剧本。第一个负责动态保存具有协议CDP的交换机接口。

example.cdp

0/0
14/0

第二个(.cfg),是一个文件,它还动态地包含了一堆我需要使用cisco命令推送到设备的接口" shutdown"测试我的主/备份环境。如果exam​​ple.cdp的接口在这里,我需要删除它们,因为我不能丢失与该设备的通信,因为管理是带内的。

example.cfg

 interface FastEthernet0/0
 shutdown
 interface FastEthernet1/0
 shutdown
 interface FastEthernet2/0
 shutdown
 interface FastEthernet2/1
 shutdown
 ...
 interface FastEthernet14/0
 shutdown

剧本

 - name: Looping file
   debug:
     msg: "{{ item }}"
   register: items
   with_file:
     - ~/ANSIBLE/{{ inventory_hostname }}.cfg
 - debug: var=items.results[0].item

 - name: capturing interfaces with cdp
   raw: egrep '[0-9]+\/[0-9]+ ' -o ~/ANSIBLE/{{ inventory_hostname }}.cdp
   register: cdp
 - debug: var=cdp.stdout_lines

 - set_fact:
     cdp: "{{cdp.stdout_lines}}"
 - debug: var=cdp

 - name: Removing interfaces with cdp
   raw: sed 's/interface FastEthernet{{item}}//' ~/ANSIBLE/{{ inventory_hostname }}.cfg
   with_items:
     - "{{cdp}}"
   register: items
 - debug: var=items 

 - name: Applying The Shutdown Template
   ios_config:
     lines:
       - "{{ items.results[0].item }}" 
     provider: "{{cli}}"
   register: shut1
 - debug: var=shut1
   tags: shut1

运行剧本:

 <169.255.0.1> EXEC sed 's/interface FastEthernet0/0 //' ~/ANSIBLE   /169.255.0.1.cfg
 failed: [169.255.0.1] (item=0/0 ) => {
"changed": true, 
"failed": true, 
"item": "0/0 ", 
"rc": 1, 
"stderr": "sed: -e expression #1, char 30: unknown option to `s'\n", 
"stdout": "", 
"stdout_lines": []
}
  <169.255.0.1> EXEC sed 's/interface FastEthernet14/0 //' ~/ANSIBLE/169.255.0.1.cfg
 failed: [169.255.0.1] (item=14/0 ) => {
"changed": true, 
"failed": true, 
"item": "14/0 ", 
"rc": 1, 
"stderr": "sed: -e expression #1, char 31: unknown option to `s'\n", 
"stdout": "", 
"stdout_lines": []
}

正如您所看到的,问题是var&#34; cdp&#34;的内容。接口的符号为&#34; /&#34;,用于&#34; sed&#34;命令,我应该反复使用ansible来解决我的问题。有没有办法打开变量并在其上制作一些regsub?

1 个答案:

答案 0 :(得分:1)

sed可以使用任何字符作为正则表达式标记生成器,因此快速解决您的问题,将其转换为(例如使用#字符):

sed 's#interface FastEthernet{{item}}##' ~/ANSIBLE/{{ inventory_hostname }}.cfg

我觉得模板化是一种更好的方式来编写你的任务。

相关问题