ansible的学习笔记

一、安装
这里使用的是yum进行安装的
yum -y install ansible
二、准备工作
1)进入到ansible的工作路径
/etc/ansible
2)修改hosts文件
hosts文件里可以设置被控制的主机的IP
[webservers]
192.168.154.130
注:[webservers]的名字是可以任意命名,这只是为了后面运行ansible进行
使用的,相当于我们之前的hostname
三、使用
注:ansible可以执行的module(因此在执行的时候使用-m)很多,这里只是
列出来常用的
1)ping一下,看看能否连通
ansible webservers -m ping -u root -k
2)执行shell
ansible webservers -m shell -a 'hostname' -u root -k
##执行shell脚本
建立一个sh文件
vi aaa.sh
#!/bin/bash
echo `date` >> /opt/aaa/aaa.txt
修改权限,不然是没权限进行执行的
chmod 777 aaa.sh
ansible webservers -m shell -a "/opt/aaa.sh" -u root -k\
3)执行command
ansible webservers -m command -a 'pwd' -u root -k
ansible webservers -m command -a "df -h" -u root -k
4)拷贝文件
ansible webservers -m copy -a "src=/opt/aaa.txt
dest=/opt/aaa/aaa.txt owner=root mode=777" -u root -k
5)安装软件
ansible webservers -m yum -a "name=httpd state=latest" -u root -k
[root@host01 opt]# rpm -qa httpd
httpd-2.4.6-88.el7.centos.x86_64
##卸载软件
ansible webservers -m yum -a "name=httpd state=absent" -u root -k
四、应用:安装并运行nginx
在ansible路径下建立一个目录
mkdir nginx_install
批量建立文件夹
mkdir -p roles/nginx/{handlers,files,tasks,templates,vars}
批量新建文件到指定路径下
touch roles/site.yaml roles/nginx/
{handlers,files,tasks,templates,vars}/main.yaml
安装tree,便于后面查看
yum -y install tree
新建文件
echo 1234 > roles/nginx/files/index.html
在ansible主机安装nginx并且拷贝配置文件到我们的剧本文件路径下
yum install -y nginx && cp /etc/nginx/nginx.conf
roles/nginx/templates/nginx.conf.j2
1)编辑tasks
vi roles/nginx/tasks/main.yaml
---
- name: install nginx package
 yum: name={{item}} state=latest
 with_items:
 - epel-release
 - nginx

- name: copy index.html
  copy: src=index.html dest=/usr/share/nginx/html/index.html
- name: copy nginx.conf template
  template: src=nginx.conf.j2 dest=/etc/nginx/nginx.conf
- name: make sure nginx service running
  service: name=nginx state=started enabled=yes

2)修改j2文件
:/worker_processes
nginx默认开启的进程要和CPU数量有关
worker_processes {{ ansible_processor_cores }};
ansible webservers -m setup -a 'filter=ansible_processor_cores' -u
root -k
SSH password: 
192.168.154.130 | SUCCESS => {
    "ansible_facts": {
        "ansible_processor_cores": 1
    }, 
    "changed": false
}

:/worker_connections
工作进程数
events {
    worker_connections {{ worker_connections }};//自定义变量
}

3)编辑vars
vi roles/nginx/vars/main.yaml
worker_connections: 20000
4)编辑handlers
vi roles/nginx/handlers/main.yaml
---
- name: restart nginx
  service: name=nginx state=restarted
5)编辑入口
- hosts: webservers
  roles:
  - nginx
6)执行剧本(播放剧本)
ansible-playbook site.yaml


 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值