수업 77일차 Ansible , 앤서블 서버 , 플레이북 , when , include_tasks

유동우·2023년 1월 14일
1

■ nginx 설치 및 삭제를 추가하기

[nginx 설치 야믈]

vim nginx_install.yml


  • name: Install nginx on CentOS
    hosts: CentOS
    gather_facts: no
    become: yes

    tasks:

    • name: install epel-release
      yum: name=epel-release state=latest
    • name: install nginx web server
      yum: name=nginx state=present
    • name: Upload default index.html for web server
      get_url: url=https://www.nginx.com dest=/usr/share/nginx/html/ mode=0644
    • name: Start nginx web server
      service: name=nginx state=started
  • name: Install nginx on Ubuntu
    hosts: Ubuntu
    gather_facts: no
    become: yes

    tasks:

    • name: install nginx web server
      apt: pkg=nginx state=present update_cache=yes
    • name: Upload default index.html for web server
      get_url: url=https://www.apache.com dest=/usr/share/nginx/html/
      mode=0644 validate_certs=no

[nginx 삭제 야믈]

vim nginx_remove.yml


  • name: Remove nginx on CentOS
    hosts: CentOS
    gather_facts: no
    become: yes

    tasks:

    • name: remove epel-release
      yum: name=epel-release state=absent
    • name: remove nginx web server
      yum: name=nginx state=absent
  • name: Remove nginx on Ubuntu
    hosts: Ubuntu
    gather_facts: no
    become: yes

    tasks:

    • name: remove nginx web server
      apt: pkg=nginx state=absent autoremove=yes

====================================

■ 시간대 변경하기에 추가하기

vim timezone.yml


  • name: Setup linux timezone
    hosts: CentOS:Ubuntu
    gather_facts: no
    become: yes

    tasks:

    • name: set timezone to Asia/Seoul
      timezone: name=Asia/Seoul
  • name: Setup windows timezone
    hosts: Windows
    gather_facts: no

    tasks:

    • name: set timezone to 'Korea Standard Time'
      win_timezone: timezone='Korea Standard Time'

anp vim timezone.yml // 실행

ans CentOS -m shell -a "timedatectl | grep 'Time zone'" -k

ans Ubuntu -m shell -a "date +'%Z %z'" -k

ans all -m shell -a "ls -l /etc/ssh/sshd_config*" -

========================================

[앤서블 서버에 앤서블을 사용할 수 있는 환경을 구성해주는 야믈 파일]

VScode에 ansible_env_ready.yml

block아래에

     [nodes]
     192.168.56.[101:103]
     192.168.56.[201:203]

Vagrantfile에
ip주소 104~106 => 201~203으로변경
앤서블 서버 cfg.vm.provision "shell", path: "add_ssh_auth.sh", privileged: false 삭제

PowerShell로가서
exit
vagrant reload

========================================

■ authorized_keys의 등록을 추가한 auto_pass.yml

VSCode에서 6.1.2 auto_pass.yml복사해서
one-server에 붙혀넣고


  • name: Create authority between server and nodes
    hosts: nodes
    connection: local
    serial: 1
    gather_facts: no
    vars:
    ansible_password: vagrant

tasks:
- name: ssh-keyscan for known_hosts file
command: /usr/bin/ssh-keyscan -t ecdsa {{ ansible_host }}
register: keyscan

- name: input key
  lineinfile:      
    path: ~/.ssh/known_hosts
    line: "{{ item }}"
    create: yes     
  with_items:
    - "{{ keyscan.stdout_lines }}"

- name: ssh-keygen for authorized_keys file
  command: "ssh-keygen -b 2048 -t rsa -f ~/.ssh/id_rsa -q -N '' "
  ignore_errors: yes
  run_once: true

- name: input key for each nodes
  connection: ssh
  authorized_key:
    user: vagrant
    state: present
    key: "{{ lookup('file', '~/.ssh/id_rsa.pub') }}"

수정후 저장

Vagrantfile 앤서블 서버 제일아래에

cfg.vm.provision "file", source: "auto_pass.yml", destination: "auto_pass.yml"
cfg.vm.provision "shell", inline: "ansible-playbook auto_pass.yml", privileged: false

추가하고 저장

vagrant provision

vagrant ssh ansible-server

ls -l ~/.ssh

ans all -m ping

================================================

■ 플레이북을 동적으로 구성

vim facts.yml


  • name: print ipv4.address for nodes
    hosts: nodes
    #gather_facts: no

tasks:
- name: debug by msg
debug:
msg:
- "eth0's ip {{ ansible_eth0.ipv4.address }}" // bridge : 10.0.2.15
- "eth1's ip {{ ansible_eth1.ipv4.address }}" // hostvars : 192.168.56.101

- name: debug by var
  debug:
    var: "{{ item  }}"
  with_items:
    - hostvars[inventory_hostname]['ansible_eth0']['ipv4']['address']
    - hostvars[inventory_hostname]['ansible_eth1']['ipv4']['address']

anp facts.yml // facts 값 확인

ans nodes -m setup > facts.txt // 리다이렉션을 통해서 노드들에 대한 facts값을 facts.txt에 저장

cat facts.txt

cat facts.txt | grep SSH_CONNECTION // 노드들에 대한 IP정보를 확인하기 위해 저장된 facts 값을 검색

ans nodes -m setup --tree /tmp/facts > /dev/null // --tree 옵션을 사용하여 각 노드별로 fact를 수집함

