Ansible

Ansible 基础

  1. ANSIBLE_CONFIG 环境变量,可以定义配置文件的位置
  2. ./ansible.cfg 存在于当前工作目录
  3. ~/.ansible.cfg 存在于当前用户家目录
  4. /etc/ansible/ansible.cfg 默认目录

Ansible命令

主机要求:
windows除外

配置语言:
yaml,json
只有server

role:
ansible 可以重复使用的

Ansible:

https://github.com/ansible/ansible

从release下载安装包

需要pip安装包的依赖

log:

https://www.cnblogs.com/xielisen/p/6817807.html

查看文件个数:
ls -l | grep ‘^-‘ | wc -l

##################################马哥 Ansible

文件传输
命令执行:应用部署,配置管理,任务流编排

企业应用场景:
开发,测试,发布,生产,灰度环境(基于主机,用户,地区)

vie0 修改主机ip

ansible -m ping
m:模块
ansible 127.0.0.1 -m ping

在 /etc/ansible/hosts中配置主机清单

测试网络通讯;

ansible 192.168.1.101 -m ping -k 

输入口令(密码)
k: 密码认证
建议基于key验证

etc/ssh/sshd_config  
ansible all -m ping  

all: 代表主机清单的所有主机

ansible.cfg

ansible.cfg

forks=5     并发执行5

ansible-doc:显示模块命令

ansible websevers –list-hosts

ansible all –list-host

ansible debserver -m ping -u wang -k 以wang的身份去连接

ansible debserver -m command -a ‘ls /root’ -u wang -k -b -K
以wang身份连接,切换到root用户权限,默认为root -K root口令

usermod -a -G wheel wang 将wang加入到组

K的口令;
sudo中:取消下面一行的注释:
%wheel ALL=(ALL) NOPASSWD:ALL

基于key验证

ssh-keygen
ssh-copy-id 192.168.80.101
ssh-copy-id 192.168.80.102
.......

& linux中表示后台执行

ansible all -m command -a “sleep 10”
休眠10s

command:

ansible all -a ‘ls /data’

ansible all -a ‘df -h’

ansible-doc command

creates 存在不执行

ansible all -a ‘removes=/etc/fs cat /etc/fstab’

removes 不存在不执行

ansible all -a ‘creates=/etc/fs cat /etc/fstab’

chdir 切换文件夹

ansible all -a ‘chdir=/root ls’

ansible 192.168.80.101 -a ‘/data/test.sh’

执行该主机上/data/test.sh

注: 注意规范 #!/bin/bash

创建账号:

ansible all -a 'useradd test1'

查询:

ansible all -a 'getent passwd test1'

command 命令对管道,重定向,变量 特殊符号支持有问题,建议shell

shell:

ansible all -m shell -a 'echo $HOSTNAME'

更改口令:

ansible all -m shell -a 'echo magedu|passwd --stdin test1'

script:

chmod +x test.sh

ansible all -m script -a ‘/root/ansible/test.sh’
在所有主机上执行test.sh

ansible all -a ‘getenforce’

cp /etc/sysconfig/selinux >
vim selinux

copy:
ansible-doc -s copy

ansible all -m copy -a ‘src=/root/ansible/selinux dest=/etc/selinux/config backup=yes’
文件复制

ansible all -m shell -a ‘getenforce’

ansible all -m copy -a ‘src=/etc/shadow dest=/data mode=000 owner=root’

ansible all -m copy -a ‘content=”hello\n thanks \n “ dest=/data/f2’
直接写内容生成文件

fetch:
从客户端去文件到服务器端,与copy相反

ansible all -m fetch -a ‘src=/var/log/messages dest=/data’
从远程主机抓取log/message,到服务器,仅限单个文件

