Ansibleで複数行のシェルスクリプトを実行する方法

ルガーデンフォックス:

現在、私は複数行にある場合にはるかに読みやすいansibleでシェルスクリプトを使用しています

- name: iterate user groups
  shell: groupmod -o -g {{ item['guid'] }} {{ item['username'] }} ....more stuff to do
  with_items: "{{ users }}"

Ansibleシェルモジュールで複数行スクリプトを許可する方法がわからない

ラーク:

Ansibleは、プレイブックでYAML構文を使用しています。YAMLにはいくつかのブロック演算子があります。

  • >折りたたみブロック演算子です。つまり、複数の行をスペースで結合します。次の構文:

    key: >
      This text
      has multiple
      lines
    

    に値This text has multiple lines\n割り当てますkey

  • |文字はリテラルブロック演算子です。これはおそらく、複数行のシェルスクリプトに必要なものです。次の構文:

    key: |
      This text
      has multiple
      lines
    

    に値This text\nhas multiple\nlines\n割り当てますkey

これは、次のような複数行のシェルスクリプトに使用できます。

- name: iterate user groups
  shell: |
    groupmod -o -g {{ item['guid'] }} {{ item['username'] }} 
    do_some_stuff_here
    and_some_other_stuff
  with_items: "{{ users }}"

注意点が1つあります。Ansibleはshellコマンドへの引数のぎこちない操作を行うため、上記は通常期待どおりに機能しますが、以下は機能しません。

- shell: |
    cat <<EOF
    This is a test.
    EOF

Ansibleは実際にテキストを先行スペースでレンダリングします。つまり、シェルはEOF行の先頭で文字列見つけることはありません次のcmdようなパラメーターを使用することで、Ansibleの役に立たないヒューリスティックを回避できます。

- shell:
    cmd: |
      cat <<EOF
      This is a test.
      EOF

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related