어쩌다 IT
article thumbnail
반응형

리뷰 (Review)

더보기

IaaS - Infrastructure as a Service

  • Cloud를 통해 가상 머신 환경을 온디멘드로 제공

 

IaC - Infrastructure as a Code

  • 인프라 구성을 코드를 사용하여 자동으로 구축, 관리, 프로비저닝
  • IaC를 통해 코드를 기반으로 인프라를 관리하고, 일관성을 유지하고, 배포 관리가 쉽다.

 

Ansible 특징

  • Agentless
  • 멱등성 - Idempotency
  • 재사용성 - Reusability

 

Ansible 구성 요소

  • 제어 노드 - Contol node
    • Ansible을 실행하는 node
    • Ansible 제공 프로그램을 이용하여 Managed node 관리
  • 매니지드 노드 - Managed node
  • 인벤토리 - Inventory
    • Managed node 목록
  • 모듈 - Module
  • 테스크 - Task
    • Ansible 작업 단위
  • 플레이 북 - Playbook
    • 순서가 지정된 Task 목록

 

Ansible을 통한 매니지드 노드 관리 방법

  • 모듈을 통한 매니지드 노드 관리
  • Ad-hoc 명령을 통한 매니지드 노드 관리
  • Task 단위로 매니지드 노드 관리
  • 플레이 북을 이용한 매니지드 노드 관리

모듈 이해

 

모듈 (Module)

  • 참고 자료
    • 참고 자료의 Example은 주로 Playbook에서 쓰는 형태
  • 간단하게 Ansible에서 사용하는 명령어
  • 모듈은 하나의 작은 프로그램
  • Ansible을 이용하여 Managed node에 대하여 구성 관리를 수행하는 실질적인 동작 수행
  • 모듈은 namespace 단위로 관리
  • 모듈 지정 방법
    • namespace.모듈
  • ansible.builtin namespace는 Ansible 기본 모듈 namespace
    • ansible.builtin namespace의 모듈은 별도로 namespace 지정 없이도 사용할 수 있다.
      • ansible managed -m ping -i ./hosts
      • ansible managed -m ansible.builtin.ping -i ./hosts
      • 둘 다 같은 결과값이 출력된다.
  • ansible-doc
    • Ansible document 확인 명령
    • Parameters - 해당 모듈을 사용할 때 전달할 수 있는 파라미터(인수, argument)에 대한 설명, 전달하는 값
    • Attribute - 해당 모듈의 속성, 모듈 동작 시 적용
    • Return values - 해당 모듈이 실행된 후의 결과값
    • Example - 해당 모듈 사용법

    • ansible-doc -l - Ansible 모듈 전체의 목록 출력
    • ansible-doc <모듈명> - 모듈에 대한 도움말 출력
    • ansible-doc -s <모듈명> - 모듈을 사용할 수 있는 Playbook 구문 출력
