Ansible 변수

조민철·2024년 6월 24일
1
post-thumbnail

Ansible 변수

앤서블에서는 앤서블 전체에서 재사용할 수 있는 값을 저장하기 위해 변수를 사용할 수 있다.

변수 정의

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에 접근하여 출력한다.

profile
엔지니어로 살아남기

0개의 댓글

관련 채용 정보