Ansible playbook 2

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

저번에 진행한 nginx 웹서버를 TSL가 지원되게 만들어 본다.

TLS란?
SSL에 기반한 기술로 인터넷에서의 정보를 암호화해서 송수신하는 프로토콜이다.
TSL는 다양한 종류의 보안 통신을 하기위한 프로토콜
HTTPS는 TLS위에 HTTP 프로토콜을 얹어 보안된 HTTP통신을 하는 프로토콜이다.

---
- name: Configure webserver with nginx and tls
  hosts: webservers 
  become: True
  vars: # 변수지정을한다.
    key_file: /etc/nginx/ssl/nginx.key # nginx.key 파일 내용을 key_file이라는 변수로 사용
    cert_file: /etc/nginx/ssl/nginx.crt # nginx.crt 파일 내용을 cert_file이라는 변수로 사용
    conf_file: /etc/nginx/sites-available/default # default 파일을 conf_file이라는 변수로사용
    server_name: localhost
  tasks: # 실행할 작업 목록
    - name: Install nginx
      apt: name=nginx update_cache=yes cache_valid_time=3600 # nginx 설치

    - name: create directories for TLS certificates 
      file: path=/etc/nginx/ssl state=directory # TLS 인증서 디렉토리 생성

    - name: copy TLS key
      copy: src=files/nginx.key dest={{ key_file }} owner=root mode=0600 #key_file 변수를 사용해서 TLS 키 복사
      notify: restart nginx

    - name: copy TLS certificate
      copy: src=files/nginx.crt dest={{ cert_file }} #key_file 변수를 사용해서 TLS 인증서 복사
      notify: restart nginx

    - name: copy nginx config file
      template: src=templates/nginx.conf.j2 dest={{ conf_file }}
      notify: restart nginx

    - name: enable configuration
      file: dest=/etc/nginx/sites-enabled/default src={{ conf_file }} state=link # nginx 설정 활성화
      notify: restart nginx

    - name: copy index.html
      template: src=templates/index.html.j2 dest=/usr/share/nginx/html/index.html mode=0644
      
  handlers: # 핸들러는 태스크에 의해 통지된 경우에만 실행된다 *TLS키 변경*, *TLS 인증서 변경*, "설정파일변경", "sites-enabled" 콘텐츠 변경일때 nginx를 다시 시작한다.
    - name: restart nginx
      service: name=nginx state=restarted

TLS 인증서와 키를 생성해준다.

openssl req -x509 -nodes -days 3650 -newkey rsa:2048 -subj /CN=localhost -keyout file/nginx.key -out files/nginx.crt

Jinja 템플릿을 이용한 설정파일 작성

#nginx.conf.j2
server {
        listen 80 default_server;
        listen [::]:80 default_server ipv6only=on;

        listen 443 ssl;

        root /usr/share/nginx/html;
        index index.html index.htm;

        server_name {{ server_name }};
        ssl_certificate {{ cert_file }};
        ssl_certificate_key {{ key_file }};

        location / {
                try_files $uri $uri/ =404;
        }
}

nginx 설정파일의 차이?
nginx.conf 와 nginx.conf.j2 의 차이는 템플릿 문법인 jinja2를 사용한것과 사용하지 않은 차이이다.
그말은 즉 nginx.conf 파일은 하드코딩된 값, 정적인 파일을 제공한다.
그에 반해 nginx.conf.j2 파일은 jinja2 템플릿 파일이며 변수,제어구조 동적으로 구성이가능하다.

플레이북을 실행하여 웹페이지를 확인헤본다.

ansible-playbook web-tls.yml

https://localhost:8443 을 치고 엔터를 하면 접속이 가능해 진다. 위에서 설명한거와 같이 TSL을 사용하여 HTTPS로 접속한다.

profile
엔지니어로 살아남기

0개의 댓글

관련 채용 정보