0
votes
  • I am writing a playbook task to get the IP address from the output and store the value and use it for other tasks.

Ansible playbook

  • name: Extract the secondary router ipsec tunnel address hosts: secondary gather_facts: false connection: local tags:
    • "sec_tunnel_ip" tasks:
    • name: Extract Tunnel1 ipsec interface address ios_command: commands: "sh ip int br | sec Tunnel1" register: save_tunn_out
    • debug: msg: "{{save_tunn_out.stdout}}"

I am getting the output like below:

ok: [172.16.12.1] => { "msg": [ "Tunnel1 172.16.121.54 YES manual up up \nTunnel100 10.0.0.101 YES manual up up" ] }

But I want to extract the first ip interface output(for tunnel1) like below, and store it in a variable.

172.16.121.54

I am not sure how to get it without regex and store it on the variable.

Please help!

1

1 Answers

0
votes

If you don't want to use regex, which would be your best bet, you have to rely on splitting the string.

Assuming it will always be after Tunnel1 and followed by a space, you can do it like this.

  - name: Extract Tunnel1 ipsec interface address
    set_fact:
      save_tunn_out: "Tunnel1 172.16.121.54 YES manual up up \nTunnel100 10.0.0.101 YES manual up up"
  
  - name: Extract IP address
    debug:
      var: save_tunn_out.split("Tunnel1 ")[1].split(" ")[0]

Which gives you the desired output

ok: [localhost] => {
    "save_tunn_out.split(\"Tunnel1 \")[1].split(\" \")[0]": "172.16.121.54"
}

To store in a variable afterward, you can use set_fact like this

  - name: Store in a variable
    set_fact:
      ip_address: "{{save_tunn_out.split('Tunnel1 ')[1].split(' ')[0]}}"

  - name: Debug variable
    debug:
      msg: "Ip address is : {{ip_address}}"   

Output :

ok: [localhost] => {
    "msg": "Ip address is : 172.16.121.54"
}