Ansible

Ansible优点:
Stupied Simple,上手简单,学习曲线平滑
SSH by default,安全,无需安装客户端
配置简单、功能强大、扩展性强
支持API及自定义模块。可通过Python轻松扩展
通过Playbooks来定制强大的配置、状态管理
提供一个功能强大、操作性强的Web管理界面和REST API接口——AWX平台
幂等性:一种操作重复多次结果相同 已经执行过的任务再次执行显示ok,这就是幂等性:一种操作重复多次结果相同
--------
-C, --check 运行检查,不执行任何操作
-e EXTRA_VARS,--extra-vars=EXTRA_VARS 设置附加变量 key=value
-u REMOTE_USER, --user=REMOTE_USER SSH连接用户,默认None
-k, --ask-pass SSH连接用户密码
-b, --become 提权,默认root
-K, --ask-become-pass 提权密码
命令行使用
ansible all -m ping
ansible all -m shell -a "ls /root" -u root -k
ansible webservers -m copy –a "src=/etc/hosts dest=/tmp/hosts"
ansible-doc –l 查看所有模块
ansible-doc –s copy 查看模块文档
==================
1、shell
- name: 将命令结果输出到指定文件
shell: somescript.sh >> somelog.txt
- name: 切换目录执行命令
shell:
cmd: ls -l | grep log
chdir: somedir/
- name: 编写脚本
shell: |
if [ 0 -eq 0 ]; then
echo yes > /tmp/result
else
echo no > /tmp/result
fi
args:
executable: /bin/bash
------------------------------------------------------------
------------------------------------------------------------
ansible webservers -m shell -a "ls /root;df -h"
-------------------------------------------------------------
将文件复制到远程主机。
- name: 拷贝文件
copy:
src: /srv/myfiles/foo.conf
dest: /etc/foo.conf
owner: foo
group: foo
mode: u=rw,g=r,o=r
# mode: u+rw,g-wx,o-rwx
# mode: '0644'
backup: yes
-------------------------------------------------------------
管理文件和文件属性。
- name: 创建目录
file:
path: /etc/some_directory
state: directory
mode: '0755'
- name: 删除文件
file:
path: /etc/foo.txt
state: absent
- name: 递归删除目录
file:
path: /etc/foo
state: absent
-------------------------------------------------------------
absent:表示卸载
present,latest:表示安装
##########################软件包管理
- name: 安装最新版apache
yum:
name: httpd
state: latest
- name: 安装列表中所有包
yum:
name:
- nginx
- postgresql
- postgresql-server
state: present
- name: 卸载apache包
yum:
name: httpd
state: absent
- name: 更新所有包
yum:
name: '*'
state: latest
- name: 安装nginx来自远程repo
yum:
name: http://nginx.org/packages/rhel/7/x86_64/RPMS/nginx-1.14.0-1.el7_4.ngx.x86_64.rpm
# name: /usr/local/src/nginx-release-centos-6-0.el6.ngx.noarch.rpm
state: present
-------------------------------------------------------------
###################debug 执行过程中打印语句。
- debug:
msg: System {{ inventory_hostname }} has uuid {{ ansible_product_uuid }}

- name: 显示主机已知的所有变量
debug:
var: hostvars[inventory_hostname]
verbosity: 4
-------------------------------------------------------------
语法检查与调试
语法检查:ansible-playbook --check /path/to/playbook.yaml
测试运行,不实际操作:ansible-playbook -C /path/to/playbook.yaml
-------------------------------------------------------------
条件:
tasks:
- name: 只在192.168.1.100运行任务
debug: msg="{{ansible_default_ipv4.address}}"
when: ansible_default_ipv4.address == '192.168.1.100'
循环:
tasks:
- name: 批量创建用户
user: name={{ item }} state=present groups=wheel
with_items:
- testuser1
- testuser2
- name: 解压
copy: src={{ item }} dest=/tmp
with_fileglob:
- "*.txt"
-------------------------------------------------------------
-------------------------------------------------------------
-------------------------------------------------------------

