2017-07-28 120 views
1

我寫了一個讀取兩個文件內容的劇本。第一個負責動態保存具有協議CDP的交換機接口。是否有可能在變量中更改變量的值?

example.cdp

0/0 
14/0 

第二個(.CFG),是一個文件還動態地包含一堆接口,我需要使用Cisco命令推到設備「關斷「來測試我的主/備份環境。如果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「cdp」。接口有符號「/」,這是在「sed」命令中使用,我應該反斜槓這個使用ansible來解決我的問題。有沒有辦法打開一個變量,並在其上做一些regsub?

回答

1

sed可以使用任何字符作爲正則表達式標記生成器,這麼快就解決您的問題,(使用#字符實例)變成:

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

在我的印象模板是寫一個更好的辦法儘管你的任務。

+0

謝謝@GUIDO。我從來沒有聽說過,我可以使用任何符號作爲您向我展示的標記。有用! –

相關問題