ansible 部署 nginx

准备工作

创建roles目录

# mkdir -pv  /data/apps/ansible/roles/nginx/{files,tasks,handlers,templates,vars}

hosts

[ubuntu]
172.16.18.31 ansible_ssh_port=22  ansible_ssh_user=ubuntu hostname=app-01

测试连通性

# ansible ubuntu -m ping
172.16.18.247 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python3"
    }, 
    "changed": false, 
    "ping": "pong"
}

创建角色相关文件

tasks/main.yml

- include: user.yml
- include: install_deps.yml
- include: unarchive.yml
- include: conf.yml
- include: service.yml

tasks/user.yml

- name: create nginx group
  group: 
    name: "{{ user }}" 
    state: present
    gid: "{{ uid }}"
- name: create nginx user
  user: 
    name: "{{ user }}"  
    group: "{{ user }}" 
    shell: /bin/false 
    system: yes
    comment: Nginx Server
    uid: "{{ uid }}"
    home: /data/apps/nginx

tasks/install_deps.yml

- name: install nginx for ubuntu22.04
  apt: name=libssl-dev,zlib1g-dev,libgd-dev,libgeoip-dev,libpcre3-dev
  when: ansible_distribution_version=="22.04"

tasks/unarchive.yml

- name: Create a directory if it does not exist
  ansible.builtin.file:
    path: /data/apps/nginx
    state: directory
    mode: '0755'
    owner: "{{ user }}"
    group: "{{ user }}"
- name: copy tar to remote nginx ubuntu22.04
  unarchive: 
    src: nginx-1.22.1.tar.gz 
    dest: /data/apps/nginx/ 
    owner:  "{{ user }}"
    group: "{{ user }}"
  when: ansible_distribution_version=="22.04"
- name: link nginx
  file: 
    src: /data/apps/nginx/nginx-1.22.1 
    dest: /usr/local/nginx 
    state: link

tasks/conf.yml

- name: config file 
  template: src=nginx.conf.j2 dest=/usr/local/nginx/conf/nginx.conf
  notify: restart nginx

tasks/service.yml

- name: service nginx script
  copy: 
    src: nginx.service  
    dest: /lib/systemd/system/nginx.service
- name: start nginx service
  systemd: 
    name: nginx 
    state: started 
    enabled: yes

handlers/main.yml

- name: restart nginx
  systemd: 
    name: nginx.service 
    state: restarted
    daemon_reload: true

templates/nginx.conf.j2

user  {{ user }};
worker_processes  auto;
.....

查看相关文件

# tree /data/apps/ansible/roles/nginx/
/data/apps/ansible/roles/nginx/
├── files
│   ├── nginx-1.22.1.tar.gz
│   └── nginx.service
├── handlers
│   └── main.yml
├── tasks
│   ├── conf.yml
│   ├── install_deps.yml
│   ├── main.yml
│   ├── service.yml
│   ├── unarchive.yml
│   └── user.yml
├── templates
│   └── nginx.conf.j2
└── vars

5 directories, 10 files

playbook调用角色

nginx_roles.yml

- hosts: ubuntu
  remote_user: ubuntu
  become: yes
  roles:
   - role: nginx
     user: nginx
     uid: 113

运行playbook

# ansible-playbook nginx_roles.yml

查看执行结果

nginx

# ls -l /usr/local/nginx
lrwxrwxrwx 1 root root 29 Mar 31 15:14 /usr/local/nginx -> /data/apps/nginx/nginx-1.22.1
# ls -l /data/apps/nginx/
total 4
drwxr-xr-x 11 nginx nginx 4096 Mar 31 16:46 nginx-1.22.1
posted @ 2023-03-31 17:05  小吉猫  阅读(116)  评论(0编辑  收藏  举报