ls /tmp/facts

※ 한 줄로 저장되어 있던 facts를 보기 좋게 json 포맷으로 변경해주기

vim facts_collector.yml


  • name: Collect facts for each node
    hosts: nodes

tasks:
- name: generate facts
setup:
register: facts

 - name: save facts
   local_action:
     module: copy
     # 저장되어 있는 facts 값을 보기 좋게 json 포맷으로 변형
     content: "{{ facts | to_nice_json  }}"
     dest: ./{{ ansible_hostname  }}_facts_by_collector.txt

anp facts_collector.yml

cat ansible-node01_facts_by_collector.txt

텍스트 파일 모두삭제

rm -rf *.txt

■ when 조건

cp nginx_install.yml nginx_install_w_when.yml

cp nginx_remove.yml nginx_remove_w_when.yml

ls

vim nginx_install_w_when.yml


  • name: Install nginx on the nodes
    hosts: nodes
    become: yes

    tasks:

    • name: install epel-release for CentOS
      action: "{{ ansible_pkg_mgr }} name=epel-release state=latest"
      when: ansible_distribution == 'CentOS'

    • name: install nginx web server for CentOS
      action: "{{ ansible_pkg_mgr }} name=nginx state=present"
      when: ansible_distribution == 'CentOS'

    • name: upload default index.html for web server
      get_url: url=https://www.nginx..com dest=/usr/share/nginx/html/ mode=0644
      when: ansible_distribution == 'CentOS'

 - name: start nginx web server
   service: name=nginx state=started
   when: ansible_distribution == 'CentOS'

 - name: install nginx web server for Ubuntu
   action: "{{ ansible_pkg_mgr }} name=nginx state=present update_cache=yes"
   when: ansible_distribution == 'Ubuntu'

 - name: upload default index.html for web server
   get_url: url=https://www.apache.com dest=/usr/share/nginx/html/
            mode=0644 validate_certs=no
   when: ansible_distribution == 'Ubuntu'

vim nginx_remove_w_when.yml


  • name: Remove nginx on nodes
    hosts: nodes
    become: yes

    tasks:

    • name: remove epel-release for CentOS
      action: "{{ ansible_pkg_mgr }} name=epel-release state=absent"
      when: ansible_distribution == 'CentOS'
 - name: remove nginx web server for CentOS
   action: "{{ ansible_pkg_mgr }} name=nginx state=absent"
   when: ansible_distribution == 'CentOS'

 - name: remove nginx web server
   action: "{{ ansible_pkg_mgr }} name=nginx state=absent autoremove=yes"
   when: ansible_distribution == 'Ubuntu'

=============================================

■ include_tasks

불필요하게 실행되는 코드를 줄이기

※ 코드를 줄여만들 야믈 생성해서 복사

cp nginx_install_w_when.yml nginx_install_w_include_tasks.yml

cp nginx_install_w_when.yml CentOS.yml

cp nginx_install_w_when.yml Ubuntu.yml

[nginx 설치]

vim nginx_install_w_include_tasks.yml


  • name: Install nginx on the nodes
    hosts: nodes
    become: yes

    tasks:

    • name: nginx for CentOS
      include_tasks: CentOS.yml
      when: ansible_distribution == 'CentOS'

    • name: nginx for Ubuntu
      include_tasks: Ubuntu.yml
      when: ansible_distribution == 'Ubuntu'

vim CentOS.yml

 - name: install epel-release for CentOS
   action: "{{ ansible_pkg_mgr }} name=epel-release state=latest"

 - name: install nginx web server for CentOS
   action: "{{ ansible_pkg_mgr }} name=nginx state=present"

 - name: upload default index.html for web server
   get_url: url=https://www.nginx.com dest=/usr/share/nginx/html/ mode=0644


 - name: start nginx web server
   service: name=nginx state=started

vim Ubuntu.yml

 - name: install nginx web server for Ubuntu
   action: "{{ ansible_pkg_mgr }} name=nginx state=present update_cache=yes"

 - name: upload default index.html for web server
   get_url: url=https://www.apache.com dest=/usr/share/nginx/html/
            mode=0644 validate_certs=no

anp nginx_install_w_include_tasks.yml

[nginx 삭제]

cp nginx_remove_w_when.yml nginx_remove_w_include_tasks.yml

cp nginx_remove_w_when.yml CentOS_remove.yml

cp nginx_remove_w_when.yml Ubuntu_remove.yml

vim nginx_remove_w_include_tasks.yml


  • name: Remove nginx on the nodes
    hosts: nodes
    become: yes

    tasks:

    • name: nginx for CentOS
      include_tasks: CentOS_remove.yml
      when: ansible_distribution == 'CentOS'

    • name: nginx for Ubuntu
      include_tasks: Ubuntu_remove.yml
      when: ansible_distribution == 'Ubuntu'

vim CentOS_remove.yml

 - name: remove epel-release
   action: "{{ ansible_pkg_mgr }} name=epel-release state=absent"

 - name: remove nginx web server
   action: "{{ ansible_pkg_mgr }} name=nginx state=absent"

vim Ubuntu_remove.yml

 - name: remove nginx web server
   action: "{{ ansible_pkg_mgr }} name=nginx state=absent autoremove=yes"

anp nginx_remove_w_include_tasks.yml

profile
클라우드 엔지니어가 되고싶은 클린이

0개의 댓글