Ansible之角色详解

ansible角色概念

角色(roles)是ansible自1.2版本开始引入的新特性,用于层次性,结构化地组织playbook。

roles能够根据层次型结构自动装载变量文件、tasks以及handlers等。要使用roles只需要在playbook中使用include指令即可。简单的说,roles就是通过分别将变量、文件、任务、模块及处理器放置于单独的目录中、并可以便捷地include他们的一种机制。角色一般用于基于主机构建服务的场景中、但也可以是用于构建守护进程等场景中。

我理解的就是把多个节点都会用到的功能将其定义成模块,以后谁用到就调用该模块即可,而ansible中它有一个特有名称,即角色(rolers)
官方文档:https://docs.ansible.com/ansible/latest/user_guide/playbooks_reuse_roles.html

角色目录规划

官方的目录结构,必须这样定义!

1
2
3
4
5
6
7
8
9
[root@ansible /etc/ansible/roles]# tree
.
├── init # 角色名称
│ ├── files # 存放需要copy的文件
│ ├── handlers # 触发任务剧本
│ ├── tasks # 具体任务剧本
│ ├── templates # 模版文件
│ └── vars # 存放变量文件
│ └── mete # 依赖关系

创建项目目录

因为每台服务器都需要创建用户组,用户,安装服务等,所以我们可以将这些相同的任务单独创建一个init初始化角色。

创建角色目录

1
2
cd /etc/ansible/roles/
mkdir init/{vars,tasks,templates,handlers,files} -p

编写系统基础环境角色剧本

  1. 配置yum源

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    vim init/tasks/yum.yml
    #01. 配置yum源
    - name: "01_configure_yum_repos"
    yum_repository:
    name: base
    description: base yum repo
    baseurl:
    - http://mirrors.aliyun.com/centos/7/os/x86_64/
    gpgcheck: no

    - name: 02_configure_yum_Repos
    yum_repository:
    name: epel
    description: epel yum repo
    baseurl:
    - https://mirrors.aliyun.com/epel/7/x86_64/
    gpgcheck: no
    enabled: yes
  2. 安装常用软件

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    vim init/tasks/install.yml
    #2. 安装常用软件
    - name: 03_install_packages all
    yum:
    name: "{{ packages }}"
    vars:
    packages:
    - lrzsz
    - ntpdate
    - lsof
    - iftop
    - iotop
    - tree
    - vim
    - net-tools
    - bash-completion
  3. 创建数据目录和脚本目录

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    vim init/tasks/datadir.yml
    # 3. 创建数据目录和脚本目录
    - name: 04_create dir
    file:
    path: "{{ item }}"
    state: directory
    mode: 0755
    loop:
    - /data
    - /server/script

  4. 创建时间同步定时任务

    1
    2
    3
    4
    5
    6
    7
    vim init/tasks/ntpdate.yml
    #4.创建时间同步定时任务
    - name: 05_cron_ntpdate
    cron:
    name: Time_Update
    minute: "*/5"
    job: /sbin/ntpdate time1.aliyun.com
  5. 拷贝优化后的ssh配置文件

1
2
3
4
5
6
7
8
9
vim init/tasks/ssh.yml
#5.拷贝优化后的ssh配置文件
- name: 06_copy_ssh
template:
src: sshd_config.j2
dest: /etc/ssh/sshd_config
mode: 0600
backup: yes
notify: restart sshd
  1. 添加环境变量
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    vim init/tasks/profile.yml
    #6. 添加环境变量
    - name: 07_profile
    lineinfile:
    dest: /etc/profile
    regexp: "{{ item.name }}"
    line: "{{ item.profile }}"
    backup: yes
    loop:
    - { name: '^export PS1=', profile: 'export PS1="[\[\e[1;35m\]\u\[\e[0;32m\]@\[\e[00;32m\]\H\[\e[00m\]\[\e[01;31m\] \w\[\e[00m\]]\$"'}
    - { name: 'HISTTIMEFORMAT', profile: 'HISTTIMEFORMAT="%F %T `whoami` "' }
  2. 内核参数优化
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
vim init/tasks/sysctl.yml
#7. 内核参数优化
- name: 08-config-sysctl
copy:
src: sysctl.conf.default
dest: /etc/sysctl.d/init.conf
owner: root
group: root
mode: 644
register: _sysctl