[ec2-user@ip-12-12-12-12 work-ansible]$ ansible-doc -l
fortios_router_community_list                       Configure community lists in Fortinet's FortiOS and FortiGate                                      
azure_rm_devtestlab_info                            Get Azure DevTest Lab facts                                                                        
ecs_taskdefinition                                  register a task definition in ecs                                                                  
avi_alertscriptconfig                               Module for setup of AlertScriptConfig Avi RESTful Object                                           
tower_receive                                       Receive assets from Ansible Tower                                                                  
netapp_e_iscsi_target                               NetApp E-Series manage iSCSI target configuration                                                  
azure_rm_acs                                        Manage an Azure Container Service(ACS) instance                     
...
[ec2-user@ip-12-12-12-12 work-ansible]$ ansible-doc -l | grep ping
win_ping                                            A windows version of the classic ping module                                                       
postgresql_ping                                     Check remote PostgreSQL server availability                                                        
lambda_event                                        Creates, updates or deletes AWS Lambda function event mappings                                     
net_ping                                            Tests reachability using ping from a network device                                                
ping                                                Try to connect to host, verify a usable python and return `pong' on success            
...
[ec2-user@ip-12-12-12-12 work-ansible]$ ansible-doc ping
> PING    (/usr/lib/python2.7/site-packages/ansible/modules/system/ping.py)

        A trivial test module, this module always returns `pong' on successful contact. It does not make sense in playbooks, but it
        is useful from `/usr/bin/ansible' to verify the ability to login and that a usable Python is configured. This is NOT ICMP
        ping, this is just a trivial test module that requires Python on the remote-node. For Windows targets, use the [win_ping]
        module instead. For Network targets, use the [net_ping] module instead.
...
[ec2-user@ip-12-12-12-12 work-ansible]$
  • 모듈은 기본적으로 멱등성(Idempotent)을 가지고 있다.
    • Ansible에서는 Module, Task, Ad-hoc, Playbook은 멱등성을 가진다.
  • 일부 모듈은 멱등성을 가지고 있지 않다.
    • command 모듈
      • Managed node들의 명령줄에서 임의의 명령 실행
      • Managed node의 쉘에서 실행되는 게 아니므로 쉘 작업을 수행할 수 없다.
      • 리다이렉션이나 파이프 기능도 사용 불가능
      • ansible <host 패턴> -m command -a <명령>
    • shell 모듈
      • Managed node의 쉘을 통해 명령어 처리
      • Managed node의 쉘 환경 변수에도 접근할 수 있고 리다이렉션이나 파이프 기능도 사용 가능
      • ansible <host 패턴> -m shell -a <명령>
    • raw 모듈
      • 모듈 하위 시스템을 거치지 않고 원격 쉘을 사용하여 직접 명령 실행
      • 파이썬을 설치할 수 없는 시스템에서 유용한 모듈
      • Linux 기본 조건을 만족하지 못하거나 SSH가 없는 환경에서 사용
[ec2-user@ip-12-12-12-12 work-ansible]$ ansible host1 -m command -a "set | grep PWD" -i ./hosts
host1 | FAILED | rc=2 >>
[Errno 2] No such file or directory: b'set': b'set'
[ec2-user@ip-12-12-12-12 work-ansible]$ ansible host1 -m shell -a "set | grep PWD" -i ./hosts
host1 | CHANGED | rc=0 >>
BASH_EXECUTION_STRING='set | grep PWD'
PWD=/home/ec2-user
[ec2-user@ip-12-12-12-12 work-ansible]$

# 똑같은 명령이지만 command와 shell의 결과값이 다르다.
[ec2-user@ip-12-12-12-12 work-ansible]$ ansible host1 -m shell -a "echo hello >> hello.txt" -i ./hosts
host1 | CHANGED | rc=0 >>
[ec2-user@ip-12-12-12-12 work-ansible]$ ansible host1 -m shell -a "ls -lF" -i ./hosts
host1 | CHANGED | rc=0 >>
total 4
-rw-rw-r-- 1 ec2-user ec2-user 6 Sep 21 03:20 hello.txt
[ec2-user@ip-12-12-12-12 work-ansible]$ ansible host1 -m shell -a "cat hello.txt" -i ./hosts
host1 | CHANGED | rc=0 >>
hello
[ec2-user@ip-12-12-12-12 work-ansible]$ ansible host1 -m shell -a "echo hello >> hello.txt" -i ./hosts
host1 | CHANGED | rc=0 >>
[ec2-user@ip-12-12-12-12 work-ansible]$ ansible host1 -m shell -a "ls -lF" -i ./hosts
host1 | CHANGED | rc=0 >>
total 4
-rw-rw-r-- 1 ec2-user ec2-user 12 Sep 21 03:26 hello.txt
[ec2-user@ip-12-12-12-12 work-ansible]$ ansible host1 -m shell -a "cat hello.txt" -i ./hosts
host1 | CHANGED | rc=0 >>
hello
hello
[ec2-user@ip-12-12-12-12 work-ansible]$

# line 7의 결과값과 line 16의 결과값이 다름. 멱등성이 적용되기 어려움.
[ec2-user@ip-12-12-12-12 work-ansible]$ ansible host1 -m shell -a "yum update -y" --become -i ./hosts
[WARNING]: Consider using the yum module rather than running 'yum'.  If you need to use command because yum is insufficient you can add 'warn: false' to this command
task or set 'command_warnings=False' in ansible.cfg to get rid of this message.
host1 | CHANGED | rc=0 >>
Loaded plugins: extras_suggestions, langpacks, priorities, update-motd
Resolving Dependencies
--> Running transaction check
---> Package amazon-ssm-agent.x86_64 0:3.1.1575.0-1.amzn2 will be updated
---> Package amazon-ssm-agent.x86_64 0:3.1.1732.0-1.amzn2 will be an update
...
Complete!
[ec2-user@ip-12-12-12-12 work-ansible]$

# --become : 관리자 권한으로 실행하는 옵션

중요 모듈

  • user 모듈
    • 사용자 추가 / 삭제 관리 모듈
    • state 파라미터
      • present - 생성, default
      • absent - 소멸
    • ansible <host 패턴> -m user -a <명령> --become
[ec2-user@ip-12-12-12-12 work-ansible]$ ansible managed -m user -a "name=worker state=present" -i ./hosts
host3 | FAILED! => {
    "changed": false, 
    "cmd": "/sbin/useradd -m worker", 
    "msg": "[Errno 13] Permission denied: b'/sbin/useradd'", 
    "rc": 13
... # 에러 발생
[ec2-user@ip-12-12-12-12 work-ansible]$ ansible managed -m user -a "name=worker state=present" --become -i ./hosts
host1 | CHANGED => {
    "changed": true, 
    "comment": "", 
    "create_home": true, 
    "group": 1001, 
    "home": "/home/worker", 
    "name": "worker", 
    "shell": "/bin/bash", 
    "state": "present", 
    "system": false, 
    "uid": 1001
}
...
# prsent로 사용자 생성
# --become 통해 관리자 권한으로 실행
[ec2-user@ip-12-12-12-12 work-ansible]$
[ec2-user@ip-12-12-12-12 work-ansible]$ ansible managed -m shell -a "tail -n 2 /etc/passwd" -i ./hosts
host3 | CHANGED | rc=0 >>
ec2-user:x:1000:1000:EC2 Default User:/home/ec2-user:/bin/bash
worker:x:1001:1001::/home/worker:/bin/bash
...
# UID 1001 worker 사용자 생성 확인
[ec2-user@ip-12-12-12-12 work-ansible]$ ansible managed -m user -a "name=worker state=absent" --become -i ./hosts
host2 | CHANGED => {
    "changed": true, 
    "force": false, 
    "name": "worker", 
    "remove": false, 
    "state": "absent"
}
...
# absent로 사용자 삭제
[ec2-user@ip-12-12-12-12 work-ansible]$ ansible managed -m shell -a "tail -n 2 /etc/passwd" -i ./hosts
host1 | CHANGED | rc=0 >>
tcpdump:x:72:72::/:/sbin/nologin
ec2-user:x:1000:1000:EC2 Default User:/home/ec2-user:/bin/bash

  • yum 모듈
    • RedHat 배포판 패키지 관리 명령인 yum에 대한 모듈
    • 유사 모듈 - apt, dnf
    • state 파라미터
      • present, installed - 설치
      • latest - upgrade
      • absent, removed - 삭제
    • ansible <host 패턴> -m yum -a <명령> --become

설정되어있던 ansible_python_interpreter=/usr/bin/python3 으로는 설치가 되지 않아서 ansible_python_interpreter=/usr/bin/python 으로 수정

[ec2-user@ip-12-12-12-12 work-ansible]$ ansible host1 -m yum -a "name=httpd state=present" --become -i ./hosts
host1 | CHANGED => {
    "ansible_facts": {
        "pkg_mgr": "yum"
    }, 
    "changed": true, 
    "changes": {
        "installed": [
            "httpd"
        ]
    }, 
...
[ec2-user@ip-12-12-12-12 work-ansible]$ ansible host1 -m shell -a "systemctl status httpd" -i ./hosts
host1 | FAILED | rc=3 >>
● httpd.service - The Apache HTTP Server
   Loaded: loaded (/usr/lib/systemd/system/httpd.service; disabled; vendor preset: disabled)
   Active: inactive (dead)
     Docs: man:httpd.service(8)non-zero return code
[ec2-user@ip-12-12-12-12 work-ansible]$

  • service 모듈
    • 시스템 서비스(데몬 프로세스)에 대한 시작, 종료, 재시작 등의 기능 제공 모듈
    • 유사 모듈 - systemd
    • state 파라미터
      • started - 시작
      • stopped - 중지
      • restarted - service 완전히 종료 후 재시작
      • reloaded - 환경 설정 파일 reload
    • ansible <host 패턴> -m service -a <명령> --become
[ec2-user@ip-12-12-12-12 work-ansible]$ ansible host1 -m service -a "name=httpd state=started" --become -i ./hosts
host1 | CHANGED => {
    "changed": true, 
    "name": "httpd", 
    "state": "started", 
    "status": {
        "ActiveEnterTimestampMonotonic": "0", 
        "ActiveExitTimestampMonotonic": "0", 
        "ActiveState": "inactive", 
...
    }
}
# host1 Public IP 로 접속하면 Test page 확인 가능
[ec2-user@ip-12-12-12-12 work-ansible]$ ansible host1 -m service -a "name=httpd state=stopped" --become -i ./hosts
host1 | CHANGED => {
    "changed": true, 
    "name": "httpd", 
    "state": "stopped", 
    "status": {
...
    }
}
# host1 Public IP 로 접속하면 error 발생
[ec2-user@ip-12-12-12-12 work-ansible]$

  • copy 모듈
    • Control node(source 측)에서 Managed node(destination 측)로 파일 복사 (전송)
    • src 파라미터
      • 복사(전송) 할 파일 이름 (경로 포함)
    • dest 파라미터
      • 복사(전송) 될 위치
[ec2-user@ip-12-12-12-12 Workspace-goorm]$ pwd
/home/ec2-user/work-ansible/Workspace-goorm
[ec2-user@ip-12-12-12-12 Workspace-goorm]$ ls
calc.js  index.html
[ec2-user@ip-12-12-12-12 Workspace-goorm]$ ansible public -m copy -a "src=index.html dest=/var/www/html/index.html" --become -i ../hosts
host2 | CHANGED => {
    "changed": true, 
    "checksum": "2e87c1090358c19fff3f211e46ce47445bf5fdaf", 
    "dest": "/var/www/html/index.html", 
    "gid": 0, 
...
}
host1 | CHANGED => {
    "changed": true, 
    "checksum": "2e87c1090358c19fff3f211e46ce47445bf5fdaf", 
    "dest": "/var/www/html/index.html", 
    "gid": 0, 
...
}
[ec2-user@ip-12-12-12-12 Workspace-goorm]$
# host1, host2 Public IP로 접속 시 웹 페이지 확인 가능

YAML 이해

 

YAML

  • YAML Ain't Markup Language
  • 데이터를 표현하는 목적으로 사용하는 script 형식
  • 주로 선언 정보나 환경 설정 정보를 기술하는 목적으로 활용
  • Ansible에서는 Playbook을 작성할 때 항상 YAML 형식으로 작성
  • Ansible에서 활용하는 YAML 문법
  • Ansible에서 작성하는 Playbook 파일 확장자 - .yml
  • 파일 시작
    • Ansible Playbook에서 사용하는 YAML 파일은 시작 시 - 기호 3개(---)로 표시
    • Playbook 최상단에 표시하며 생략할 수 있다. (대부분 작성)
  • 파일 끝
    • Playbook 파일 끝 표시는 ... 으로 표시
    • Playbook 최하단에 표시하며 생략할 수 있다. (대부분 생략)
  • 데이터 표현을 위한 자료형
    • 문자열
      • 일반적인 모든 자료 형태
      • YAML 문자열을 " " 로 묶을 필요가 없다.
      • 필요하다면 " " 로 묶어서 사용 가능
    • Boolean
      • yes or no와 같은 둘 중 하나의 상태 표시
      • YAML은 Native Boolean 타입을 갖고 있다.
      • True or False로 해석
  • Collection - 여러 개의 데이터 저장
    • 리스트 - list
      • 파이썬 리스트 자료형과 유사
      • YAML에서는 시퀀스 (sequence) 라 부른다.
      • 리스트는 - 로 구분한다.
      • [ ]로 묶는 인라인(inline) 포맷 지원
    • 딕셔너리 - dictionary
      • 파이썬 dict 자료형과 유사
      • YAML에서는 매핑 (mapping) 이라 부른다.
      • key:value 형식
      • { }로 묶는 인라인 포맷 지원
  • 라인 폴딩 - line folding
    • 파일 콘텐츠를 보기 좋게 관리하기 위해 여러 라인에 나누여 표기할 때 사용
    • > 문자로 라인 폴딩을 사용해 표현
  • YAML 내용은 각 단계(level)에 대한 표현은 스페이스를 이용하여 표현 
    • 단계 표현을 위한 들여 쓰기(indentation)는 스페이스 2칸을 사용
    • 탭(tap)을 사용하면 오류 발생

Playbook 이해

 

Playbook

  • 인벤토리에 정의된 Managed node에서 무엇을 해야 할 것인가(서버 환경 구성 정보)를 정의한 내용
  • 자동화 절차를 기술한 코드 파일
  • YAML 포맷으로 표현
  • 설정이나 프로세스에 대한 모델 정의를 표현한 최소한의 문법으로 구성
  • Playbook의 목표는 Managed node 그룹을 잘 정의된 Ansible 내에서 Task로 불리는 역할(role)에 매핑해 주는 것

 

Playbook 파일

  • 파일명에 대한 특별한 규칙은 없다.
  • 임의의 이름으로 Playbook 파일을 작성하고 확장자는 .yml 부여
---
# ping-test.yml
- name: ping test
  hosts: managed
  tasks:
    - name: ping
      ping:
    - name: current directory
      shell:
        cmd: pwd

Playbook 실행

  • ansible-playbook [옵션] <playbook 파일명>
    • -i <인벤토리 파일명> : 사용자가 지정한 위치의 인벤토리 파일 사용
    • -e <추가 변수> : 추가 변수 지정, key=value 형식
[ec2-user@ip-12-12-12-12 work-ansible]$ ansible-playbook ping-test.yml -i ./hosts

PLAY [ping test] *****************************************************************************************************************************************************

TASK [Gathering Facts] ***********************************************************************************************************************************************
ok: [host1]
ok: [host3]
ok: [host2]

TASK [ping] **********************************************************************************************************************************************************
ok: [host2]
ok: [host3]
ok: [host1]

TASK [current directory] *********************************************************************************************************************************************
changed: [host3]
changed: [host2]
changed: [host1]

PLAY RECAP ***********************************************************************************************************************************************************
host1                      : ok=3    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
host2                      : ok=3    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
host3                      : ok=3    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

[ec2-user@ip-12-12-12-12 work-ansible]$

Playbook 구조

  • Playbook - Play - Task 구조
    • Playbook - Play 집합
    • Play - Managed node에 적용할 여러 작업 코드의 집합, 한 번에 수행할 작업 단위, task 모음
    • Task - 실제 수행할 작업 내용, 모듈로 표현

TIF

yum 모듈 실습 중에 httpd 설치하는데 먹통이 되길래 식겁했다.

실습할 때마다 느끼지만 중간에 에러가 발생하면 머리가 하얘지고, 그다음부터는 수업에 집중이 안된다.

다행히 인벤토리 파일 수정 직후 발생했던 일이라 거기서 문제가 있겠구나 싶었고, 주석이 문제였음을 빨리 발견했다.

 

구글 스터디잼 심화반은 Architecting with Google Kubernetes Engine: Foundations 과정 진행 중인데

강의와 퀴즈까지는 완료했고, 실습만 남았다.

AWS를 배우고 진행하다 보니 용어 부분이나 기능들이 겹치는 부분들이 있어서 퀴즈가 어렵지는 않았다.

실습을 위해 신청했던 것이기에 주말에 집중해서 해보려 한다.

 

지난달에 샀던 만들면서 배우는 파이썬과 40개의 작품들은 오늘부로 마무리했다.

모든 것을 완벽하게 이해했다고 할 수는 없지만, 간단하게 무언가를 만들어보면서 파이썬과 조금은 가까워진 것 같다.

 

 

2022. 09. 21 에 작성된 글입니다.

반응형
profile

어쩌다 IT

@jwlish

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!