春风十里不如你 —— Taozi - ansible https://www.xiongan.host/index.php/tag/ansible/ 【ansible】linux下的集群管理服务 https://www.xiongan.host/index.php/archives/137/ 2022-11-08T17:33:00+08:00 介绍ansible是新出现的自动化运维工具,基于Python开发,集合了众多运维工具(puppet、cfengine、chef、func、fabric)的优点,实现了批量系统配置、批量程序部署、批量运行命令等功能。Ansible架构相对比较简单,仅需通过SSH连接客户机执行任务即可主机名ip角色Server192.168.123.195主控Backend01192.168.123.196被控01Backend02192.168.123.197被控02安装ansible准备eple源这边使用的是阿里云的源wget -O /etc/yum.repos.d/epel.repo https://mirrors.aliyun.com/repo/epel-7.repo下载完成后就可以安装ansible服务yum install -y ansible openssh-clients配置ansible修改配置文件 vim /etc/ansible/ansible.cfg //* 71 行,取消注释。开启关闭对未连接的主机 SSH 秘钥检测 host_key_checking = False编写 Ansible 主机管理文件mv /etc/ansible/hosts /etc/ansible/hosts.bak ##先备份一下内容 vi /etc/ansible/hosts ##建立目标群组,并写入被管机(目标服务器)的 IP/FQDN [tz1101] backend01 backend02测试连通性ansible tz1101 -m pingTip:配置ssh免密才可以出现上面结果的配置ssh免密登陆ssh-keygen一路回车,默认免密通信ssh-copy-id ip/主机名把密钥发送到集群主机中另外在需要/etc/hosts中写入主机名和ipansible应用添加用户为集群主机添加单独用户ansible tz1101 -m user -a 'name=tao state=present'添加完成用户后再设置一个密码,在server端用pip python 生成哈希密码首先安装pip pythonyum install python-pip -y生成密码ansible tz1101 -m user -a 'name=tao password=tarRU/F9EJjRU update_password=always'查看一下playbook剧本测试集群安装一个httpd软件的playbook剧本vim playbook_create_install.yml #编写剧本文件→安装软件 - hosts: tz1101 #集群组名 tasks: - name: install vsftpd ##任务名称 yum: name=vsftpd state=installed ##安装vsftpd - name: running and enabled service: name=vsftpd state=started enabled=yes ##设置开机自启动使用tag标签创建tag文件yml注:自定义了tag,他就会只执行带有tag=test2的内容其他标签内容不会执行使用变量自定义变量安装服务- hosts: tz1101 become: yes become_method: sudo tasks: - name: installed bao yum: name={{ item }} state=installed with_items: - vim-enhanced ##软件名 - wget - unzip tags: Taozhengansible-playbook bianliang.ymlroles内网中需要关闭防火墙和selinuxansible tz1101 -a "setenforce 0 && systemctl stop firewalld"在当前server主机内安装tree服务yum install -y tree群组下的主机也要安装tree软件ansible tz1101 -m yum -a "name=tree state=installed"/*-m 使用模块 yum命令 -a是具体内容 name是tree state是操作安装创建roles子目录及内容mkdir -p roles/ins_httpd/{files,tasks,vars}回到roles,编写一个yml文件Vim playbook_httpd.yml - hosts: tz1101 roles: - ins_httpd 编写vars下的main文件 vim roles/ins_httpd/vars/main.yml packages: - httpd创建任务剧本编写tasks下的main文件 vim roles/ins_httpd/tasks/main.yml - name: httpd is installed yum: name=httpd state=installed tags: install_httpd - name: edit httpd.conf lineinfile: > dest=/etc/httpd/conf/httpd.conf regexp="{{item.regexp}}" line="{{item.line}}" with_items: - { regexp: "^#ServerName",line: "ServerName {{ansible_fqdn}}:80" } tags: edit_httpd.conf - name: httpd is running and enabled service: name=httpd state=started enabled=yes - name: put index.html copy: src=index.html dest=/var/www/html owner=root group=root mode=0644执行剧本ansible-playbook playbook_httpd.yml查看写入的httpd的index.htmlansible tz1101 -m shell -a "curl localhost"