- name: 09-sysctl-reload
command: /usr/sbin/sysctl -p
ignore_errors: True
when:
- _sysctl is changed
  1. 整合到main.yml
    1
    2
    3
    4
    5
    6
    7
    8
    9
    vim init/tasks/main.yml
    - name: Centos init server
    - include_tasks: yum.yml
    - include_tasks: install.yml
    - include_tasks: datadir.yml
    - include_tasks: ntpdate.yml
    - include_tasks: ssh.yml
    - include_tasks: profile.yml
    - include_tasks: sysctl.yml

编写jinja模板文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
vim /etc/ansible/roles/init/templates/sshd_config.j2
Port 22
ListenAddress {{ ansible_facts.eth0.ipv4.address }}
HostKey /etc/ssh/ssh_host_rsa_key
HostKey /etc/ssh/ssh_host_ecdsa_key
HostKey /etc/ssh/ssh_host_ed25519_key
SyslogFacility AUTHPRIV
AuthorizedKeysFile .ssh/authorized_keys
PasswordAuthentication yes
ChallengeResponseAuthentication no
GSSAPIAuthentication yes
GSSAPICleanupCredentials no
UsePAM yes
X11Forwarding yes
UseDNS no
Subsystem sftp /usr/libexec/openssh/sftp-server

编写handlers文件

1
2
3
4
5
vim /etc/ansible/roles/init/handlers/main.yml 
- name: restart sshd
service:
name: sshd
state: restarted

拷贝sysctl.conf.default

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
cat > /etc/ansible/roles/init/files/sysctl.conf.default <<EOF
fs.suid_dumpable=0
kernel.randomize_va_space=2
# net.ipv6.conf.all.disable_ipv6=1
# net.ipv6.conf.lo.disable_ipv6=1
# net.ipv6.conf.default.disable_ipv6=1

net.ipv4.ip_forward=0
net.ipv4.conf.all.send_redirects=0
net.ipv4.conf.all.accept_source_route=0
net.ipv4.conf.all.accept_redirects=0
net.ipv4.conf.all.secure_redirects=0
net.ipv4.conf.all.log_martians=1
net.ipv4.conf.all.rp_filter=0
net.ipv4.conf.all.arp_announce=2
net.ipv4.conf.default.send_redirects=0
net.ipv4.conf.default.accept_source_route=0
net.ipv4.conf.default.accept_redirects=0
net.ipv4.conf.default.secure_redirects=0
net.ipv4.conf.default.log_martians=1
net.ipv4.conf.default.rp_filter=0
net.ipv4.conf.default.arp_announce=2
net.ipv4.conf.lo.arp_announce=2
net.ipv4.icmp_echo_ignore_broadcasts=1
net.ipv4.icmp_ignore_bogus_error_responses=1
net.ipv4.tcp_synack_retries=2
net.ipv4.tcp_tw_reuse=1
# net.ipv4.tcp_tw_recycle=0
net.ipv4.tcp_timestamps=1
net.ipv4.tcp_syncookies=1
net.ipv4.tcp_max_tw_buckets=5000
net.ipv4.tcp_fin_timeout=30
net.ipv4.tcp_keepalive_intvl=15
net.ipv4.tcp_keepalive_time=600
net.ipv4.tcp_keepalive_probes=3
net.ipv4.tcp_max_syn_backlog=8192
net.ipv4.route.flush=1
# net.ipv4.neigh.default.gc_stale_time=120
net.ipv4.ip_local_port_range=1024 65000
net.core.somaxconn=32768
# net.core.netdev_max_backlog=32768

fs.file-max=65535
vm.drop_caches=3
vm.dirty_ratio=10
vm.nr_hugepages=512
vm.overcommit_memory=1
vm.swappiness=0
vm.max_map_count=655360
vm.dirty_background_ratio=5
EOF

定义playbook

【注意】:要在roles目录同级创建playbook。

1
2
3
4
vim /etc/ansible/init.yaml
- hosts: dbserver
roles:
- init

当然也可以把这些内容写入同一个playbook中。playbook的名字可以自定义。