68
65

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Ansible Playbookでdebugモジュールの出力を少し見やすく

Last updated at Posted at 2014-10-15

Ansible Playbookのデバッグ時の小ネタ。stdout_lines は便利だねという話。

課題

何か外部コマンドを実行し、結果を正しく受け取れているか表示するのに、debug モジュールを使います。

こんな感じで。

test.yml
--- # file: test.yml

- hosts: all
  gather_facts: False

  tasks:
    - command: ls -1 /etc/cron.daily/
      register: ls_result
      changed_when: False

    - debug: var=ls_result.stdout
      when: ls_result | success

しかし、実行すると、あんまり見やすくない表示になります。

$ ansible-playbook -i hosts test.yml

PLAY [all] ********************************************************************

TASK: [command ls -1 /etc/cron.daily/] ****************************************
ok: [localhost]

TASK: [debug var=ls_result.stdout] ********************************************
ok: [localhost] => {
    "ls_result.stdout": "0yum-daily.cron\nlogrotate\nman-db.cron"
}

PLAY RECAP ********************************************************************
localhost                  : ok=2    changed=0    unreachable=0    failed=0

理由は、改行文字がエスケープされてしまう から。

回避策

debugモジュールは、JSONの1要素を1行で表示するので、受け取った文字列をsplitすると1行毎に表示します。

コマンド出力では、最初から split してくれてる stdout_lines を利用できるので…

test2.yml
--- # file: test2.yml

- hosts: all
  gather_facts: False

  tasks:
    - command: ls -1 /etc/cron.daily/
      register: ls_result
      changed_when: False

    - debug: var=ls_result.stdout_lines # stdout => stdout_lines
      when: ls_result | success

そうすると得られる表示は、こんな感じに。

$ ansible-playbook -i hosts test2.yml

PLAY [all] ********************************************************************

TASK: [command ls -1 /etc/cron.daily/] ****************************************
ok: [localhost]

TASK: [debug var=ls_result.stdout_lines] **************************************
ok: [localhost] => {
    "ls_result.stdout_lines": [
        "0yum-daily.cron",
        "logrotate",
        "man-db.cron"
    ]
}

PLAY RECAP ********************************************************************
localhost                  : ok=2    changed=0    unreachable=0    failed=0

ちょっと便利。

68
65
0

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
68
65

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?