ansibles使用

目录

 

查看帮助文档

ansible命令的参数

ansible的配置文件

ping模块

命令模块(command/shell/raw)

command 模块

shell 模块

raw模块

实现批服务器无密码登录

copy模块

script模块批量运行脚本

playbook使用

实例1 ,使用copy模块

实例2,将echo的输出结果返回

 变量使用

 template 模块

 playbook的notify和下发

 使用role标准化playbook


查看帮助文档

 

查看所有的模块的帮助文档

[root@miner-k ~]# ansible-doc -l
a10_server                                Manage A10 Networks AX/SoftAX/Thunder/vThunder devices' server object.
a10_server_axapi3                         Manage A10 Networks AX/SoftAX/Thunder/vThunder devices
a10_service_group                         Manage A10 Networks AX/SoftAX/Thunder/vThunder devices' service groups.
a10_virtual_server                        Manage A10 Networks AX/SoftAX/Thunder/vThunder devices' virtual servers.
accelerate                                Enable accelerated mode on remote node
aci_aep                                   Manage attachable Access Entity Profile (AEP) on Cisco ACI fabrics (infra:At...
aci_ap                                    Manage top level Application Profile (AP) objects on Cisco ACI fabrics (fv:A...
aci_bd                                    Manage Bridge Domains (BD) on Cisco ACI Fabrics (fv:BD)
aci_bd_subnet                             Manage Subnets on Cisco ACI fabrics (fv:Subnet)

查看指定模块(ping)的帮助文档

[root@miner-k ~]# ansible-doc -s ping
- name: Try to connect to host, verify a usable python and return `pong' on success
  ping:
      data:                  # Data to return for the `ping' return value. If this parameter is set to `crash', the module
                               will cause an exception.

 

ansible命令的参数

参数作用
-i INVENTORY指定主机列表,eg: ansible -i /etc/ansible/hosts
-m 指定ansible的模块
-u指定登录远程主机的用户名默认是root
-k指定远程主机的密码
-a指定模块对用的参数

 

 

 

 

 

 

 

[root@miner-k ~]# ansible -i /etc/ansible/hosts test -u root  -m ping -k
SSH password:
192.168.47.130 | SUCCESS => {
    "changed": false,
    "ping": "pong"
}

注意: test 指定test组的所有服务器,如果是所有hosts中的服务器,可以使用all


[root@miner-k ~]# cat /etc/ansible/hosts
[test]
192.168.47.130

ansible的配置文件

  • 主机清单列表 /etc/ansible/hosts
# Ex 1: 直接指定主机.

## green.example.com
## blue.example.com
## 192.168.100.1
## 192.168.100.10

# Ex 2: 分组指定主机下面是 'webservers' 组

## [webservers]
## alpha.example.org
## beta.example.org
## 192.168.1.100
## 192.168.1.110

# 如果有多台主机可以如下设置

## www[001:006].example.com

# Ex 3: 将所有的有关数据库的服务器写在 'dbservers' 组

## [dbservers]
##
## db01.intranet.mydomain.net
## db02.intranet.mydomain.net
## 10.25.1.56
## 10.25.1.57

ansible_ssh_user  指定远程登录主机的用户名

ansible_ssh_host    指定远程登录主机的IP地址

ansible_ssh_pass    指定远程登录主机的密码

ansible_ssh_port     指定远程登录主机的端口

ansible_ssh_private_key_file=   指定私钥的存放位置

ansible_key_checking=false  第一次登录时,不需要输入yes/no

 

主机组之间可以相互嵌套

[database:children]
mysql
maridb
noSQL
[mysql]
10.10.10.10
[maridb]
10.10.30.10
[noSQL]
10.10.20.10

如果对database操作的时候会对所有的子节点操作。

  • 配置文件

 

ping模块

[root@miner-k ~]# cat /etc/ansible/hosts
[test]
192.168.47.130 ansible_ssh_port=22 ansible_ssh_host=192.168.47.130 ansible_ssh_pass=123

[test2]
192.168.47.128 ansible_ssh_port=22 ansible_ssh_host=192.168.47.130 ansible_ssh_pass=123


# all 对所有的主机组进行ping操作

[root@miner-k ~]# ansible all -m ping
192.168.47.128 | SUCCESS => {
    "changed": false,
    "ping": "pong"
}
192.168.47.130 | SUCCESS => {
    "changed": false,
    "ping": "pong"
}


#  指定一个test组进行ping检查

[root@miner-k ~]# ansible test -m ping
192.168.47.130 | SUCCESS => {
    "changed": false,
    "ping": "pong"
}
[root@miner-k ~]# ansible test:test1 -m ping
 [WARNING]: Could not match supplied host pattern, ignoring: test1

192.168.47.130 | SUCCESS => {
    "changed": false,
    "ping": "pong"
}
[root@miner-k ~]# ansible test:test2 -m ping
192.168.47.130 | SUCCESS => {
    "changed": false,
    "ping": "pong"
}
192.168.47.128 | SUCCESS => {
    "changed": false,
    "ping": "pong"
}

命令模块(command/shell/raw)

command 模块

不能使用管道符(|)、重定向(‘>>’    '<<')

[root@miner-k ~]# ansible test -m command -a 'pwd'
192.168.47.130 | SUCCESS | rc=0 >>
/root

shell 模块

可以使用管道符、重定向,如果有特殊字符需要使用转义符

[root@miner-k ~]# ansible test -m shell -a 'cat /etc/passwd | awk -F":" "{print \$1}"'
192.168.47.130 | SUCCESS | rc=0 >>
root
bin
daemon

raw模块

shell模块是基于python的,如果有一些python模块不能使用,可以使用raw模块

[root@miner-k ~]# ansible test -m raw -a 'a=1;echo $a'
192.168.47.130 | SUCCESS | rc=0 >>
1
Shared connection to 192.168.47.130 closed.

 

实现批服务器无密码登录

1.生成密钥对

[root@miner-k ~]# ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):
/root/.ssh/id_rsa already exists.
Overwrite (y/n)? y
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:QDMS91nRMr8f/pW44Wo7NzVv9RzkSkYpbbAsJ4TbCWA root@miner-k
The key's randomart image is:
+---[RSA 2048]----+
|    oE* . oo     |
|    .+ * +o..    |
|      . B o++ .  |
|       o = =.= . |
|        S + +.o  |
|            .oo=o|
|            o=o+B|
|           o.+= *|
|          .o=o.o.|
+----[SHA256]-----+

2. 跳过远程登录时的密钥检查

# 可以在客户端将StrictHostKeyChecking设置为no,或者在/etc/ansible/hosts中设置跳过密码检查

[root@miner-k ~]# grep Checking /etc/ssh/ssh_config
StrictHostKeyChecking no

3. 将公钥推送到目标服务器

[root@miner-k ~]# ansible all -m raw -a '(umask 077; echo $publicKey >> ~/.ssh/authorized_keys)'
127.0.0.1 | SUCCESS | rc=0 >>
Shared connection to 192.168.47.131 closed.


192.168.47.128 | SUCCESS | rc=0 >>
Shared connection to 192.168.47.130 closed.


192.168.47.130 | SUCCESS | rc=0 >>
ControlSocket /root/.ansible/cp/370cfc0dbc already exists, disabling multiplexing
Connection to 192.168.47.130 closed.

 

copy模块

能实现批量下发文件或者文件夹

copy模块的参数含义
src=指定需要拷贝的文件路径
dest=指定需要拷贝文件的目标主机存放路径
back=是否备份
owner=设置拷贝到目标服务器之后,文件的属主
group=设置拷贝到目标服务器之后,文件的属组
mode=设置文件或目录的权限

 

 

 

 

 

 

 

 

实例1: 拷贝文件到指定的服务器

[root@miner-k ~]# ansible test -m copy -a 'src=/etc/passwd dest=/root/'
192.168.47.130 | SUCCESS => {
    "changed": true,
    "checksum": "c8a664bf150bab5326ef0e4d79c09201199989be",
    "dest": "/root/passwd",
    "gid": 0,
    "group": "root",
    "md5sum": "0fb06014b5a00ab12a714eb9a1bdb758",
    "mode": "0644",
    "owner": "root",
    "size": 798,
    "src": "/root/.ansible/tmp/ansible-tmp-1545344956.34-214624546366555/source",
    "state": "file",
    "uid": 0
}

实例2: 拷贝文件夹到指定的服务器中

[root@miner-k ~]# ansible test -m copy -a 'src=/root/dir1 dest=/root/'
192.168.47.130 | SUCCESS => {
    "changed": true,
    "dest": "/root/",
    "src": "/root/dir1"
}

实例3:自动备份目标服务器上的相同文件

 注意如果文件内容没有变化,是不会生成备份的。

[root@miner-k ~]# ansible test -m copy -a 'src=/root/dir1/a.txt dest=/root/ backup=1'
192.168.47.130 | SUCCESS => {
    "backup_file": "/root/a.txt.2468.2018-12-21@06:39:42~",
    "changed": true,
    "checksum": "a4ee26cea582492544445727d3788dfbf4569010",
    "dest": "/root/a.txt",
    "gid": 0,
    "group": "root",
    "md5sum": "ec1ac12ab85dbcdbf7b3b506314fe9b4",
    "mode": "0644",
    "owner": "root",
    "size": 5,
    "src": "/root/.ansible/tmp/ansible-tmp-1545345582.02-277801486519732/source",
    "state": "file",
    "uid": 0
}

实例4 : 设置目标服务器的文件属性

[root@miner-k ~]# ansible test -m copy -a 'src=/root/dir1/a.txt dest=/root/ backup=1 owner=tom group=tom'
192.168.47.130 | SUCCESS => {
    "changed": true,
    "checksum": "a4ee26cea582492544445727d3788dfbf4569010",
    "gid": 1000,
    "group": "tom",
    "mode": "0644",
    "owner": "tom",
    "path": "/root/a.txt",
    "size": 5,
    "state": "file",
    "uid": 1000
}

script模块批量运行脚本

原理:将本地的文件传到指定的服务器上,执行完毕之后删除脚本

[root@miner-k ~]# cat a.sh
#!/bin/bash

echo aaaaa
touch a.txt



[root@miner-k ~]# ansible test -m script -a '/root/a.sh'
192.168.47.130 | SUCCESS => {
    "changed": true,
    "rc": 0,
    "stderr": "Shared connection to 192.168.47.130 closed.\r\n",
    "stdout": "aaaaa\r\n",
    "stdout_lines": [
        "aaaaa"
    ]
}

playbook使用

[root@miner-k ~]# cat test.yml
---
- hosts: all
  tasks:
  - name: test1
    shell: echo "cabd" > /root/a.dd


内容解释:
hosts 指定主机组,all代表的是所有的主机组,可以在指定hosts中的主机组或者直接指定IP地址
tasks 指定要执行的任务。
name 是定义test的名称
shell  使用shell模块,后面跟shell 模块的参数

使用ansible-pllaybook命令执行yaml文件 

# 执行yaml文件

[root@miner-k ~]# ansible-playbook test.yml

PLAY [all] ****************************************************************************************************************

TASK [Gathering Facts] ****************************************************************************************************
ok: [192.168.47.130]
ok: [192.168.47.128]
ok: [127.0.0.1]

TASK [test1] **************************************************************************************************************
changed: [127.0.0.1]
changed: [192.168.47.130]
changed: [192.168.47.128]

PLAY RECAP ****************************************************************************************************************
127.0.0.1                  : ok=2    changed=1    unreachable=0    failed=0
192.168.47.128             : ok=2    changed=1    unreachable=0    failed=0
192.168.47.130             : ok=2    changed=1    unreachable=0    failed=0

 

实例1 ,使用copy模块

将/root目录下的a.dd文件拷贝到所有的主机组上。

---
- hosts: all
  tasks:
  - name: copy test
    copy: src=/root/a.dd dest=/tmp/

实例2,将echo的输出结果返回

---
- hosts: all
  tasks:
  - name: copy test
    shell: echo "abcd"

上面这个yaml文件使用ansible-playbook运行之后结果返回到管理机上,

---
- hosts: all
  tasks:
  - name: test1
    shell: echo "cabd"
    register: echo_str
  - debug: var=echo_str

regitster 接受echo的输出的结果,debug 输出接受的变量结果。 

 变量使用

 可以自定义变量,在tasks中使用自定义变量

---
- hosts: test
  vars:
  - name: "tom"
    age: 12

  tasks:
  - name: echo variables
    shell: echo "{{ name }} is {{ age }} year old."
    register: echo_str
  - debug: var=echo_str

ansible有内置变量,查询方法 ansible test -m setup。

输出指定服务器的IP地址和cpu的核数。

---
- hosts: test

  tasks:
  - name: echo variables
    shell: echo "IP {{ ansible_all_ipv4_addresses[0] }} ,cpu {{ansible_processor_vcpus}}."
    register: echo_str
  - debug: var=echo_str

 template 模块

copy模块可以将本地的文件拷贝到指定的服务器上,但是无法直接修改配置文件中的值。template模块,可以根据不同的服务器生成不同的配置文件。

---
- hosts: test2
  vars:
    myname: "tom"

  tasks:
  - name: template test
    template: src=/root/config dest=/tmp/
  - name: test echo
    shell: echo "acbd" > /tmp/abc
[root@miner-k ~]# cat config
my name is {{myname}}
master is {{ ansible_hostname}}

hostname is {{ansible_nodename}}

 playbook的notify和下发

notify和handlers 是要一起使用的

---
- hosts: test2
  tasks:
  - name: nginx config
    template: src=/root/config dest=/tmp/
    notify:
    - reload nginx
  handlers:
  - name: reload nginx
    shell: systemctl reload nginx

 使用role标准化playbook

[root@miner-k myrole]# tree .
.
├── main.retry
├── main.yml
└── roles
    └── nginx
        ├── files     使用copy模块和script模块从该文件夹中找
        │   ├── add.sh
        │   └── copy_config
        ├── handlers    用来存放notify
        ├── tasks        用来存储ansible的模块任务
        │   └── main.yml
        ├── templates    保存temple模块需要拷贝的文件
        │   └── template_config
        └── vars    保存相关的变量
            └── main.yml

1. 配置文件的入口 main.yml

[root@miner-k myrole]# cat main.yml
---
- hosts: all
  roles:
  - nginx

2. 按照上面的目录结构创建目录树

3. files目录中存放的内容

[root@miner-k files]# cat add.sh
#!/bin/bash

echo "hello test" > /tmp/abcdddd
[root@miner-k files]# cat copy_config
hello world !!!!

 4. tasks目录中存放的内容

[root@miner-k tasks]# cat main.yml
---
- name: check alive
  ping:

- name: hostname
  shell: echo " name {{myname}} TEL {{tel}}"
  register: host_name
- debug: var=host_name

- name: copy
  copy: src=copy_config dest=/tmp

- name: script
  script: add.sh

- name: template
  template: src=template_config dest=/tmp

5. template目录中存放的内容

[root@miner-k nginx]# cat templates/template_config
name:{{myname}}
TEL:{{tel}}

6. vars目录中存放的内容

[root@miner-k nginx]# cat vars/main.yml
---
myname: "tom"
tel: 123456789


 

参考文档:

[ansible指导文档](https://docs.ansible.com/ansible/latest/index.html)

[yaml语法](https://docs.ansible.com/ansible/latest/reference_appendices/YAMLSyntax.html)

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值