on
[Ansible] 기본 개념 정리
[Ansible] 기본 개념 정리
Ansible은 Python Module 및 SSH를 사용하여 원격 호스트에 명령을 수행할 수 있도록 해주는 CM(Configuration Management) 도구이다.
별도의 Agent를 설치하지 않아도 되며 단순히 SSH 접속이 가능하면 편리하게 사용할 수 있다.
(내부적으로 Python을 사용하게 되는데 대부분의 Linux에는 Python이 기본적으로 설치가 되어 있다.)
나는 Ansible을 사용하여 원격 Node에 명령어를 수행하기 전에 다음의 과정을 거친다.
1. ansible.cfg 파일 설정 및 확인
2. inventory 파일 생성 및 Group 변수, Host 변수 등 설정
3. ansible-inventory 명령어를 사용하여 정상적으로 호스트 및 그룹 등록이 완료되었는지 확인
4. ansible -m ping {{group or host}} 명령어로 Master 노드에서 원격 노드로 ping 모듈이 성공하는지 확인
5. Playbook 작성
6. Playbook 테스트
1) Syntax Check
2) --list-hosts, --list-tasks 확인
3) --check 옵션으로 Dry run 수행
...
등의 과정을 거치는 편이다.
Inventory 파일의 보안을 위해서 ansible-vault 명령어를 활용하여 Encrypted 할 수도 있다.
(ansible-playbook 등 명령어를 할 때 자동으로 vault password를 물어보게 하려면 ansible.cfg에서 설정값을 수정하면 된다.)
Inventory 파일
- 특정 변수를 Host, Groups 별로 설정이 가능
- inventory 파일에서 Host 변수 및 Group 변수를 설정할 수도 있지만 각 File 별로 찢어놓을 수도 있음
[web-servers] host1 http_port=80 maxRequestPerChild=888 host2 http_port=443 maxRequestPerChild=400 [web-servers:vars] ntp_server=centos7.org proxy=bastion.com ...
변수 값들을 Inventory 파일에 넣지 않고 별도 파일에 저장하기
: 변수 파일의 형식은 YAML이다.
Host vars와 Group vars 모두 yml 포맷으로 생성하면 되며, 각각 host_vars 디렉터리, group_vars 디렉터리에 생성할 수 있다.
# Host vars http_port: 80 maxRequestPerChild: 500 # Group vars ntp_server: centos7.org proxy: basation.com
Inventory Parameters
ansible_ssh_host: 접속할 SSH Host 명
ansible_ssh_user : SSH User name
ansible_ssh_pass : 패스워드로 접속할 때 사용
ansible_ssh_private_key_file : SSH Private key 파일
ansible_python_interpreter : Target host의 Python path
테스트용 Playbook setup (gather_facts) Test Display pwd output
gather_facts의 default 값은 yes이기 때문에 Task는 총 3개가 돌 것이다.
❯ cat playbooks/test.yml --- - name: Ansible Test hosts: centos7_hosts tasks: - name: Test shell: pwd register: result - name: Display pwd output debug: msg: "{{ result }}"
Syntax 확인
❯ ansible-playbook --syntax-check playbooks/test.yml playbook: playbooks/test.yml
실행될 Hosts 확인
❯ ansible-playbook --list-hosts playbooks/test.yml playbook: playbooks/test.yml play #1 (centos7_hosts): Ansible Test TAGS: [] pattern: ['centos7_hosts'] hosts (2): centos7-01 centos7-02
실행될 Tasks 확인
❯ ansible-playbook --list-tasks playbooks/test.yml playbook: playbooks/test.yml play #1 (centos7_hosts): Ansible Test TAGS: [] tasks: Test TAGS: [] Display pwd output TAGS: []
추가로 -v 옵션도 가능하니 Debug 할 경우 유용하게 사용될 수 있다.
모의로 실행해보기 (Dry run)Gather_facts 결과 (setup 모듈이며, gather_facts 또한 TASK에 속하게 됨)
TEST란 Task가 수행되고 Display pwd output이란 Task가 수행된 것을 확인할 수 있다.
맨 처음에 지정해놓은 Playbook 이름,
❯ ansible-playbook playbooks/test.yml --check PLAY [Ansible Test] ********************************************************************************************************************************************** TASK [Gathering Facts] ******************************************************************************************************************************************* ok: [centos7-02] ok: [centos7-01] TASK [Test] ****************************************************************************************************************************************************** skipping: [centos7-01] skipping: [centos7-02] TASK [Display pwd output] **************************************************************************************************************************************** ok: [centos7-01] => { "msg": { "changed": false, "failed": false, "msg": "skipped, running in check mode", "skipped": true } } ok: [centos7-02] => { "msg": { "changed": false, "failed": false, "msg": "skipped, running in check mode", "skipped": true } } PLAY RECAP ******************************************************************************************************************************************************* centos7-01 : ok=2 changed=0 unreachable=0 failed=0 skipped=1 rescued=0 ignored=0 centos7-02 : ok=2 changed=0 unreachable=0 failed=0 skipped=1 rescued=0 ignored=0
주요 Module들
copy 모듈
ansible web-servers -m copy -a "src=/etc/hosts dest=/tmp/hosts"
file 모듈
ansible web-servers -m file -a "dest=/path/to/c mode=755 owner=ec2-user group=admin state=directory"
yum, apt 모듈
ansible web-servers -m yum -a "name=httpd state=present"
user 모듈
ansible all -m user -a "name=foo password=" ansible all -m user -a "name=foo state=absent"
Ansible에서 변수를 사용할 때 우선순위가 있다. 우선 순위 중 하나가 걸리면 그 후순위는 무시하게 된다.
변수 종류
환경 변수 ( -e )
플레이북 변수 ( var_files, vars )
인벤터리 변수
호스트 변수, 그룹 변수
Facts
우선 순위
Extra vars Task vars Block vars Role and Include vars set_facts registered vars playbook var_files playbook vars_prompt playbook vars host facts playbook host_vars playbook group_vars inventory host_vars inventory group_vars inventory vars role defaults
변수 종류와 Overriding
Group / Host variables
모든 Group에 해당하는 변수는 group_vars/all 에 저장하면 된다.
특정 그룹에 해당하는 변수는 group_vars/a_group 등과 같이 저장이 가능하다.
변수 사용하기
변수는 inventory에 저장할 수도 있고 group_vars 혹은 host_vars, var_files 등을 통해 가져올 수도 있다.
../vars/users.yml
외부 파일에 생성할 유저와 패스워드, Group 명을 지정하였다.
❯ cat vars/users.yml users: - name: james password: dkagh1. group: wheel - name: gildong password: passw0rd1! group: wheel - name: hodong password: hodong1! group: wheel
Playbook
vars_files로 변수 파일의 위치를 지정해주고
with_items로 users란 리스트 변수를 반복문으로 접근하도록 하였다.
--- - name: Create multiple users with wheel group hosts: centos7_hosts gather_facts: no vars_files: - ../vars/users.yml tasks: # name, password, group - name: Create user {{ item.name }} user: name: "{{ item.name }}" create_home: yes password: "{{ 'item.password' | password_hash('sha512') }}" update_password: on_create groups: "{{ item.group }}" with_items: "{{ users }}" - name: Get wheel group`s users shell: cat /etc/group | grep wheel register: result - name: Cat above task result debug: var=result
Test
syntax 검사와 실행될 hosts들이 무엇인지, 어떤 Tasks들이 수행될지, Dry run까지 테스트
❯ ansible-playbook --syntax-check playbooks/create_user.yml playbook: playbooks/create_user.yml ❯ ansible-playbook --list-hosts playbooks/create_user.yml playbook: playbooks/create_user.yml play #1 (centos7_hosts): Create multiple users with wheel group TAGS: [] pattern: ['centos7_hosts'] hosts (2): centos7-01 centos7-02 ❯ ansible-playbook --list-tasks playbooks/create_user.yml playbook: playbooks/create_user.yml play #1 (centos7_hosts): Create multiple users with wheel group TAGS: [] tasks: Create user {{ item.name }} TAGS: [] Cat wheel group users at /etc/group TAGS: [] ❯ ansible-playbook --check playbooks/create_user.yml PLAY [Create multiple users with wheel group] **************************************************************************************************** TASK [Create user {{ item.name }}] *************************************************************************************************************** changed: [centos7-01] => (item={'name': 'james', 'password': 'dkagh1.', 'group': 'wheel'}) changed: [centos7-01] => (item={'name': 'gildong', 'password': 'passw0rd1!', 'group': 'wheel'}) changed: [centos7-01] => (item={'name': 'hodong', 'password': 'hodong1!', 'group': 'wheel'}) changed: [centos7-02] => (item={'name': 'james', 'password': 'dkagh1.', 'group': 'wheel'}) changed: [centos7-02] => (item={'name': 'gildong', 'password': 'passw0rd1!', 'group': 'wheel'}) changed: [centos7-02] => (item={'name': 'hodong', 'password': 'hodong1!', 'group': 'wheel'}) TASK [Cat wheel group users at /etc/group] ******************************************************************************************************* skipping: [centos7-01] skipping: [centos7-02] PLAY RECAP *************************************************************************************************************************************** centos7-01 : ok=1 changed=1 unreachable=0 failed=0 skipped=1 rescued=0 ignored=0 centos7-02 : ok=1 changed=1 unreachable=0 failed=0 skipped=1 rescued=0 ignored=0
만약 hodong 유저에는 어떠한 Group도 지정하고 싶지 않을 경우에는 어떻게 할까?
공백으로 만들어놓기
❯ cat vars/users.yml users: - name: james password: dkagh1. group: wheel - name: gildong password: passw0rd1! group: wheel - name: hodong password: hodong1! group:
hodong 유저는 wheel 그룹에 할당되지 않은 것으로 확인할 수 있다.
from http://nyyang.tistory.com/107 by ccl(A) rewrite - 2021-11-14 16:01:21