date: 2020-04-03title: ansible初始化服务器 #标题
tags: 初始化服务器 #标签
categories: ansible # 分类

用于记录下初始化服务器的playbook。篇幅较长,需要耐心。

入口文件

我是将playbook文件封装在了shell脚本中,将此shell脚本作为入口文件

  1. [root@ansible ansible-init-system]# cat ansible-init.sh
  2. #!/usr/bin/env bash
  3. # __author__ == "Ray"
  4. # __Email__ == "lv916551516@163.com"
  5. Usage(){
  6. echo -e "$0 脚本使用说明
  7. -f: 指定要执行的playbook(.yml)文件
  8. -h: 指定远程主机,多个主机以冒号分割
  9. -u: 指定远程主机的用户,(支持sudo),默认值为root
  10. -p: 指定远程主机端口号"
  11. }
  12. cur_dir=$(cd $(dirname ${BASH_SOURCE[0]}); pwd) #获取当前目录
  13. if [[ $# -eq 0 ]];then
  14. Usage
  15. exit 1
  16. elif [[ $1 == "--help" ]];then
  17. Usage
  18. exit 2
  19. fi
  20. #1.指定参数赋值
  21. while getopts ":f:h:u:p:" values;do
  22. case "$values" in
  23. "f")
  24. file="$OPTARG"
  25. ;;
  26. "h")
  27. host="$OPTARG"
  28. ;;
  29. "u")
  30. user="$OPTARG"
  31. ;;
  32. "p")
  33. port="$OPTARG"
  34. ;;
  35. "?")
  36. echo "无此选项 $OPTARG"
  37. ;;
  38. ":")
  39. echo "此选项无值 $OPTARG"
  40. ;;
  41. *)
  42. Usage
  43. ;;
  44. esac
  45. done
  46. # 2.确认参数
  47. if [[ -n ${file} ]];then
  48. echo -e "
  49. playbook文件:${file}
  50. 远端主机: ${host}
  51. 远端主机用户:${user}
  52. 远端主机端口: ${port}
  53. "
  54. read -p "回车确认执行......" OK
  55. # 3.执行playbook
  56. ansible-playbook ${cur_dir}/${file} --extra-vars "remote_host=$host ansible_ssh_user=$user ansible_ssh_port=$port"
  57. fi

playbook入口文件

  1. [root@ansible ansible-init-system]# cat szy_init_system.yml
  2. ---
  3. - hosts: '{{ remote_host }}'
  4. become: yes
  5. become_method: sudo
  6. gather_facts: no
  7. roles: # 下面定义了各种角色,如果哪些角色无需执行,注释掉即可
  8. - vim
  9. - epel_config
  10. - firewalld
  11. - selinux
  12. - set-hostname
  13. # - certbot
  14. - python3
  15. - zabbix-agent
  16. - rsync
  17. - setup-system
  18. - yum
  19. - change-root-password # 执行此role前,务必保证被控端已创建拥有sudo权限的普通用户

roles文件

好,接下来我们来看看roles文件写的都是什么。

  1. [root@ansible ansible-init-system]# ls roles/ # 以下是所有role的目录
  2. certbot firewalld selinux vim
  3. change-root-password python3 set-hostname yum
  4. epel_config rsync setup-system zabbix-agent

