Ansible Shell 모듈

AnsibleBeginner
지금 연습하기

소개

이 랩에서는 Ansible Shell 모듈을 사용하여 원격 호스트에서 셸 명령을 실행하는 방법을 배우게 됩니다. Shell 모듈은 기존 Ansible 모듈에서 다루지 않는 셸 명령을 실행해야 하거나 실행에 대한 더 많은 유연성과 제어가 필요한 경우 유용합니다.

이것은 가이드 실험입니다. 학습과 실습을 돕기 위한 단계별 지침을 제공합니다.각 단계를 완료하고 실무 경험을 쌓기 위해 지침을 주의 깊게 따르세요. 과거 데이터에 따르면, 이것은 초급 레벨의 실험이며 완료율은 97%입니다.학습자들로부터 98%의 긍정적인 리뷰율을 받았습니다.

간단한 셸 명령 실행

이 단계에서는 Ansible Shell 모듈을 사용하여 원격 호스트에서 간단한 셸 명령을 실행합니다.

먼저, /home/labex/project/simple_shell_command.yml 파일을 완성합니다.
다음 내용을 플레이북 파일에 추가합니다.

- name: Execute a Simple Shell Command
  hosts: localhost
  gather_facts: false

  tasks:
    - name: Execute ls -l command
      shell: ls -l
      register: command_output

    - name: Display command output
      debug:
        var: command_output.stdout_lines
  • hosts: localhost: 이 Ansible 플레이북을 실행할 대상 호스트는 localhost입니다.
  • gather_facts: false: 호스트 정보 수집을 비활성화합니다.
  • shell: ls -l: 실행할 명령을 지정합니다.

요약하면, 이 플레이북의 목적은 로컬 호스트에서 ls -l 명령을 실행하고 명령의 출력을 표시하는 것입니다.

그런 다음, Ansible 플레이북에서 명령의 출력을 표시합니다.

ansible-playbook /home/labex/project/simple_shell_command.yml

예시 출력:

[WARNING]: No inventory was parsed, only implicit localhost is available
[WARNING]: provided hosts list is empty, only localhost is available. Note that
the implicit localhost does not match 'all'

PLAY [Execute a Simple Shell Command] ******************************************

TASK [Execute ls -l command] ***************************************************
changed: [localhost]

TASK [Display command output] **************************************************
ok: [localhost] => {
    "command_output.stdout_lines": [
        "total 16",
        "-rwxrwxrwx 1 labex root 285 Mar  8 13:33 complex_shell_commands.yml",
        "-rwxrwxrwx 1 labex root 221 Mar  8 13:33 handle_command_failure.yml",
        "-rwxrwxrwx 1 labex root 222 Mar  8 13:33 pass_variables.yml",
        "-rwxrwxrwx 1 labex root 266 Mar  8 13:36 simple_shell_command.yml"
    ]
}

PLAY RECAP *********************************************************************
localhost                  : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

여기서 "command_output.stdout_lines":[...]는 대상 호스트에서 ls -l의 출력입니다.

셸 명령에 변수 전달

이 단계에서는 Ansible 플레이북에서 Shell 모듈을 사용하여 실행되는 셸 명령으로 변수를 전달하는 방법을 배우게 됩니다.

먼저, /home/labex/project/pass_variables.yml 파일을 완성합니다.
다음 내용을 플레이북 파일에 추가합니다.

- name: Pass Variables to Shell Commands
  hosts: localhost
  gather_facts: false
  vars:
    directory_path: /home/labex

  tasks:
    - name: Execute ls command with a variable
      shell: ls "{{ directory_path }}"
      register: variable_command_output

    - name: Display variable command output
      debug:
        var: variable_command_output.stdout_lines
  • hosts: localhost: 이 Ansible 플레이북을 실행할 대상 호스트는 localhost입니다.
  • vars: /home/labex 값을 가진 directory_path라는 변수를 정의합니다.
  • shell: ls "{{ directory_path }}": directory_path라는 변수의 내용을 출력하기 위해 ls 명령을 실행합니다.

요약하면, 이 플레이북은 로컬 호스트에서 디렉토리 경로 (/home/labex) 를 나타내는 변수를 사용하여 ls 명령을 실행하고 명령의 출력을 표시합니다.

그런 다음, Ansible 플레이북에서 명령의 출력을 표시합니다.

ansible-playbook /home/labex/project/pass_variables.yml

예시 출력:

[WARNING]: No inventory was parsed, only implicit localhost is available
[WARNING]: provided hosts list is empty, only localhost is available. Note that
the implicit localhost does not match 'all'

PLAY [Pass Variables to Shell Commands] ****************************************

TASK [Execute ls command with a variable] **************************************
changed: [localhost]

TASK [Display variable command output] *****************************************
ok: [localhost] => {
    "variable_command_output.stdout_lines": [
        "Code",
        "Desktop",
        "golang",
        "project"
    ]
}

PLAY RECAP *********************************************************************
localhost                  : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

여기서 "variable_command_output.stdout_lines": [...]는 대상 호스트에서 ls /home/labex의 출력입니다.

명령 실패 처리

이 단계에서는 Shell 모듈을 사용하여 셸 명령을 실행할 때 명령 실패를 처리하는 방법을 배우게 됩니다. 셸 명령이 0 이 아닌 종료 상태를 반환하여 실패를 나타내는 경우를 처리합니다.

먼저, /home/labex/project/handle_command_failure.yml 파일을 완성합니다.
다음 내용을 플레이북 파일에 추가합니다.

