앤서블에서는 앤서블 전체에서 재사용할 수 있는 값을 저장하기 위해 변수를 사용할 수 있다.
playbook에 vars
섹션을 추가하여 변수를 정의할 수 있다.
vars
의 섹션에 key_file
, cert_file
, conf_file
변수들을 정의하여 각 파일의 경로를 value 값으로 넣음
vars:
key_file: /etc/nginx/ssl/nginx.key
cert_file: /etc/nginx/ssl/nginx.crt
conf_file: /etc/nginx/sites-available/default
또한 vars_file
라는 섹션을 사용해 하나 이상의 파일에 변수를 저장이 가능하다.
vars_files:
- nginx.yml
----------------------------------------------
# nginx.yml
key_file: /etc/nginx/ssl/nginx.key
cert_file: /etc/nginx/ssl/nginx.crt
conf_file: /etc/nginx/sites-available/default
server_name: localhost
nginx.yml
파일에 하나 이상의 변수가 정의되어있다. 이 파일을 vars_files 라고 정하면 해당 파일에서 nginx.yml
파일에 있는 변수들을 사용가능하다. key: {{ key_file }}
playbook 태스크를 실행할 때 디버그 debug
를 사용해 변수를 출력 가능하다.
- debug: var=varname
playbook 태스크 결과에 따라 변수의 값을 설정해야 하는 경우가 존재한다. 이때 태스크에서 register
속성을 사용해 변수를 생성한다.
- name: capture output of whoami command
command: whoami
register: login # command whoami의 명령어 결과가 login이라는 변수에 저장된다
yaml파일을 사용해 register 속성을 이용해 login이라는 변수를 debug로 출력해보겠다.
- name: show return value of command module
hosts: server1
tasks:
- name: capture output of id command
command: id -un
register: login
- debug: var=login
cmd
-> 호출된 커맨드를 문자열 리스트로 갖는다rc
-> rc
키 값이 0이 아니라면 앤서블은 해당커맨드가 실행하지 못한 태스크로 간주stderr
-> 표준 에러에 저장된 모든 텍스트stdout
-> 표준 축력에 저장된 모든 텍스트stdout_lines
-> 개행 문자로 분리된 표준 출력 텍스트 포함command 모듈에서 register 절을 사용하는 경우 stdout키에 접근해야한다.
- name: show return value of command module
hosts: server1
tasks:
- name: capture output of id command
command: id -un
register: login
- dubug: msg="Logged in as user {{ login.stout }}
task id -un
명령어 결과를 login
에 저장후 위에서 설명한것과 같이 stdout에 접근하여 출력한다.