developer tip

Ansible에서 여러 줄 셸 스크립트를 수행하는 방법

optionbox 2020. 8. 28. 07:22
반응형

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 }}"

한 가지주의 할 점이 있습니다. Ansible은 shell명령 에 대한 인수의 버벅 거림 조작을 수행하므로 위의 내용은 일반적으로 예상대로 작동하지만 다음은 작동하지 않습니다.

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

Ansible은 실제로 해당 텍스트를 선행 공백으로 렌더링합니다. 즉, 셸이 EOF줄 시작 부분에서 문자열 찾지 못함을 의미합니다 . 다음 cmd과 같은 매개 변수 를 사용하여 Ansible의 도움이되지 않는 휴리스틱 스를 피할 수 있습니다 .

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

https://support.ansible.com/hc/en-us/articles/201957837-How-do-I-split-an-action-into-a-multi-line-format-

YAML 라인 연속을 언급합니다.

예 (ansible 2.0.0.2로 시도) :

---
- hosts: all
  tasks:
    - name: multiline shell command
      shell: >
        ls --color
        /home
      register: stdout

    - name: debug output
      debug: msg={{ stdout }}

셸 명령은 다음과 같이 한 줄로 축소됩니다. ls --color /home


EOF 구분 기호 앞에 공백을 추가하면 cmd를 피할 수 있습니다.

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

참고 URL : https://stackoverflow.com/questions/40230184/how-to-do-multiline-shell-script-in-ansible

반응형