- name: Handle Command Failure
  hosts: localhost
  gather_facts: false

  tasks:
    - name: Execute a failing command
      shell: failing-command
      register: failing_command_output
      ignore_errors: yes

    - name: Handle command failure
      debug:
        msg: "The command failed. Performing fallback action."
      when: failing_command_output.failed
  • hosts: localhost: 이 Ansible 플레이북을 실행할 대상 호스트는 localhost입니다.
  • shell: failing-command: 이 줄은 shell 모듈을 사용하여 failing-command 명령을 실행합니다. 이 명령의 출력은 캡처되어 failing_command_output 변수에 저장됩니다. failing-command 스크립트가 존재하지 않으므로 이 명령은 실패해야 합니다.
  • ignore_errors: yes: 이 줄은 failing-command 실행 중에 발생하는 모든 오류를 무시하도록 Ansible 에 지시합니다. 이를 통해 명령이 실패하더라도 플레이북이 계속 실행될 수 있습니다.
  • debug: 이 모듈은 debug 모듈을 사용하여 "The command failed. Performing fallback action."이라는 메시지를 표시합니다. 이 메시지는 failing_command_output.failed 조건이 충족될 때만 표시되며, 이는 이전 명령 실행이 실패했음을 나타냅니다.

요약하면, 플레이북은 실패할 것으로 예상되는 명령을 실행하려고 시도하고, 실행 중에 발생하는 모든 오류를 무시한 다음, 명령이 실패했음을 나타내는 메시지를 표시하고 명령의 실패 상태에 따라 대체 작업이 수행될 것임을 나타냅니다.

그런 다음, Ansible 플레이북에서 명령의 출력을 표시합니다.

ansible-playbook /home/labex/project/handle_command_failure.yml

예시 출력:

[WARNING]: No inventory was parsed, only implicit localhost is available
[WARNING]: provided hosts list is empty, only localhost is available. Note that
the implicit localhost does not match 'all'

PLAY [Handle Command Failure] **************************************************

TASK [Execute a failing command] ***********************************************
fatal: [localhost]: FAILED! => {"changed": true, "cmd": "failing-command", "delta": "0:00:00.009169", "end": "2024-03-08 13:46:22.701946", "msg": "non-zero return code", "rc": 127, "start": "2024-03-08 13:46:22.692777", "stderr": "/bin/sh: line 1: failing-command: command not found", "stderr_lines": ["/bin/sh: line 1: failing-command: command not found"], "stdout": "", "stdout_lines": []}
...ignoring

TASK [Handle command failure] **************************************************
ok: [localhost] => {
    "msg": "The command failed. Performing fallback action."
}

PLAY RECAP *********************************************************************
localhost                  : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=1

"msg": "The command failed. Performing fallback action."의 존재는 failing-command 명령의 실행이 실패했음을 나타냅니다.

복잡한 셸 명령어 실행

이 단계에서는 Shell 모듈을 사용하여 더 복잡한 셸 명령을 실행합니다. 명령 리디렉션, 파이프라인 및 복잡한 명령 구조의 사용법을 살펴봅니다.

먼저, /home/labex/project/complex_shell_commands.yml 파일을 완성합니다.
다음 내용을 플레이북 파일에 추가합니다.

- name: Execute Complex Shell Commands
  hosts: localhost
  gather_facts: false

  tasks:
    - name: Execute complex command
      shell: ls -l /home/labex | grep 'project' > /home/labex/output.txt
      register: complex_command_output

    - name: Display complex command output
      debug:
        var: complex_command_output.stdout_lines
  • hosts: localhost: 이 Ansible 플레이북을 실행할 대상 호스트는 localhost입니다.
  • shell: ls -l /home/labex의 출력을 /home/labex/output.txt 파일로 리디렉션하고 grep을 사용하여 project에 대한 내용을 필터링합니다.

요약하면, 이 플레이북은 로컬 호스트에서 복잡한 셸 명령을 실행하고, 출력을 필터링 및 리디렉션하여 파일로 저장한 다음, 명령 실행의 출력을 표시합니다.

그런 다음, Ansible 플레이북 명령을 실행합니다.

ansible-playbook /home/labex/project/complex_shell_commands.yml

예시 출력:

[WARNING]: No inventory was parsed, only implicit localhost is available
[WARNING]: provided hosts list is empty, only localhost is available. Note that
the implicit localhost does not match 'all'

PLAY [Execute Complex Shell Commands] ******************************************

TASK [Execute complex command] *************************************************
changed: [localhost]

TASK [Display complex command output] ******************************************
ok: [localhost] => {
    "complex_command_output.stdout_lines": []
}

PLAY RECAP *********************************************************************
localhost                  : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

마지막으로, /home/labex/output.txt 파일 내용을 봅니다.

cat /home/labex/output.txt

예시 출력:

drwxr-xr-x 1 labex labex 4096 Mar 8 13:49 project

요약

축하합니다! Ansible Shell 모듈 랩을 성공적으로 완료했습니다. Shell 모듈을 사용하여 원격 호스트에서 셸 명령을 실행하고, 변수를 명령에 전달하고, 명령 실패를 처리하고, 복잡한 셸 명령을 실행하는 방법을 배웠습니다.

Shell 모듈은 Ansible 플레이북에서 셸 명령을 실행하는 데 있어 뛰어난 유연성과 제어 기능을 제공합니다. 그러나 임의의 셸 명령을 실행하는 것은 보안에 영향을 미칠 수 있으므로 사용할 때 주의해야 합니다. 항상 명령을 신뢰하고 사용자가 제공한 모든 입력을 검증하십시오.

이제 Shell 모듈에 대한 이해가 높아졌으므로, 이를 활용하여 다양한 자동화 작업을 수행하고 원격 호스트를 효율적으로 관리할 수 있습니다. 즐거운 Ansible 스크립팅 되세요!