웹사이트 검색

Debian 11에서 Ansible을 설치하고 사용하는 방법


이 페이지에서

  1. 전제 조건
  2. Debian 11에 Ansible 설치
    1. APT를 사용하여 Ansible 설치\n
    2. PIP를 사용하여 Ansible 설치\n

    Ansible은 무료 오픈 소스이며 가장 널리 사용되는 구성 관리 도구 중 하나입니다. 클라우드 컴퓨팅, 구성 관리, 패키지 설치 및 서비스 구성을 단순화하는 크로스 플랫폼 도구입니다. 사용자가 특정 시스템에서 실행하려는 단계가 포함된 YAML 파일을 사용합니다. Ansible을 사용하면 단일 명령으로 호스트 이상을 구성하고 관리할 수 있습니다. Ansible은 Chef 및 Puppet과 같은 다른 구성 관리 도구의 대안입니다.

    이 기사에서는 Debian 11에서 Ansible 구성 관리 도구를 설치하고 사용하는 방법을 보여줍니다.

    전제 조건

    • Debian 11을 실행하는 세 대의 서버.\n
    • 루트 암호는 각 서버에 구성됩니다.\n

    이 자습서에서는 다음 설정을 사용합니다.

    • Ansible 컨트롤러 - 192.168.10.9
    • Ansible 호스트 - 192.168.10.10, 192.168.10.11\n

    Debian 11에 Ansible 설치

    기본적으로 Ansible 패키지는 Debian 기본 리포지토리에 포함되어 있지 않습니다. Debian 11에 Ansible을 설치하는 방법에는 두 가지가 있습니다.

    1. APT 명령 사용
    2. PIP 명령 사용

    APT를 사용하여 Ansible 설치

    먼저 시스템에 몇 가지 종속 항목을 설치해야 합니다. 다음 명령을 사용하여 필요한 종속성을 설치할 수 있습니다.

    apt-get install gnupg2 curl wget -y

    모든 종속성이 설치되면 APT source.list를 편집하고 Ansible 리포지토리를 추가합니다.

    nano /etc/apt/sources.list

    다음 줄을 추가합니다.

    deb http://ppa.launchpad.net/ansible/ansible/ubuntu focal main
    

    완료되면 파일을 저장하고 닫은 후 다음 명령을 사용하여 Ansible GPG 키를 추가하십시오.

    apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 93C4A3FD7BB9C367

    다음 출력이 표시되어야 합니다.

    Warning: apt-key is deprecated. Manage keyring files in trusted.gpg.d instead (see apt-key(8)).
    Executing: /tmp/apt-key-gpghome.lFEjztT9TY/gpg.1.sh --keyserver keyserver.ubuntu.com --recv-keys 93C4A3FD7BB9C367
    gpg: key 93C4A3FD7BB9C367: public key "Launchpad PPA for Ansible, Inc." imported
    gpg: Total number processed: 1
    gpg:               imported: 1
    

    이제 리포지토리를 업데이트하고 다음 명령을 사용하여 Ansible을 설치합니다.

    apt-get update
    apt-get install ansible -y

    Ansible이 설치되면 다음 명령을 사용하여 Ansible 버전을 확인합니다.

    ansible --version

    다음 출력이 표시되어야 합니다.

    ansible 2.10.8
      config file = None
      configured module search path = ['/root/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
      ansible python module location = /usr/lib/python3/dist-packages/ansible
      executable location = /usr/bin/ansible
      python version = 3.9.2 (default, Feb 28 2021, 17:03:44) [GCC 10.2.1 20210110]
    

    PIP를 사용하여 Ansible 설치

    먼저 Python과 PIP를 시스템에 설치해야 합니다. 다음 명령을 사용하여 설치할 수 있습니다.

    apt-get install python3 python3-pip -y

    설치가 완료되면 아래와 같이 pip 명령을 사용하여 Ansible을 설치합니다.

    pip install ansible

    sshpass 설치

    sshpass는 SSH 명령으로 암호를 제공할 수 있는 명령줄 도구입니다. 여기에서는 원격 호스트를 인증하기 위해 Ansible과 함께 Ansible 컨트롤러 노드에서 sshpass를 사용합니다.

    다음 명령을 사용하여 sshpass를 설치할 수 있습니다.

    apt-get install sshpass -y

    다음으로 첫 번째 원격 호스트에 연결하여 known_hosts 파일에 SSH 지문을 추가합니다.

    ssh 

    아래와 같이 SSH 암호를 제공하라는 메시지가 표시됩니다.

    The authenticity of host '192.168.10.10 (192.168.10.10)' can't be established.
    ECDSA key fingerprint is SHA256:q3zMoJ6qdjYvAdL7/w4Z0gm0ZEgGOB+rNIPKEMdYS6o.
    Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
    Warning: Permanently added '192.168.10.10' (ECDSA) to the list of known hosts.
    Password: 
    

    비밀번호를 입력하고 Enter 키를 눌러 SSH 지문을 추가하세요.

    다음으로 두 번째 원격 호스트에 연결하여 known_hosts 파일에 SSH 지문을 추가합니다.

    ssh 

    아래와 같이 SSH 암호를 제공하라는 메시지가 표시됩니다.

    The authenticity of host '192.168.10.11 (192.168.10.11)' can't be established.
    ECDSA key fingerprint is SHA256:q3zMoJ6qdjYvAdL7/w4Z0gm0ZEgGOB+rNIPKEMdYS6o.
    Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
    Warning: Permanently added '192.168.10.11' (ECDSA) to the list of known hosts.
    Password: 
    

    비밀번호를 입력하고 Enter를 누르십시오.

    이제 sshpass 명령어를 사용하여 SSH 연결을 확인할 수 있습니다.

    sshpass -p yourpassword ssh 

    Ansible 호스트 인벤토리 파일 생성

    다음으로 원격 호스트 IP 주소, 사용자 이름, 암호 및 SSH 포트를 정의하기 위한 인벤토리 파일을 생성해야 합니다.

    nano ~/.hosts

    다음 줄을 추가합니다.

    [servers]
    server1 ansible_host=192.168.10.10 ansible_user=root ansible_ssh_pass=password ansible_ssh_port=22
    server2 ansible_host=192.168.10.11 ansible_user=root ansible_ssh_pass=password ansible_ssh_port=22
    

    파일을 저장하고 닫습니다.

    참고: 위 파일에서는 원격 호스트 IP, 사용자 이름, 암호 및 SSH 포트를 사용합니다.

    앤서블 작업

    Ansible은 원격 호스트를 관리하는 데 도움이 되는 많은 모듈을 제공합니다.

    Ansible을 실행하는 기본 구문은 아래와 같습니다.

    ansible -i [inventory_file] -m [module] [host]

    모든 호스트에 대한 ping 연결을 확인합니다.

    ansible -i ~/.hosts -m ping all

    모든 것이 정상이면 다음과 같은 결과가 표시됩니다.

    server2 | SUCCESS => {
        "ansible_facts": {
            "discovered_interpreter_python": "/usr/bin/python3"
        },
        "changed": false,
        "ping": "pong"
    }
    server1 | SUCCESS => {
        "ansible_facts": {
            "discovered_interpreter_python": "/usr/bin/python3"
        },
        "changed": false,
        "ping": "pong"
    }
    

    유일한 server1의 ping 연결을 확인하려면 다음 명령을 실행하십시오.

    ansible -i ~/.hosts -m ping server1

    다음 출력이 표시되어야 합니다.

    server1 | SUCCESS => {
        "ansible_facts": {
            "discovered_interpreter_python": "/usr/bin/python3"
        },
        "changed": false,
        "ping": "pong"
    }
    

    쉘 모듈을 사용하여 원격 호스트에서 모든 명령을 실행할 수 있습니다.

    예를 들어, server2에서 "free -m" 명령을 실행하려면 다음 명령을 실행하십시오.

    ansible -i ~/.hosts -m shell -a "free -m" server2

    다음 출력이 표시되어야 합니다.

    server2 | CHANGED | rc=0 >>
                   total        used        free      shared  buff/cache   available
    Mem:            1982         128         491           2        1363        1669
    Swap:              0           0           0
    

    server2에서 "df -h" 명령을 실행하려면 다음 명령을 실행하십시오.

    ansible -i ~/.hosts -m shell -a "df -h" server2

    다음 출력이 표시되어야 합니다.

    server2 | CHANGED | rc=0 >>
    Filesystem      Size  Used Avail Use% Mounted on
    udev            976M     0  976M   0% /dev
    tmpfs           199M  404K  198M   1% /run
    /dev/sda1        50G  2.4G   45G   5% /
    tmpfs           992M  124K  992M   1% /dev/shm
    tmpfs           5.0M     0  5.0M   0% /run/lock
    tmpfs           199M     0  199M   0% /run/user/0
    

    Ansible은 원격 호스트에 모든 패키지를 설치할 수 있는 적절한 모듈을 제공합니다.

    Nginx 패키지를 server1에 설치하려면 다음 명령을 실행합니다.

    ansible -i ~/.hosts -m ansible.builtin.apt -a "name=nginx state=present" server1

    다음 출력이 표시되어야 합니다.

    server1 | CHANGED => {
        "ansible_facts": {
            "discovered_interpreter_python": "/usr/bin/python3"
        },
        "cache_update_time": 1631424599,
        "cache_updated": false,
        "changed": true,
        "stderr": "",
        "stderr_lines": [],
            "Upgrading binary: nginx.",
            "Setting up nginx (1.18.0-6.1) ...",
            "Processing triggers for man-db (2.9.4-2) ...",
            "Processing triggers for libc-bin (2.31-13) ..."
        ]
    }
    

    server1에서 Nginx 서비스의 상태를 확인하려면 다음 명령을 실행합니다.

    ansible -i ~/.hosts -m shell -a "systemctl status nginx" server1

    다음 출력이 표시되어야 합니다.

    server1 | CHANGED | rc=0 >>
    ? nginx.service - A high performance web server and a reverse proxy server
         Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled)
         Active: active (running) since Sun 2021-09-12 05:55:36 UTC; 49s ago
           Docs: man:nginx(8)
        Process: 10761 ExecStartPre=/usr/sbin/nginx -t -q -g daemon on; master_process on; (code=exited, status=0/SUCCESS)
        Process: 10764 ExecStart=/usr/sbin/nginx -g daemon on; master_process on; (code=exited, status=0/SUCCESS)
       Main PID: 10871 (nginx)
          Tasks: 2 (limit: 2341)
         Memory: 5.8M
            CPU: 54ms
         CGroup: /system.slice/nginx.service
                 ??10871 nginx: master process /usr/sbin/nginx -g daemon on; master_process on;
                 ??10874 nginx: worker process
    
    Sep 12 05:55:36 ansible systemd[1]: Starting A high performance web server and a reverse proxy server...
    Sep 12 05:55:36 ansible systemd[1]: nginx.service: Failed to parse PID from file /run/nginx.pid: Invalid argument
    Sep 12 05:55:36 ansible systemd[1]: Started A high performance web server and a reverse proxy server.
    

    Ansible은 원격 호스트에서 사용자를 생성하고 관리하는 사용자 모듈을 제공합니다.

    server1에서 user1이라는 새 사용자를 만들려면 다음 명령을 실행합니다.

    ansible -i ~/.hosts -m ansible.builtin.user -a "name=user1 password=yourpassword" server1

    다음 출력이 표시되어야 합니다.

    server1 | CHANGED => {
        "ansible_facts": {
            "discovered_interpreter_python": "/usr/bin/python3"
        },
        "changed": true,
        "comment": "",
        "create_home": true,
        "group": 1000,
        "home": "/home/user1",
        "name": "user1",
        "password": "NOT_LOGGING_PASSWORD",
        "shell": "/bin/sh",
        "state": "present",
        "system": false,
        "uid": 1000
    }
    

    결론

    이 기사에서는 APT 및 PIP를 사용하여 Ansible을 설치하는 방법을 배웠습니다. 또한 다양한 Ansible 모듈을 사용하여 원격 호스트를 관리하는 방법도 배웠습니다. 이제 Ansible에 대해 충분히 이해하셨기를 바랍니다. 궁금한 점이 있으면 언제든지 문의해 주세요.