LoginSignup
10
11

More than 5 years have passed since last update.

Ansibleでtelnetする

Posted at

Ansibleでtelnetする

通常、Ansibleでは被管理ホストに対して、sshでアクセスし制御しますが

「どうしてもsshではなくtelnetで入って任意のコマンドを実行したい」

ということがあると思います。

本記事ではAnsible2.4から入ったtelnetモジュール利用し、ciscoの装置に対してtelnetでログインしコマンドを実行、ログに残します。

実行環境

Item Value
ansible version 2.4.1.0
被管理ホスト telnet可能なcisco機器

ファイル構成

.
├── cisco.yml
├── hosts
└── roles
    └── cisco
        ├── tasks
        │   └── main.yml
        └── vars
            └── main.yml

各ファイルの内容

  • hostsとplaybook
    まずはhostとplaybook本体のcisco.yml。
    sshでは繋げない前提なのでgather_factsをFalseにしています。
[R1]
192.168.56.2
cisco.yml
---
- hosts: R1
  gather_facts: False
  roles:
    - cisco
  • roles/cisco/tasks/main.ymlとroles/cisco/vars/main.yml
    基本的にtelnetモジュールでべた書きです。
    コマンドの出力に#や>が入りそうな場合はpromptsに{{ inventory_hostname }}等を入れるといいでしょう。
    telnetの出力をcommand_resultとして保存、local_actionで管理ホスト(ansibleコマンド実行ホスト)側にログを出力しています。
    command_result.output[3]としているのはshow runが4番目に実行されているからです。この部分を変更してあげれば別のコマンドや続けてのログ出力が可能です。
roles/cisco/tasks/main.yml
---
- name: show run
  telnet:
    user: cisco
    password: cisco
    login_prompt: "Username: "
    prompts:
      - "[>|#]|Password: "
    command:
      - terminal length 0
      - enable
      - cisco
      - show run
  changed_when: False
  register: command_result

- name: debug
  debug:
    var: command_result.output

- name: log export
  local_action:
    module: copy
    owner: nohara
    group: nohara
    mode: 0644
    dest: "{{ log_dir }}/show_run.log"
    content: "{{ command_result.output[3] }}"
  changed_when: False
roles/cisco/vars/main.yml
---
log_dir: "/home/nohara"

  • 出力されるログ
    一行目にコマンドが入ってしまっていますが、まぁいいでしょう。。
show run
Building configuration...

Current configuration : 895 bytes
!
version 12.4
service timestamps debug datetime msec
service timestamps log datetime msec
no service password-encryption
!
hostname R1
---snip---

失敗談

  • show runの出力にpromptと判定される文字列(上記だと#とか)が入っており出力がおかしい
  • gather_facts: Falseとしていなくて、gather_factsで止まる

    困ったときはパケットキャプチャ!!!

参考URL

Ansible telnet

10
11
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
11