ansible all -m shell -a ‘tar jcf log.tar.xz /var/log/*.log’

包的加压与解压
archive
unarchive

file:

ansible all -m file -a ‘name=/data/f3 state=touch’ 创建文件

ansible all -m file -a ‘name=/data/f3 state=absent’ 删除文件

ansible all -a ‘ls -l /data’

ansible all -m file -a ‘name=/data/dir1 state=directory’ 创建文件夹,’state=absent’ 删除

‘src=/etc/fstab dest=/data/fstab.link state=link’ 创建软连接

‘dest=/data/fstab.link state=absent’ 删除软连接

‘dest=/data/* state=absent’ 删除所有文件

‘dest=/data/ state=absent’ 删除文件夹

不能删除挂载点上的

ansible 192.168.80.101 -m hostname -a ‘name=new_name’ 修改主机名

cron:

ansible all -m cron -a ‘minute=* weekday=1,3,5 job=”/usr/bin/wall FBI warning” name=warningcron’ 创建定时报警任务,写入crontab

ansible all -m cron -a ‘disabled=true job=”/usr/bin/wall FBI warning” name=warningcron’ 禁用此任务,必须加name

‘job=”/usr/bin/wall FBI warning” name=warningcron state=absent’ 删除

yum
/etc/yum.repos/base.repo yum仓库配置

ansible all -m yum -a ‘name=vsftpd’
安装
多个软件用’,’隔开

ansible all -m yun -a ‘list=instealled’ 安装过的列表

‘name=vsftpd state=removed’卸载

‘name=vsftpd state=absent’

‘rpm -q vsftpd’ 查找是否卸载

安装下载好的软件;
ansible all -m copy -a ‘src=/data/softname dest=/root/‘

ansible all -a ‘ls /root/‘

ansbile all -m yum -a ‘name=/root/softname’

disable_gpg_check=yes 忽略,禁用

‘name=dstat update_cache=yes’ 更新缓存

services:

ansible all -m services -a ‘name=vsftpd state=started enabled=yes’
启动服务,同时设为开机启动

user:

ansible all -m user -a ‘name=nginx shell=/sbin/nologin system=yes home=/var/nginx groups=root,bin uid=80 comment=”nginx service”‘

创建账号

ansible all -m user -a ‘name=nginx state=absent remove=yes’ 删除账号,删除home目录

group:

ansible all -m group -a ‘name=nginx system=yes gid=80’

ansible all -a ‘getent group nginx’

ansible -m group -a ‘name=nginx state=absent’ 删除

ansible-galaxy:

ansible-galaxy install geerlingguy.nginx

yml/yaml:

注意缩进,格式

---
-hosts:webserver
remote_user:root

tasks:
    -name:hello
    command:hostname

ansible-playbook test.yaml

ansible-vault:
ansible-vault encrypt test.yaml 对文件进行加密,避免敏感信息泄露

需要设置加密口令,再次执行yaml时会报错,

ansible-vault decrypt test.yaml 解密

ansible-vault view test.yaml 查看yaml需要输入口令

ansible-vault rekey test.yaml 修改密码

ansible-vault create test2.yaml 创建新的playbook文件

ansible-console:

交互式:
ansible-console

“root@all (3)[f:5]$ “ 并发数量为5也可以修改forks 10

cd 192.168.80.135 切换到135主机

hostname name=node2.magedu.com 修改主机名

playbook

playbook采用YAMl语言编写

1.# test yaml 注释
2.缩进必须统一

---
- hosts:webserver
remote_user:root

tasks:
    - name:create new file  #描述
    file:name=/data/newfile state=touch   模块/命令
    - name:create new user
    user: name=test2 
    - name: install httpd
    yum:name=httpd
    - name:copy conf
    copy:src=/etc/conf dest=/etc/conf
    - name:start service
    service:name=httpd state=started enables=yes

ansible-playbook -C file.yml # -C 检查

ansible all -a ‘getent passwd test2’ #查看test2用户

ansible all -m shell -a ‘ss -tln | grep :80’ #查看80端口

ansible all -a ‘getent passwd test2’ –limit 192.168.80.134

ansibel-playbook file.yml –list

ansibel-playbook file.yml –list-tasks

- name:copy a file
copy:src=files/test.py dest=/etc/test.py  #files相对路径,相对于当前目录

注:文件修改后再次执行copy,不会生效

更新配置文件,执行playbook后,并不会生效

http.yml
---
- hosts: webserver
remote_user:root
tasks:
    - name:install https package
    yum:name-httpd
    - name: copy conf file
    copy: src=files/httpd.conf dest=/etc/httpd/conf baskup=yes
    - name: start service
    service: name=httpd state=started enabled=yes

执行http.yml,修改配置文件后,执行不会重启

http.yml
---
- hosts: webserver
  remote_user:root

  tasks:
    - name:install https package
    yum:name-httpd
    tag:inshttpd
    - name: copy conf file
    copy: src=files/httpd.conf dest=/etc/httpd/conf baskup=yes
    notify:restart service
    - name: start service
    service: name=httpd state=started enabled=yes
    tag:rshttpd

  handlers:
    - name: restart service
      service: name=http state=restarted

也可以同时触发两个任务

tags:

添加标签,可以单独执行标签

多个动作共用一个标签

ansible-playbook -t rshttpd httpd.yml

ansible-playbook -t inshttpd,rshttpd httpd.yml

setup:

ansible all -m setup -a ‘filter=ansible_hostname’

ansible all -m setup -a ‘filter=address‘\

ansible all -m setup -a ‘filter=ansible_all_ipv4_address’

app.yml
---
- hosts: webserver
remote_user: root

tasks:
    - name: install packing
    yum: name={{ pkname }}
    - name: start service
    service: name={{ pkname }} state=started enabled=yes

ansible-playbook -e ‘pkname=httpd’ app.yml

pkname 不会写死,灵活定义

也可以同时装多个包,用逗号隔开

eg:

---
- hosts:websever
  remote_user: root

  vars:
    - pkname1: httpd
    - pkname2: vsftpd
  tasks:
    - name:install pachage
      yum: name={{ pkname1 }}
    - name: install package
      yum: name={{ pkname2 }}

定义变量在playbook中,

hostname.yml:

---
- hosts: webserver
  rempte_user: root

  tasks:
    - name: set hostname
      hostname: name= www{{http_port}}.magedu.com

hosts:

[webserver:vars]
nodenamw=www
domainname=magedu.com

此处的变量对webserver所有主机有效

tasks:
  - name: set hostname
    hostname:name={{nodename}}{{http_port}}.{{domasinname}}

命令行优先级高于配置文件

ansible all -m setup
ansible all -m setup -a ‘filter=”ansbile_fqdn”‘

var.yml

---
- hosts:webserver
renote_use: root

tasks:
    - name: create a file
    file: name=/data/{{ ansible_fqdn }}.log state=touch mode=600 owner=wang

ansible-playbook -c var.yml

vars.yml

var1: httpd
var2: vsftpd

testvars.yml
---
- hosts: webserver
  remote_user: root
  vars_file:
    - vars.yml
  tasks:
    - name:install package
      yum: name={{ var1 }}
    - name: create file
      file: name= /data/{{ var2 }}.log state=touch

template.yml

---
- hosts: webserver
remote_user: root

tasks: 
    - name: install package
    tum: name=nginx
    - name: copy template
    template: src=nginx.conf.j2 dest=/etc/nginx/nginx.conf
    - name start service
    service: name=nginx state=started enabled=yes

ansible all -m shell -a ‘ss -ntpl’ #查看端口

nginx.conf中修改:

worker_processes NaN #cpu个数的2次方

修改template.yml

---
- hosts: webserver
remote_user: root

tasks: 
    - name: install package
    tum: name=nginx
    - name: copy template
    template: src=nginx.conf.j2 dest=/etc/nginx/nginx.conf
    notify: start service
    - name start service
    service: name=nginx state=started enabled=yes
handlers:
    - name: restart service
      service: name=nginx state=restarted

ansible all -m shell -a ‘ps aux | grep nginx’ #过滤nginx进程

hosts:也可以写成如下模式

[webserver]
192.168.80.134 http_port=81
192.168.80.135 http_port=82

ansible-playbook -e ‘http_port=99’ testtemp.yml #修改端口

优先级:命令行>playbook>主机清单

ansibel all -m setup -a ‘filte=ansible_os_family’

‘filter=”distribution“‘

testitem.yml

---
- hosts: webserver
remote_user: root

tasks:
    - name: create some files
      file: name=/data/{{ item }} state=touch
      when: ansible_distribution_major_version == "7"
      with_items:
        - file1
        - file2
        - file3

    - name: install spme package
      yum: name={{ item }}

      with_items:
        - htop
        - sl
        - hping3

create_group.yml

---
- hosts: all
  remote_user: root

  tasks:
    - name: create some groups
      group: name={{ item }}
      when: ansible_distribution_major_version == "7"
      with_items:
        - g1
        - g2 
        - g3

创建用户,并加入到组

---
- hosts: all
  remote_user: root

  tasks:
    - name: create some groups
      group: name={{ item }}
      when: ansible_distribution_major_version == "7"
      with_items:
        - g1
        - g2 
        - g3
    - name:create some users
      user: name={{item.name}} group={{item.group}}
      with_items:
        - { name: 'user1', group: 'g1' }
        - { name: 'user2', group: 'g2' }
        - { name: 'user3', group: 'g3' }

for:

testfor.yml

---
- hosts: all
  remote_user: root
  vars:
    ports:
      - 81
      - 82
      - 83

  tasks:
    - name: copy conf
      template: src=for1.conf.j2 dest=/data/for1.conf

创建文件:for1.conf.j2

{% for port in ports %}
    server{
        listen {{ port }}
    }
    {% endfor %}

修改为字典模式:

---
- hosts: all
  remote_user: root
  vars:
    ports:
      - listen_port:81
      - listen_port:82
      - listen_port:83

  tasks:
    - name: copy conf
      template: src=for2.conf.j2 dest=/data/for1.conf   

for2.conf.j2

{% for port in ports %}
    server{
        listen {{ port.listen_port }}
    }
    {% endfor %}

---
- hosts: all
  remote_user: root
  vars:
    ports:
      - web1:
        port: 81
        name: web1.magedu.com
        rootdir: /data/website1
      - web2:
        port: 83
        name: web2.magedu.com
        rootdir: /data/website2
      - web3:
        port: 83
        name: web3.magedu.com
        rootdir: /data/website3

  tasks:
    - name: copy conf
      template: src=for3.conf.j2 dest=/data/for1.conf 

for3.conf.j22

{% for p in ports %}
    server{
        listen {{ p.port }}
        servername {{ p.name }}
        documentroot {{ p.rootdir }}
    }
    {% endfor %}

---
- hosts: all
  remote_user: root
  vars:
    ports:
      - web1:
        port: 81
        #name: web1.magedu.com
        rootdir: /data/website1
      - web2:
        port: 83
        name: web2.magedu.com
        rootdir: /data/website2
      - web3:
        port: 83
        #name: web3.magedu.com
        rootdir: /data/website3

  tasks:
    - name: copy conf
      template: src=for4.conf.j2 dest=/data/for4.conf

for4.conf.j22

{% for p in ports %}
    server{
        listen {{ p.port }}
    {% if p.name is defined %}
        servername {{ p.name }}
    {% endif %}
        documentroot {{ p.rootdir }}
    }
    {% endfor %}

roles

创建roles文件夹:

mkdir roles

mkdir roles/{httpd, mysql, memcache} -pv

mkdir roles/nginx

ansible all -m shell -a ‘rpm -q nginx’

‘getent group nginx’

‘userdel -f nginx’ 删除用户,组

cd nginx

mkdir tasks templates

cd tasks

vim group.yml

- name:create group
  group: name=nginx gid=80

vim user.yml

- name: create user
  user: name=nginx group=nginx system=yes shell=/sbin/nologin uid=80

vim yum.yml

- name: install package
  yum: name=nginx

vim start.yml

- name: start service
  service: name=nginx state=started enabled=yes

vim restart.yml

- name: restart service
  sservice: name=nginx  state=restarted

templates:

nginx.conf.j2(nginx.conf重命名为此)

vim temp.yml

- name: copy conf
  template: src=nginx.conf.j2 dest=/etc/ngiunx/nginx.conf

vim main.yml

- include: group.yml
- include: user.yml
- include: yum.yml
- include: temp.yml
- include: start.yml

调用的剧本与roles同级

vim nginx_role.yml

- hosts: all
  remote_usr: root

  roles:
    - role: nginx

ansibel-playbook -c nginx_role.yml


httpd_roles

mkdir tasks

vim user.yml

- name: create user
  user: name=apache system=yes shell=/sbin/nologin

vim copyfile.yml

- name: copy file
  file: src= dest=

httpd:

tasks:

vim user.yml

- name: create user
  user: name=apache system=yes shell=/sbin/nologin

vim copyfile.yml

- name: copy file
  copy: src=httpd.conf dest=/data/

vim main.yml

- include: user.yml
- include: copyfile.yml

vim httpd_role.yml

- hosts: all
  remote_user: root

  roles:
    - role: httpd

在一个角色中,调用另一个角色

vim some_role.yml

- hosts: all
  remote_user:root

  roles:
    - role: http
    - role: nginx

一个角色引用另一个角色中的任务
在main.yml中添加一行

- include: roles/httpd/tasks/copyfileyml

此处需要注意路径的选择

ansible.cfg

当playbook失败的情况下,一个重试文件将会创建,后缀为retry,默认开启此功能

添加标签:
some_role.yml

---
- hosts: all
  remote_user: root

  roles:
    - { role: httpd, tags:['web', 'httpd'] }    #即属于web,也属于httpd
    - { role: nginx, tags:['web', 'nginx'] }

ansible-playbook -t web some_role.yml #只执行标签web

some_role.yml

---
- hosts: all
  remote_user: root

  roles:
    - { role: httpd, tags:['web', 'httpd'] }    #即属于web,也属于httpd
    - { role: nginx, tags:['web', 'nginx'] , when: ansible_distribution_major_version == '7'}    # 当版本为7的时候执行

mkdir app
cd app
mkdir tasks templates vars handlers files

task:

vim group.yml

- name: create group
  group: name=app system=yes gid=123

vim user.yml

- name: create user
  user: name=app group=app system=yes shell=/sbin/nologin uid=1223

vim yum.yml

- name: isntall package
  yum: name=httpd

vim templ.yml

- name: copy conf
  template: src=httpd.conf.j2 dest=/etc/httpd/conf/httpd.conf
  notify: restart service

vars:
main.yml

username:app
groupname: app

handlers:
vim main.yml

- name: restart service
  service: name=httpd state=restarted

tasks:
vim start.yml

- name: start service
  service: name=httpd state=started enabled=yes

vim copyfile.yml

- name: copy config
  copy: src=vhosts.conf dest=/etc/httpd/conf.d/ owner=app

vim main.yml

- include: group.yml
- include: user.yml
- include: yum.yml
- include: templ.yml
- include: copyfile.yml
- include: start.yml

files:
touch vhosts.conf


app_role.yml

- hosts: all
  remote_user: root

  roles:
    - app

memcached:

yum install memcached

cat /etc/sysconfig/memcached

cp /etc/sysconfig/memcached templates/memcached.j2
修改:
CACHESIZE=”NaN“

vim tasks/yum.yml

- name: install package
  yum: name=memcached

vim taska/start.yml

- name: start service
  service: name=memcached state=started enabled=yes

vim /tasks/templ.yml

- name: copy conf
  templates: src=memcached.j2 dest=/etc/sysconfig/memcached

vim tasks/main.yml

- include: yum.yml
- include: templ.yml
- include: start.yml

vim memcached_role.yml

- hosts: all
  remote_user: root

  roles:
    - memcached

ansible-playbook -C memecached_role.yml

ansible-playbook memcached_role.yml