vim优化——vim

  1. [root@ansible roles]# tree -L 2 vim # vim角色的目录结构如下
  2. vim
  3. ├── files
  4. ├── vimfiles
  5. └── vimrc
  6. ├── meta
  7. └── main.yml
  8. ├── Readme.txt
  9. └── tasks
  10. └── main.yml
  11. # 部分重要文件内容
  12. [root@ansible roles]# cat vim/tasks/main.yml # tasks/main.yml文件
  13. ---
  14. - name: copy vimfiles
  15. copy: src=vimfiles/ dest=/usr/share/vim/vimfiles/
  16. - name: copy vimrc
  17. copy: src=vimrc dest=/etc/vimrc mode=0644
  18. [root@ansible roles]# cat vim/files/vimrc
  19. if v:progname =~? "evim"
  20. finish
  21. endif
  22. set nocompatible
  23. set backspace=indent,eol,start
  24. if has("vms")
  25. set nobackup
  26. else
  27. set backup
  28. endif
  29. set history=50
  30. set ruler
  31. set showcmd
  32. set incsearch
  33. map Q gq
  34. inoremap <C-U> <C-G>u<C-U>
  35. "if has('mouse')
  36. "" set mouse=a
  37. "endif
  38. if &t_Co > 2 || has("gui_running")
  39. syntax on
  40. set hlsearch
  41. endif
  42. if has("autocmd")
  43. filetype plugin indent on
  44. augroup vimrcEx
  45. au!
  46. autocmd FileType text setlocal textwidth=78
  47. autocmd BufReadPost *
  48. \ if line("'\"") > 1 && line("'\"") <= line("$") |
  49. \ exe "normal! g`\"" |
  50. \ endif
  51. augroup END
  52. else
  53. set autoindent
  54. endif " has("autocmd")
  55. if !exists(":DiffOrig")
  56. command DiffOrig vert new | set bt=nofile | r ++edit # | 0d_ | diffthis
  57. \ | wincmd p | diffthis
  58. endif
  59. " ---------------------------------------------------------------------------
  60. "colors
  61. set t_Co=256
  62. syntax enable
  63. syntax on
  64. colorscheme molokai
  65. " 不备份文件
  66. set nobackup
  67. " 自动格式化
  68. set formatoptions=tcrqn
  69. " 继承前一行的缩进方式,特别适用于多行注释
  70. set autoindent
  71. " 为C程序提供自动缩进
  72. set smartindent
  73. " 使用C样式的缩进
  74. set cindent
  75. " 设置以缩进的方式自动折叠和设置快捷方式
  76. " set foldmethod=indent
  77. " 统一缩进为4
  78. set softtabstop=4
  79. set shiftwidth=4
  80. " 在行和段开始处使用制表符
  81. set smarttab
  82. " 制表符为4
  83. set tabstop=4
  84. " 用空格代替制表符
  85. set expandtab
  86. " 不要换行
  87. set nowrap
  88. " 粘贴模式
  89. set paste
  90. " 我的状态行显示的内容(包括文件类型和解码)
  91. set statusline=%F%m%r%h%w\[POS=%l,%v][%p%%]\%{strftime(\"%d/%m/%y\ -\ %H:%M\")}
  92. " 总是显示状态行
  93. set laststatus=2
  94. " 高亮显示匹配的括号
  95. set showmatch
  96. set fileencodings=utf-8,ucs-bom,gb18030,gbk,gb2312,cp936
  97. set termencoding=utf-8
  98. set encoding=utf-8
  99. [root@ansible roles]# cat vim/meta/main.yml # 由于安装的系统没有vim指令,所以必须依赖于yum角色先进行安装vim
  100. ---
  101. dependencies:
  102. - { role: yum }

安装基本工具——yum

  1. [root@ansible roles]# tree -C yum # yum角色的目录结构
  2. yum
  3. ├── meta
  4. └── main.yml
  5. ├── Readme.txt
  6. ├── tasks
  7. └── main.yml
  8. └── vars
  9. └── main.yml
  10. [root@ansible roles]# cat yum/tasks/main.yml # 安装软件
  11. ---
  12. - name: Install epel repo
  13. yum:
  14. name: 'epel-release.noarch'
  15. state: latest
  16. - name: install the 'Development tools' package group
  17. yum:
  18. name: "@Development tools"
  19. state: present
  20. - name: Install packages
  21. yum:
  22. name: "{{ pkg_list }}" # 这里是引用的变量
  23. state: latest
  24. [root@ansible roles]# cat yum/vars/main.yml # 下面就是定义的上面引用的变量
  25. # 需要安装什么,只需要在此文件下增加即可
  26. pkg_list:
  27. - net-tools
  28. - bash-completion
  29. - bash-completion-extras
  30. - chrony
  31. - cronie
  32. - supervisor
  33. - crontabs
  34. - dstat
  35. - python-pip
  36. - file
  37. - htop
  38. - iftop
  39. - rsync
  40. - iproute
  41. - jq
  42. - less
  43. - mlocate
  44. - net-tools
  45. - nload
  46. - nmap
  47. - nmap-ncat
  48. - procps
  49. - screen
  50. - sysstat
  51. - telnet
  52. - traceroute
  53. - tree
  54. - unzip
  55. - zlib-devel
  56. - vim
  57. - which
  58. - openssl
  59. - openssl-devel
  60. - bzip2-devel
  61. - ncurses-devel
  62. - sqlite-devel
  63. - readline-devel
  64. - tk-devel
  65. - gdbm-devel
  66. - db4-devel
  67. - libpcap-devel
  68. - xz-devel
  69. - libselinux-python
  70. - lrzsz
  71. [root@ansible roles]# cat yum/meta/main.yml # 嗯,yum角色又依赖epel_config角色
  72. ---
  73. dependencies:
  74. - { role: epel_config }

配置epel-repo源——epel_config

  1. [root@ansible roles]# tree epel_config/ # 目录结构如下
  2. epel_config/
  3. └── tasks
  4. └── main.yml
  5. [root@ansible roles]# cat epel_config/tasks/main.yml # 任务列表
  6. ---
  7. # 备份原有repo文件
  8. - name: backup origin yum repos
  9. shell:
  10. cmd: "mkdir bak;mv *.repo bak"
  11. chdir: /etc/yum.repos.d
  12. creates: /etc/yum.repos.d/bak
  13. # 添加repo源
  14. - name: add os repo and epel repo
  15. yum_repository:
  16. name: "{{item.name}}"
  17. description: "{{item.name}} repo"
  18. baseurl: "{{item.baseurl}}"
  19. file: "{{item.name}}"
  20. enabled: 1
  21. gpgcheck: 0
  22. reposdir: /etc/yum.repos.d
  23. loop:
  24. - name: os
  25. baseurl: "https://mirrors.tuna.tsinghua.edu.cn/centos/7/os/$basearch"
  26. - name: epel
  27. baseurl: "http://mirrors.aliyun.com/epel/7/$basearch"

防火墙配置——firewalld

  1. [root@ansible roles]# tree firewalld/ # 目录结构
  2. firewalld/
  3. ├── files
  4. └── work.xml # 这个文件是自定义的防火墙规则,就不看了
  5. ├── handlers
  6. └── main.yml
  7. └── tasks
  8. └── main.yml
  9. [root@ansible roles]# cat firewalld/tasks/main.yml # 查看任务列表
  10. ---
  11. # 安装firewalld
  12. - name: Install firewalld.
  13. yum:
  14. name: firewalld
  15. state: latest
  16. #确保服务启动
  17. - name: Ensure firewalld is started and enabled at boot.
  18. systemd:
  19. name: firewalld
  20. state: started
  21. enabled: yes
  22. #设置firewalld的默认区域
  23. - name: Set work as default policy
  24. command: firewall-cmd --set-default-zone=work
  25. notify: reload firewalld
  26. # 初始 zone 配置
  27. - name: copy work.xml for firewalld
  28. copy: src=work.xml dest=/etc/firewalld/zones/work.xml mode=0600
  29. notify: reload firewalld
  30. [root@ansible roles]# cat firewalld/handlers/main.yml # 触发操作
  31. ---
  32. #重载firewalld
  33. - name: reload firewalld
  34. command: firewall-cmd --reload

selinux配置——selinux

  1. [root@ansible roles]# tree selinux/ # 目录结构
  2. selinux/
  3. └── tasks
  4. └── main.yml
  5. [root@ansible roles]# cat selinux/tasks/main.yml # 任务列表
  6. ---
  7. #改变selinux状态为disable
  8. - name: selinu修改为disabled,提示需要重启生效
  9. selinux:
  10. policy: targeted
  11. state: disabled
  12. #临时禁用
  13. - name: 临时设置selinux关闭,如果关闭,忽略
  14. shell: setenforce 0
  15. ignore_errors: True

更改主机名——set-hostname

  1. [root@ansible roles]# tree set-hostname/ # 目录结构
  2. set-hostname/
  3. ├── tasks
  4. └── main.yml
  5. └── vars
  6. └── main.yml
  7. [root@ansible roles]# cat set-hostname/tasks/main.yml # 任务列表
  8. ---
  9. #设置控制机的主机名
  10. - name: set hostname
  11. hostname:
  12. name: "{{item.name}}"
  13. when: item.host == inventory_hostname
  14. loop: "{{hostnames}}"
  15. [root@ansible roles]# cat set-hostname/vars/main.yml # 将IP与想要更改的主机名写在下面即可
  16. ---
  17. hostnames:
  18. - host: 192.168.20.9
  19. name: node01
  20. - host: 192.168.20.10
  21. name: node02

安装python3——Python3

  1. [root@ansible roles]# tree python3/ # 目录结构
  2. python3/
  3. ├── files
  4. └── Python-3.7.1.tgz # 这个为python3的软件包
  5. ├── Readme.txt
  6. ├── tasks
  7. └── main.yml
  8. └── vars
  9. └── main.yml
  10. [root@ansible roles]# cat python3/tasks/main.yml # 任务列表
  11. ---
  12. #安装依赖包
  13. - name: "安装python3的依赖包"
  14. yum:
  15. name: "{{ python3_depend }}"
  16. state: latest
  17. #拷贝Python-3.7.1
  18. - name: "copy Python3.7.1 to dest"
  19. copy: src=Python-3.7.1.tgz dest=/usr/local/src/Python-3.7.1.tgz
  20. #编译安装python3.7.1
  21. - name: "compile install"
  22. shell: cd /usr/local/src/;tar zxf Python-3.7.1.tgz; cd Python-3.7.1;./configure --prefix=/usr/local/python3.7;make;make install
  23. #删除之前存在的/usr/bin/python3
  24. - name: "删除已存在的python3"
  25. shell: rm -f /usr/bin/python3
  26. args:
  27. removes: /usr/bin/python3
  28. #软连接python3
  29. - name: "ln -s python3"
  30. file: src=/usr/local/python3.7/bin/python3 dest=/usr/bin/python3 state=link
  31. [root@ansible roles]# cat python3/vars/main.yml # 定义变量,以下是python3依赖的程序
  32. ---
  33. python3_depend:
  34. - zlib-devel
  35. - bzip2-devel
  36. - openssl-devel
  37. - ncurses-devel
  38. - sqlite-devel
  39. - readline-devel
  40. - tk-devel
  41. - gdbm-devel
  42. - db4-devel
  43. - libpcap-devel
  44. - xz-devel
  45. - libffi-devel

同步工具——rsync

  1. [root@ansible roles]# tree rsync/ # 目录结构
  2. rsync/
  3. ├── files
  4. └── rsyncd.conf # 此为我这里定义的配置文件,不便展示,根据需要定义自己的配置文件即可
  5. ├── handlers
  6. └── main.yml
  7. └── tasks
  8. └── main.yml
  9. [root@ansible roles]# cat rsync/tasks/main.yml # 任务列表
  10. ---
  11. # 安装rsync服务
  12. - name: "install rsync"
  13. package:
  14. name: '{{ item }}'
  15. state: present
  16. with_items:
  17. - rsync
  18. - name: "copy rsyncd.conf to dest_host"
  19. copy: src=rsyncd.conf dest=/etc/rsyncd.conf
  20. notify: restart rsyncd
  21. [root@ansible roles]# cat rsync/handlers/main.yml # 触发任务
  22. ---
  23. #restart rsyncd
  24. - name: restart rsyncd
  25. systemd: name=rsyncd state=restarted

更改root密码——change-root-password

  1. [root@ansible roles]# tree change-root-password/ # 目录结构
  2. change-root-password/
  3. └── tasks
  4. └── main.yml
  5. [root@ansible roles]# cat change-root-password/tasks/main.yml # 任务列表
  6. ---
  7. - name: 设置主机root密码
  8. shell: pwd=`openssl rand -base64 20` && echo $pwd >/root/.rootpwd && echo "root:$pwd" | chpasswd && echo $pwd
  9. register: password
  10. # 此任务存在些bug,万一服务器没有其他拥有sudo权限的用户,那么将无法得到修改后的root密码
  11. # 解决办法:增加发邮件功能,将root密码发送到邮箱。或者,在执行此role前创建拥有sudo权限的用户

安装zabbix-agent

  1. [root@ansible roles]# tree zabbix-agent/ # 目录结构如下
  2. zabbix-agent/
  3. └── tasks
  4. └── main.yml
  5. [root@ansible roles]# cat zabbix-agent/tasks/main.yml # 任务列表
  6. - name: Install zabbix-agent
  7. shell: rpm -ivh http://repo.zabbix.com/zabbix/4.0/rhel/7/x86_64/zabbix-agent-4.0.0-2.el7.x86_64.rpm
  8. args:
  9. creates: /usr/sbin/zabbix_agentd # 如果指定的文件存在,则不执行此任务

系统优化——setup-system

  1. [root@ansible roles]# tree setup-system/ # 目录结构
  2. setup-system/
  3. ├── files
  4. ├── bashrc
  5. ├── ctn
  6. ├── limits.conf
  7. ├── profile
  8. ├── rc.local
  9. ├── rectn
  10. └── sysctl.conf
  11. ├── handlers
  12. └── main.yml
  13. ├── Readme.txt
  14. └── tasks
  15. └── main.yml
  16. # 接下来将依次展示files目录下的文件
  17. [root@ansible roles]# cat setup-system/files/bashrc # bashrc文件
  18. # /etc/bashrc
  19. # System wide functions and aliases
  20. # Environment stuff goes in /etc/profile
  21. # It's NOT a good idea to change this file unless you know what you
  22. # are doing. It's much better to create a custom.sh shell script in
  23. # /etc/profile.d/ to make custom changes to your environment, as this
  24. # will prevent the need for merging in future updates.
  25. # are we an interactive shell?
  26. if [ "$PS1" ]; then
  27. if [ -z "$PROMPT_COMMAND" ]; then
  28. case $TERM in
  29. xterm*|vte*)
  30. if [ -e /etc/sysconfig/bash-prompt-xterm ]; then
  31. PROMPT_COMMAND=/etc/sysconfig/bash-prompt-xterm
  32. elif [ "${VTE_VERSION:-0}" -ge 3405 ]; then
  33. PROMPT_COMMAND="__vte_prompt_command"
  34. else
  35. PROMPT_COMMAND='printf "\033]0;%s@%s:%s\007" "${USER}" "${HOSTNAME%%.*}" "${PWD/#$HOME/~}"'
  36. fi
  37. ;;
  38. screen*)
  39. if [ -e /etc/sysconfig/bash-prompt-screen ]; then
  40. PROMPT_COMMAND=/etc/sysconfig/bash-prompt-screen
  41. else
  42. PROMPT_COMMAND='printf "\033k%s@%s:%s\033\\" "${USER}" "${HOSTNAME%%.*}" "${PWD/#$HOME/~}"'
  43. fi
  44. ;;
  45. *)
  46. [ -e /etc/sysconfig/bash-prompt-default ] && PROMPT_COMMAND=/etc/sysconfig/bash-prompt-default
  47. ;;
  48. esac
  49. fi
  50. # Turn on parallel history
  51. shopt -s histappend
  52. history -a
  53. # Turn on checkwinsize
  54. shopt -s checkwinsize
  55. [ "$PS1" = "\\s-\\v\\\$ " ] && PS1="[\u@\h \W]\\$ "
  56. # You might want to have e.g. tty in prompt (e.g. more virtual machines)
  57. # and console windows
  58. # If you want to do so, just add e.g.
  59. # if [ "$PS1" ]; then
  60. # PS1="[\u@\h:\l \W]\\$ "
  61. # fi
  62. # to your custom modification shell script in /etc/profile.d/ directory
  63. fi
  64. if ! shopt -q login_shell ; then # We're not a login shell
  65. # Need to redefine pathmunge, it get's undefined at the end of /etc/profile
  66. pathmunge () {
  67. case ":${PATH}:" in
  68. *:"$1":*)
  69. ;;
  70. *)
  71. if [ "$2" = "after" ] ; then
  72. PATH=$PATH:$1
  73. else
  74. PATH=$1:$PATH
  75. fi
  76. esac
  77. }
  78. # By default, we want umask to get set. This sets it for non-login shell.
  79. # Current threshold for system reserved uid/gids is 200
  80. # You could check uidgid reservation validity in
  81. # /usr/share/doc/setup-*/uidgid file
  82. if [ $UID -gt 199 ] && [ "`/usr/bin/id -gn`" = "`/usr/bin/id -un`" ]; then
  83. umask 002
  84. else
  85. umask 022
  86. fi
  87. SHELL=/bin/bash
  88. # Only display echos from profile.d scripts if we are no login shell
  89. # and interactive - otherwise just process them to set envvars
  90. for i in /etc/profile.d/*.sh; do
  91. if [ -r "$i" ]; then
  92. if [ "$PS1" ]; then
  93. . "$i"
  94. else
  95. . "$i" >/dev/null
  96. fi
  97. fi
  98. done
  99. unset i
  100. unset -f pathmunge
  101. fi
  102. # vim:ts=4:sw=4
  103. HISTFILESIZE=100
  104. HISTSIZE=100
  105. HISTTIMEFORMAT='[%Y.%m.%d %H:%M:%S]'
  106. export HISTTIMEFORMAT
  107. [root@ansible roles]# cat setup-system/files/limits.conf # limits.conf文件
  108. # /etc/security/limits.conf
  109. #
  110. #This file sets the resource limits for the users logged in via PAM.
  111. #It does not affect resource limits of the system services.
  112. #
  113. #Also note that configuration files in /etc/security/limits.d directory,
  114. #which are read in alphabetical order, override the settings in this
  115. #file in case the domain is the same or more specific.
  116. #That means for example that setting a limit for wildcard domain here
  117. #can be overriden with a wildcard setting in a config file in the
  118. #subdirectory, but a user specific setting here can be overriden only
  119. #with a user specific setting in the subdirectory.
  120. #
  121. #Each line describes a limit for a user in the form:
  122. #
  123. #<domain> <type> <item> <value>
  124. #
  125. #Where:
  126. #<domain> can be:
  127. # - a user name
  128. # - a group name, with @group syntax
  129. # - the wildcard *, for default entry
  130. # - the wildcard %, can be also used with %group syntax,
  131. # for maxlogin limit
  132. #
  133. #<type> can have the two values:
  134. # - "soft" for enforcing the soft limits
  135. # - "hard" for enforcing hard limits
  136. #
  137. #<item> can be one of the following:
  138. # - core - limits the core file size (KB)
  139. # - data - max data size (KB)
  140. # - fsize - maximum filesize (KB)
  141. # - memlock - max locked-in-memory address space (KB)
  142. # - nofile - max number of open file descriptors
  143. # - rss - max resident set size (KB)
  144. # - stack - max stack size (KB)
  145. # - cpu - max CPU time (MIN)
  146. # - nproc - max number of processes
  147. # - as - address space limit (KB)
  148. # - maxlogins - max number of logins for this user
  149. # - maxsyslogins - max number of logins on the system
  150. # - priority - the priority to run user process with
  151. # - locks - max number of file locks the user can hold
  152. # - sigpending - max number of pending signals
  153. # - msgqueue - max memory used by POSIX message queues (bytes)
  154. # - nice - max nice priority allowed to raise to values: [-20, 19]
  155. # - rtprio - max realtime priority
  156. #
  157. #<domain> <type> <item> <value>
  158. #
  159. #* soft core 0
  160. #* hard rss 10000
  161. #@student hard nproc 20
  162. #@faculty soft nproc 20
  163. #@faculty hard nproc 50
  164. #ftp hard nproc 0
  165. #@student - maxlogins 4
  166. * soft nofile 65535
  167. * hard nofile 65535
  168. * soft nproc 65535
  169. * hard nproc 65535
  170. # End of file
  171. [root@ansible roles]# cat setup-system/files/rc.local # rc.local文件
  172. #!/bin/bash
  173. # THIS FILE IS ADDED FOR COMPATIBILITY PURPOSES
  174. #
  175. # It is highly advisable to create own systemd services or udev rules
  176. # to run scripts during boot instead of using this file.
  177. #
  178. # In contrast to previous versions due to parallel execution during boot
  179. # this script will NOT be run after all other services.
  180. #
  181. # Please note that you must run 'chmod +x /etc/rc.d/rc.local' to ensure
  182. # that this script will be executed during boot.
  183. touch /var/lock/subsys/local
  184. ulimit -SHn 65535
  185. if test -f /sys/kernel/mm/transparent_hugepage/enabled; then
  186. echo never > /sys/kernel/mm/transparent_hugepage/enabled
  187. [root@ansible roles]# cat setup-system/files/sysctl.conf # 系统内核优化
  188. kernel.sysrq = 0
  189. kernel.core_uses_pid = 1
  190. fs.file-max=655360
  191. kernel.msgmnb = 65536
  192. kernel.msgmax = 65536
  193. kernel.shmmax = 68719476736
  194. kernel.shmall = 4294967296
  195. kernel.pid_max = 655360
  196. net.ipv4.tcp_tw_reuse = 1
  197. net.ipv4.tcp_tw_recycle = 0
  198. net.ipv4.tcp_max_tw_buckets = 262144
  199. net.ipv4.tcp_fin_timeout = 30
  200. net.ipv4.tcp_timestamps = 1
  201. net.ipv4.tcp_sack = 1
  202. net.ipv4.tcp_window_scaling = 1
  203. net.ipv4.tcp_ecn = 0
  204. net.ipv4.tcp_keepalive_time = 600
  205. net.ipv4.tcp_keepalive_intvl = 30
  206. net.ipv4.tcp_keepalive_probes = 3
  207. net.ipv4.tcp_max_orphans = 655360
  208. net.ipv4.tcp_max_syn_backlog = 262144
  209. net.ipv4.tcp_mem = 65536 131072 262144
  210. net.ipv4.udp_mem = 65536 131072 262144
  211. net.ipv4.tcp_rmem = 4096 87380 16777216
  212. net.ipv4.tcp_wmem = 4096 16384 16777216
  213. net.ipv4.ip_local_port_range = 1024 65535
  214. net.ipv4.route.gc_timeout = 100
  215. # 禁止icmp重定向报文
  216. net.ipv4.conf.all.accept_redirects = 0
  217. # 禁止icmp源路由
  218. net.ipv4.conf.all.accept_source_route = 0
  219. net.core.somaxconn = 65535
  220. net.core.rmem_default = 8388608
  221. net.core.wmem_default = 8388608
  222. net.core.rmem_max = 16777216
  223. net.core.wmem_max = 16777216
  224. net.core.netdev_max_backlog = 262144
  225. vm.swappiness = 3
  226. vm.overcommit_memory = 1
  227. vm.max_map_count = 262144
  228. [root@ansible roles]# cat setup-system/files/profile # 环境变量文件
  229. # /etc/profile
  230. # System wide environment and startup programs, for login setup
  231. # Functions and aliases go in /etc/bashrc
  232. # It's NOT a good idea to change this file unless you know what you
  233. # are doing. It's much better to create a custom.sh shell script in
  234. # /etc/profile.d/ to make custom changes to your environment, as this
  235. # will prevent the need for merging in future updates.
  236. pathmunge () {
  237. case ":${PATH}:" in
  238. *:"$1":*)
  239. ;;
  240. *)
  241. if [ "$2" = "after" ] ; then
  242. PATH=$PATH:$1
  243. else
  244. PATH=$1:$PATH
  245. fi
  246. esac
  247. }
  248. if [ -x /usr/bin/id ]; then
  249. if [ -z "$EUID" ]; then
  250. # ksh workaround
  251. EUID=`/usr/bin/id -u`
  252. UID=`/usr/bin/id -ru`
  253. fi
  254. USER="`/usr/bin/id -un`"
  255. LOGNAME=$USER
  256. MAIL="/var/spool/mail/$USER"
  257. fi
  258. # Path manipulation
  259. if [ "$EUID" = "0" ]; then
  260. pathmunge /usr/sbin
  261. pathmunge /usr/local/sbin
  262. else
  263. pathmunge /usr/local/sbin after
  264. pathmunge /usr/sbin after
  265. fi
  266. HOSTNAME=`/usr/bin/hostname 2>/dev/null`
  267. HISTSIZE=1000
  268. if [ "$HISTCONTROL" = "ignorespace" ] ; then
  269. export HISTCONTROL=ignoreboth
  270. else
  271. export HISTCONTROL=ignoredups
  272. fi
  273. export PATH USER LOGNAME MAIL HOSTNAME HISTSIZE HISTCONTROL
  274. # By default, we want umask to get set. This sets it for login shell
  275. # Current threshold for system reserved uid/gids is 200
  276. # You could check uidgid reservation validity in
  277. # /usr/share/doc/setup-*/uidgid file
  278. if [ $UID -gt 199 ] && [ "`/usr/bin/id -gn`" = "`/usr/bin/id -un`" ]; then
  279. umask 002
  280. else
  281. umask 022
  282. fi
  283. for i in /etc/profile.d/*.sh /etc/profile.d/sh.local ; do
  284. if [ -r "$i" ]; then
  285. if [ "${-#*i}" != "$-" ]; then
  286. . "$i"
  287. else
  288. . "$i" >/dev/null
  289. fi
  290. fi
  291. done
  292. unset i
  293. unset -f pathmunge
  294. PS1='[\[\e[36m\]\#::\[\e[31m\]\u@\[\e[32m\]\h\[\e[36m\]::\w]\$ >>>\[\e[m\]'
  295. [root@ansible roles]# cat setup-system/files/ctn # ctn文件
  296. #!/usr/bin/env bash
  297. if [ $# -ne 1 ];then
  298. echo -e "
  299. Usage: $0 {Container_name | Container ID}
  300. "
  301. exit 1
  302. fi
  303. docker exec -it $1 /bin/bash
  304. [root@ansible roles]# cat setup-system/files/rectn # rectn文件
  305. #!/usr/bin/env bash
  306. if [ $# -ge 2 ] ; then
  307. FILTER="$1"
  308. shift
  309. CMD="$@"
  310. else
  311. echo '请检查参数'
  312. exit 1
  313. fi
  314. if docker ps --format '{{.Names}}' --filter name=$FILTER &> /dev/null; then
  315. C_LIST=$(docker ps --format '{{.Names}}' --filter name=$FILTER)
  316. for C_NAME in $C_LIST; do
  317. echo "---- ${C_NAME}:"
  318. docker exec $C_NAME $CMD
  319. done
  320. else
  321. echo '找不到容器'
  322. exit 2
  323. fi
  324. [root@ansible roles]# cat setup-system/tasks/main.yml # 任务列表
  325. ---
  326. # 禁用Ctrl-Alt-Delete组合键
  327. - name: disable Ctrl-Alt-Delete
  328. file: src=/dev/null dest=/etc/systemd/system/ctrl-alt-del.target state=link
  329. # 内核参数优化
  330. - name: sysctl_config
  331. copy: src=sysctl.conf dest=/etc/sysctl.conf mode=0644
  332. notify:
  333. - sysctl-load
  334. # 记录所有shell命令的执行历史...
  335. - name: copy bashrc
  336. copy: src=bashrc dest=/etc/bashrc mode=0644
  337. notify:
  338. - source bashrc
  339. # 添加 PS1 提示
  340. - name: copy profile
  341. copy: src=profile dest=/etc/profile mode=0644
  342. notify:
  343. - source profile
  344. # 增加打开最大文件描述符...
  345. - name: copy limits.conf
  346. copy: src=limits.conf dest=/etc/security/limits.conf mode=0644
  347. # 时间同步服务器开启
  348. - name: Ensure chronyd is started and enabled at boot.
  349. systemd:
  350. name: chronyd
  351. state: started
  352. enabled: yes
  353. # 取消容器redis的警告
  354. - name: "临时取消透明大页警告,不用重启"
  355. shell: echo never > /sys/kernel/mm/transparent_hugepage/enabled
  356. ignore_errors: True
  357. # 永久生效:redis透明大页
  358. - name: "永久取消透明大页警告,重启生效"
  359. copy: src=rc.local dest=/etc/rc.local
  360. [root@ansible roles]# cat setup-system/handlers/main.yml # 触发任务
  361. ---
  362. - name: sysctl-load
  363. shell: sudo sysctl --system
  364. - name: source bashrc
  365. shell: source /etc/bashrc
  366. - name: source profile
  367. shell: source /etc/profile
  368. - name: source ctn
  369. shell: source /etc/bash_completion.d/ctn

至此,相关的roles文件就展示的差不多了。

执行脚本程序

  1. [root@ansible ansible-init-system]# ./ansible-init.sh -f szy_init_system.yml -u root -p 22 -h node

执行过程如下:

ansible初始化服务器 - 图1

既然都看到这了,那我就把该博文所涉及到的文件打个包供你们下载(提取码:kj4g)吧!