Ansible使用
大约 6 分钟
介绍
Ansible 是一个配置管理和应用部署工具。
- Ansible 中文权威指南: https://ansible-tran.readthedocs.io/en/latest/index.html
- GitHub 地址:https://github.com/ansible/ansible
Ansible 安装
官方安装地址:https://cn-ansibledoc.readthedocs.io/zh_CN/latest/installation_guide/intro_installation.html#
1、安装 ansible
yum install ansible –y
## 查看版本
ansible --version
2、编译安装
yum -y install python-jinja2 PyYAML python-paramiko python-babel python-crypto
# 需要提前安装Python环境(略)
wget https://releases.ansible.com/ansible/ansible-2.9.27.tar.gz
tar xf ansible-2.9.27.tar.gz
cd ansible-2.9.27 && ls -al
python setup.py build
python setup.py install
mkdir -p /etc/ansible
cp -r examples/* /etc/ansible/
3、Git 源码安装
git clone https://github.com/ansible/ansible.git
cd ansible
git checkout stable-2.9
source ./hacking/env-setup
4、pip 安装
yum install python-pip python-devel
yum install gcc glibc-devel zibl-devel rpm-bulid openss1-devel
pip install -U pip
pip install ansible --upgrade
Ansible 相关文件说明
目录结构
- /etc/ansible/ 配置文件目录
- /etc/ansible/ansible.cfg 主配置文件,配置 ansible 工作特性
- /etc/ansible/hosts 主机清单文件,管理的目标主机地址清单
- /etc/ansible/roles/ 存放角色的目录
- /usr/bin/ 执行文件目录
主配置文件介绍
默认的主配置文件,一般无需修改
vi /etc/ansible/ansible.cfg (部分主要的配置)
[defaults]
#inventory = /etc/ansible/hosts # 主机列表配置文件
#library =/usr/share/my_modules/ # 库文件存放目录
#remote_tmp = $HOME/.ansible/tmp # 临时py命令文件存放在远程主机目录
#local_tmp = $HOME/.ansible/tmp # 本机的临时命令执行目录
#forks = 5 # 默认并发数
#sudo_user = root # 默认sudo用户
#ask_sudo_pass = True # 每次执行ansible命令是否询间ssh密码
#ask_pass = True # 是否询问密码
#remote_port = 22 # 默认的远程登录端口
host_key_checking = False # 检查对应服务器的host_key,建议取消注释
log_path=/var/log/ansible.log # 日志文件,建议启用
#module_name = command # 默认模块,可以修改为shell模块
Inventory 主机清单文件
配置受控 hosts 地址或者域名地址
vi /etc/ansible/hosts
[test]
192.168.60.90
192.168.60.[95:96]
Ansible 相关命令
###### ansible ######
ansible --version
ansible "*" --list-hosts
## 检查清单文件
ansible-inventory -i host.yaml --graph
ansible 192.168.60.* -m ping
ansible test -m ping
###### ansible-doc ######
## 主要用于显示针对某个模块的使用方法的帮助信息
## 列出所有模块
ansible-doc -l
## 查看指定模块帮助用法
ansible-doc copy
## 查看指定模块帮助用法[简化版的帮助]
ansible-doc -s copy
###### 点对点命令 ######
## ansible [模式] -m [模块] -a "[模块选项]"
ansible 192.168.60.* -m shell -a 'cat /etc/passwd |grep "root"'
ansible test -m shell -a 'cat /etc/passwd |grep "root"'
ansible test -m shell -a "echo '6666' >> /opt/demo.txt"
###### 文件管理
## 将文件从本地系统复制到远程系统
echo "123456789" >> ~/number.txt
ansible test -m copy -a "src=~/number.txt dest=/opt/"
ansible test -m command -a "ls -lh /opt/"
ansible test -m command -a "cat /opt/number.txt"
## 将文件/opt/number.txt 权限更改为 777
ansible test -m file -a "dest=/opt/number.txt mode=777"
## 删除/opt/number.txt 文件
ansible test -m file -a "dest=/opt/number.txt state=absent"
## 递归删除指定目录
ansible test -m command -a "mkdir -p /opt/demo/zhang"
ansible test -m command -a "ls -lh /opt"
ansible web -m file -a "dest=/opt/demo state=absent"
###### 用户管理
## 新增用户
ansible test -m user -a "name=testuser password=testuser"
## 删除用户
ansible test -m user -a "name=testuser state=absent"
##### 管理包
## 安装httpd
ansible test -m yum -a "name=httpd state=latest"
## 卸载httpd
ansible test -m yum -a "name=httpd state=absent"
###### 管理服务
## 停止 httpd 服务:
ansible test -m service -a "name=httpd state=stopped"
## 启动 httpd 服务:
ansible test -m service -a "name=httpd state=started"
## 重启 httpd 服务:
ansible test -m service -a "name=httpd state=restarted"
Ansible 剧本
- name: [脚本描述]
hosts: group [添加主机或主机组]
become: true [如果你想以 root 身份运行任务,则标记它]
tasks: [你想在任务下执行什么动作]
- name: [输入模块选项]
module: [输入要执行的模块]
module_options-1: value [输入模块选项]
module_options-2: value
...
module_options-N: value
安装 Apache Web 服务器
mkdir -p ~/ansible/playbooks
cat > ~/ansible/playbooks/apache.yml << EOF
- hosts: test
become: yes
name: "Install and Configure Apache Web server"
tasks:
- name: "Install Apache Web Server"
yum:
name: httpd
state: latest
- name: "Ensure Apache Web Server is Running"
service:
name: httpd
state: started
EOF
## 检查剧本文件的正确性
ansible-playbook ~/ansible/playbooks/apache.yml --syntax-check
## 不会对远程机器进行任何修改。相反,它会告诉你它将要做什么改变但不是真的执行
ansible-playbook ~/ansible/playbooks/apache.yml --check
## 执行剧本文件任务
ansible-playbook ~/ansible/playbooks/apache.yml
## 命令查看状态
ansible test -m command -a "systemctl status httpd"
安装软件包列表
mkdir -p ~/ansible/playbooks
cat > ~/ansible/playbooks/packages.yml << EOF
- hosts: test
become: yes
name: "Install a List of Packages on Red Hat Based System"
vars:
packages: [ 'curl', 'git', 'htop' ]
tasks:
- name: "Installing Security Update on Red Hat Based System"
yum: name=* update_cache=yes security=yes state=latest
when: ansible_facts['distribution'] == "CentOS"
- name: "Installing Security Update on Ubuntu Based System"
apt: upgrade=dist update_cache=yes
when: ansible_facts['distribution'] == "Ubuntu"
- name: Install a list of packages
yum: name={{ item }} state=latest
with_items: "{{ packages }}"
when: ansible_facts['distribution'] == "CentOS"
EOF
## 执行剧本文件任务
ansible-playbook ~/ansible/playbooks/packages.yml
安装nginx
cat > install_nginx.yml << EOF
---
- hosts: all
tasks:
- name: Installs nginx web server
yum: name=nginx state=installed update_cache=true
notify:
- start nginx
handlers:
- name: start nginx
service: name=nginx state=started
EOF
# “handlers” 部分与“hosts”、“tasks” 处于同一级别。handlers就像任务,但它们只有在客户端系统发生了更改的任务被告知时才运行。
# 例如,我们在这里有一个handlers,在安装软件包后启动Nginx服务。除非 “Installs nginx web server” 任务导致系统更改,否则不会调用处理程序,这意味着包必须安装,并且之前没有被安装。
ansible-playbook install_nginx.yml
使用 Block/Rescue 来恢复或回滚
- name: block test
hosts: node1
tasks:
- block:
- debug: msg="vg myvg not found" # 提示卷组没找到
- debug: msg="create vg myvg .. .." # 做其他操作(比如创建这个卷组...)
when: ('myvg' not in ansible_lvm.vgs) # 当卷组myvg不存在时
rescue:
- debug: msg="creating failed .. .." # block失败时提示创建卷组失败
always:
- shell: vgscan # 列出卷组信息
register: list # 保存到名为list的变量
- debug: msg={{list.stdout_lines}} # 提示卷组扫描结果
K8s 安装
cat > ~/k8s.yml << EOF
- name: init k8s
hosts: all
tasks:
# 关闭防火墙
- shell: firewall-cmd --set-default-zone=trusted
# 关闭selinux
- shell: getenforce
register: out
- debug: msg="{{out}}"
- shell: setenforce 0
when: out.stdout != "Disabled"
- replace:
path: /etc/selinux/config
regexp: "SELINUX=enforcing"
replace: "SELINUX=disabled"
- shell: cat /etc/selinux/config
register: out
- debug: msg="{{out}}"
- copy:
src: ./hosts
dest: /etc/hosts
force: yes
# 关闭交换分区
- shell: swapoff -a
- shell: sed -i '/swap/d' /etc/fstab
- shell: cat /etc/fstab
register: out
- debug: msg="{{out}}"
# 配置yum源
- shell: tar -cvf /etc/yum.tar /etc/yum.repos.d/
- shell: rm -rf /etc/yum.repos.d/*
- shell: wget ftp://ftp.rhce.cc/k8s/* -P /etc/yum.repos.d/
# 安装docker-ce
- yum:
name: docker-ce
state: present
# 配置docker加速
- shell: mkdir /etc/docker
- copy:
src: ./daemon.json
dest: /etc/docker/daemon.json
- shell: systemctl daemon-reload
- shell: systemctl restart docker
# 配置属性,安装k8s相关包
- copy:
src: ./k8s.conf
dest: /etc/sysctl.d/k8s.conf
- shell: yum install -y kubelet-1.21.1-0 kubeadm-1.21.1-0 kubectl-1.21.1-0 --disableexcludes=kubernetes
# 缺少镜像导入
- copy:
src: ./coredns-1.21.tar
dest: /root/coredns-1.21.tar
- shell: docker load -i /root/coredns-1.21.tar
# 启动服务
- shell: systemctl restart kubelet
- shell: systemctl enable kubelet
EOF
角色
## 生成一个角色目录
ansible-galaxy init demo
tree -L 2
# ├── defaults 定义变量的缺省值,优先级较低
# │ └── main.yml
# ├── files 存放一些静态文件
# ├── handlers 定义handlers处理任务
# │ └── main.yml
# ├── meta 定义作者、版本、兼容性、依赖项等描述信息
# │ └── main.yml
# ├── README.md 描述自述信息
# ├── tasks 任务入口,最主要的文件
# │ └── main.yml
# ├── templates 存放模板文件
# ├── tests 用于角色测试
# │ ├── inventory
# │ └── test.yml
# └── vars 定义变量,相对于defaults优先级更高
# └── main.yml