ansible连通性测试: ansible testhosts -m ping
执行命令测试: ansible testhosts -m command -a 'uptime'
第二种方法:
vim /etc/ansible/hosts
ansible_ssh_user=root ansible_ssh_port=22 ansible_ssh_pass=root
在hosts文件的末尾添加
[testhosts]
192.168.30.149 ansible_ssh_user=root ansible_ssh_port=22 ansible_ssh_pass=root
192.168.30.151 ansible_ssh_user=root ansible_ssh_port=22 ansible_ssh_pass=root
保存退出进行ansible连通性测试
[root@c1 ~]# ansible testhosts -m ping
192.168.30.149 | FAILED! => {
"msg": "Using a SSH password instead of a key is not possible because Host Key checking is enabled and sshpass does not support this. Please add this host's fingerprint to your known_hosts file to manage this host."
}
192.168.30.151 | FAILED! => {
"msg": "Using a SSH password instead of a key is not possible because Host Key checking is enabled and sshpass does not support this. Please add this host's fingerprint to your known_hosts file to manage this host."
出现上面问题是因为启用了主机密钥检查,所以我们可以修改/etc/ansible/ansible.cfg配置文件来跳过这个检查
[root@c1 ~]# vim /etc/ansible/ansible.cfg
host_key_checking = False #默认是注释的,打开注释即可 ################################################333
保存退出再测试结果正常:
[root@c1 ~]# ansible testhosts -m ping ################################3
192.168.30.151 | SUCCESS => {
"changed": false,
"ping": "pong"
}
192.168.30.149 | SUCCESS => {
"changed": false,
"ping": "pong"
}
6.ansible常用命令
ansible-doc -l #查看支持的模块
ansible-doc -s MODEL_NAME #查看模块用法
ansible命令应用基础
ansible <host-pattern> [options]
-f fork:启动并发 线程数
-m model_name:要使用的模块
-a args:特有的参数
ansible all -m ping #查看client端是否正常ping通
ansible webserver -m setup #查看客户端信息
ansible webserver -m copy -a 'src=/root/git_test/code.txt dest=/root/test' #copy文件到client端
ansible webserver -m user -a "name=test state=present" #创建test用户
ansible webserver -m user -a "name=test state=absent" #删除test用户
ansible webserver -m yum -a 'name=epel-relese state=latest' #yum安装
ansible webserver -m systemd -a 'name=httpd state=stopped enabled=no' #停止httpd服务
ansible webserver -m script -a '/tmp/test,sh' #运行脚本
ansible webserver -m command 'date' #查看时间
7.playbooks:
一个任务代表一个play,多个play组合成叫做playbooks
一个yaml或yml文件就是一个playbooks
yaml介绍
yaml是一个可读性高的用来表达资料序列的格式,yaml参考了其他多种语言,包括:xml,c语言,python,perl以及电子邮件格式RFC2822等,ClarkEvans在2001年在首次发表了这种语言。
yaml的可读性好
yaml和脚本语言的交互性好
yaml使用实现语言的数据类型
yaml有一个一致的信息模型
yaml易于实现
yaml可以基于流程来处理
yaml表达能力强,扩展性好
ansible执行yaml/yml文件格式:
ansible-playbook *.yml/*.yaml
例1:playbook基础语法比较严格
- hosts: testhosts #声明主机组
remote_user: root #声明以谁的身份执行
tasks: #任务组
- name: yum remove nginx #任务名
yum: name=nginx state=absent #模块:用法
- name: yum install httpd
yum: name=httpd state=latest
- name: systemctl start httpd
systemd: name=httpd state=started
ansible-playbook test.yml
-------------------------------------------------
ansible和 ansible-playbook使用方式
  Ansible命令是ansible提供的命令行工具,基于hosts清单来使用,具体如下:
  ansible <host组名> [-f 并发数量] [-m 模块名字] [-a args] -i host清单名
默认的Host 清单配置文件在/etc/ansible/hosts,也可以定制新的路径。内容格式与window下的.ini文件类似。
  #hosts
  [web]
  192.168.100.10
  192.168.100.11
  [db]
  192.168.100.11
  192.168.100.12
这里定义了俩个组,服务器可以是名字也可以是IP地址,同一个服务器可以属于不同的组。
用用户root向所有的服务器发ping命令,-k需要输入root密码,也可以现将所有服务器的密钥批量添加到本地,就可以无交互操作远程机器。
  $ ansible all -m ping -u root -k -i hosts
  SSH password:
  192.168.100.10 | success >> {
  "changed": false,
  "ping": "pong"
  }
  192.168.100.11 | success >> {
  "changed": false,
  "ping": "pong"
  }
  192.168.100.12 | success >> {
  "changed": false,
  "ping": "pong"
  }
  默认不指定-m参数的时候使用的module只是执行命令,不会用一些shell下的environment变量等设置
  copy|file--文件复制及文件属性设置
  $ansible dbservers -m copy -a "src=/etc/hosts dest=/tmp/hosts"
  $ansible webservers -m file -a "dest=/srv/foo/test.txt mode=600 owner=test group=test"
  git--使用git指定服务器
  $ansible webservers -m git -a "repo=git://test.example.org/repo.git dest=/srv/myapp version=HEAD"
  service--对指定服务操作
  ansible webservers -m service -a "name=httpd state=started"
  命令行工具提供简单任务操作,实际部署应用常常需要很多操作。ansible-playbook则可以按照一定先后顺序和逻辑关系事先定义好所有操作,然后一次完成所有的部署任务。

=============================================================================================
=============================================================================================
一个playbook的示例
- hosts: webserver //定义的主机组,即应用的主机
vars: //定义变量
http_port: 80
max_clients: 200
user: root
tasks: //执行的任务
- name: ensure apache is at the latest version #友好提示,自己定义
yum: pkg=httpd state=latest #检查httpd包是不是最新版本
- name: write the apache config file
template: src=/srv/httpd.j2 dest=/etc/httpd.conf
notify: #调用触发下面具体的操作
- restart apache
- name: ensure apache is running
service: name=httpd state=started
handlers: //处理器
- name: restart apache #调这个操作
service: name=httpd state=restarted

执行一个playbook
ansible-playbook [yaml文件名]
例如:ansible-playbook ping.yml
参数:-k(–ask-pass) 用来交互输入ssh密码
-K(-ask-become-pass) 用来交互输入sudo密码
-u 指定用户
补充命令:
ansible-playbook nginx.yml --syntax-check #检查yaml文件的语法是否正确
ansible-playbook nginx.yml --list-task #检查tasks任务
ansible-playbook nginx.yml --list-hosts #检查生效的主机
ansible-playbook nginx.yml --start-at-task='Copy Nginx.conf' #指定从某个task开始运行
实验环境
=====================
ansible-playbook 单个yml文件部署tomcat简单示例
#单yaml配置
[root@jenkins pb]# cat tomcat.yml
---
- hosts: eee
vars:                                           #设置变量
war_files: /var/lib/jenkins/workspace/java_test/target/huizhongph.war    #本地war包路径
tomcat_root: /root/tomcat_hzph_pc_9090/webapps/huizhongph           #远端tomcat目录

tasks:
- name: 关闭tomcat
shell: chdir={{ tomcat_root }}/../../bin nohup ./shutdown.sh &
- name: backup old code                            #备份当前正在使用的源码
shell: chdir={{ tomcat_root }}/../ tar -czf /bak/huizhongph_$(date -d "today" +"%Y%m%d_%H%M%S").tar.gz huizhongph &

- name: 删除旧版本的配置文件
file:
state: absent
dest: "{{ tomcat_root }}"

- name: clean cache|清除缓存
shell: chdir={{ tomcat_root }}/../../ nohup rm -rf work &

- name: 创建目录
file:
state: directory
dest: "{{ tomcat_root }}"
mode: 755

- name: 解压war包
unarchive:
src: "{{ war_files }}"
dest: "{{ tomcat_root }}"
copy: yes

- name: 覆盖(替换)配置文件
copy: src=/root/{{ item }} dest=/root/test/{{ item }}    #这里指定配置文件的路径为本地路径
with_items:                              #要替换的配置文件
- a.txt
- b.txt
- c.txt
- d.txt
- shell (目录)

- name: 启动tomcat
shell: chdir={{ tomcat_root }}/../../bin nohup ./startup.sh &
执行命令
ansible-playbook -i /xxx/xxx/host tomcat.yml
ps2
========================
ansible-playbook使用实例(分发文件,执行脚本)
技术标签: ansible linux playbook yml 文件分发

ansible-playbook使用实例
在这里插入图片描述
change.yml
hosts: gameservers #要操作的主机组,在ansible的hosts文件中定义(默认安装位置/etc/ansible/hosts)
serial: 20 #开启的并发数
remote_user: root #进行操作的用户
tasks: #要进行的操作
name: fenfa #任务名称,自定义
copy: #使用复制模块,进行文件分发,从本地主机分发到远程主机
src: ‘{{ item.src }}’ #源文件,我这里有多个源文件,所有采用了定义变量的方法,可参考ansible循环内容http://www.ansible.com.cn/docs/playbooks_loops.html#standard-loops
dest: /usr/local/zabbix/scripts/ #文件复制的目标目录
owner: zabbix
group: zabbix
mode: 0700
with_items:
{ src: ‘/home/ma/change_agent.sh’ } #源文件
{ src: ‘/home/ma/check_diskio.sh’ }
{ src: ‘/home/ma/get_diskname.sh’ }
{ src: ‘/home/ma/get_linecpu.sh’ }
{ src: ‘/home/ma/mysql_statu.sh’ }
name: backup #使用command模块,复制备份远程主机上的文件
command: cp -a /usr/local/zabbix/etc/zabbix_agentd.conf /usr/local/zabbix/etc/zabbix_agentd.conf.bak
name: doshell #执行分发到目标主机的shell脚本
shell: /bin/bash /usr/local/zabbix/scripts/change_agent.sh
name: restart #用command模块进行服务重启
command: service zabbix_agentd restart
执行playbook
ansible-playbook -C change.yml
-C 预执行,可以看到执行后会有什么变化,但不会再远程主机上实际执行这些操作
实际执行:
ansible-playbook change.yml
########ps3===============================================
使用 Ansible 统计服务器资源利用率 统计服务器 CPU、内存、磁盘利用率,3 条 shell 脚本实现统计:
CPU 利用率统计:
top -bn1 | grep load | awk '{printf "CPU Load: %.2f ", $(NF-2)}'
内存利用率统计:
free -m | awk 'NR==2{printf "Memory Usage: %s/%sMB (%.2f%%) ", $3,$2,$3*100/$2 }'
磁盘利用率统计(列出每块磁盘利用率):
df -h -t ext2 -t ext4 | grep -vE '^Filesystem|tmpfs|cdrom' | awk '{ print "Disk Usage:"" " $1 " " $3"/"$2" ""("$5")"}'
Ansible playbook: server-cpu-mem-disk-usage.yml
---
- name: Statistics CPU Memory Disk Utilization
hosts: "{{ hosts }}"
become: no
remote_user: "{{ user }}"
gather_facts: no
tasks:
- name: "Statistics CPU Memory Disk Utilization..."
shell: |
free -m | awk 'NR==2{printf "Memory Usage: %s/%sMB (%.2f%%) ", $3,$2,$3*100/$2 }'
df -h -t ext2 -t ext4 | grep -vE '^Filesystem|tmpfs|cdrom' | awk '{ print "Disk Usage:"" " $1 " " $3"/"$2" ""("$5")"}'
top -bn1 | grep load | awk '{printf "CPU Load: %.2f ", $(NF-2)}'
register: out
- debug: var=out.stdout_lines

输出结果样例:
ok: [gke-test-standard-pool] => {
"out.stdout_lines": [
"Memory Usage: 8766/16052MB (54.61%)",
"Disk Usage: /dev/root 449M/1.2G (37%)",
"Disk Usage: /dev/sda8 28K/12M (1%)",
"Disk Usage: /dev/sda1 61G/95G (64%)",
"CPU Load: 0.92"
]
}
==================ps 5==========
ansible的硬件巡检脚本
for i in {1..100}
do
sshpass -p ' 123456' ssh-copy-id -o StrictHostKeyChecking=no root@172.16.255.$i
done
或者
sshpass -p123456 ssh-copy-id -i /root/.ssh/id_dsa.pub -o StrictHostKeyChecking=no 172.16.1.$i &>/dev/null
ansible all -m shell -a "disk=$(expr `df |awk '{print $2}'|sort -nr|head -1` / 1048576) && cpu=$(cat /proc/cpuinfo| grep 'cpu cores'| wc -l),&& men=$(free -h|grep 'Mem'|awk '{print $2}') && echo -e '$disk , $cpu , $men'" > test.csv
==================ps 6==========

zhaisongfang
原文地址:https://www.cnblogs.com/zhaisongfang/p/14010821.html