LoginSignup
87
80

More than 5 years have passed since last update.

ansible-playbookのYAMLを読みやすくする工夫

Posted at

Ansibleは勉強中の身なので初歩的な内容かもしれませんが、チュートリアルを見ていて気になったので。

なるべくYAML構文で書く

モジュールのオプションをfoo=varみたいに書いている例をたまに見かけますが、横に長くなって読みにくいように思います。
YAMLの「>」(folded block構文)を使えば改行もできますが、そこまでやるなら素直にYAMLの構文で書いた方がいいと思いました。(素のYAMLの方がansible以外のプログラムでも扱いやすくなりますよね)

before

- name: configure sshd_config
  lineinfile: dest=/etc/ssh/sshd_config owner=root group=root mode=0600 backup=yes regexp="{{ item.regexp }}" line="{{ item.line }}" insertafter="{{ item.insertafter }}"
  with_items:
    - regexp: '^PasswordAuthentication'
      line: 'PasswordAuthentication no'
      insertafter: '#PasswordAuthentication'

after

- name: configure sshd_config
  lineinfile:
    dest: /etc/ssh/sshd_config
    owner: root
    group: root
    mode: "0600"
    backup: yes
    regexp: "{{ item.regexp }}"
    line: "{{ item.line }}"
    insertafter: "{{ item.insertafter }}"
  with_items:
    - regexp: '^PasswordAuthentication'
      line: 'PasswordAuthentication no'
      insertafter: '#PasswordAuthentication'

shellモジュールは「|」とargsで分解

たぶん一番お世話になる?shellモジュールは、shell: にシェルスクリプトの文字列を直接渡すスタイルなので、ちょっと変則的です。YAML記法にしたいなら、argsオプションを使います。

また、YAMLの「|」(literal block記法)を使うことで、複数行のシェルスクリプトもそのまま書くことができます。
「"」も「'」もシェルスクリプト中では多用するので、YAML上ではシェルスクリプトの文字列自体はクオートしない方がよいと思います。

before

- name: なにか実行
  shell: echo hoge >> somelog.txt; echo foo; echo baa chdir=somedir/

after


- name: なにか実行
  shell: |
    echo hoge >> somelog.txt
    echo foo
    echo baa
  args:
    chdir: somedir/
87
80
2

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
87
80