ansible

ssh准备

远程主机时候询问是否保存node机器密钥
自动信任对方
方法一:

[root@centos8 ~]#vim /etc/ssh/ssh_config
   StrictHostKeyChecking no

方法二:
配置ansible的配置文件实现
取消第一次连接节点主机时 检查对应服务器的host_key,

[root@centos8 ~]#vim /etc/ansible/ansible.cfg
host_key_checking = False

ansible实现基于key验证脚本

Note:执行过程中只有一到多的单项执行成功,目标是多对多并且双向。
后续有时间改进

[root@centos8 ~]#bash ssh_key_v1.sh
awk: warning: escape sequence `\/' treated as plain `/'
mv: cannot stat '/root/.ssh/': No such file or directory
Generating public/private rsa key pair.
Created directory '/root/.ssh'.
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:5bbV4QovIHgkIi7rmDfrJ3yUNfP2GDgXz7wBqXRP9Wc root@centos8.magedu.org
The key's randomart image is:
+---[RSA 3072]----+
|                 |
|            .    |
|. . . .  ... ..  |
|.. . += =o.  o..E|
|..  .+oBSO+ . oo |
|..  o.+.=o*= .   |
|.. .   + +ooo    |
|o.= o   . o.     |
|o+o*             |
+----[SHA256]-----+
sshpass-1.06-9.el8.x86_64
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys

Number of key(s) added: 1

Now try logging into the machine, with:   "ssh -o 'StrictHostKeyChecking=no' '10.0.0.5'"
and check to make sure that only the key(s) you wanted were added.

Warning: Permanently added '10.0.0.6' (ECDSA) to the list of known hosts.
Warning: Permanently added '10.0.0.7' (ECDSA) to the list of known hosts.
Warning: Permanently added '10.0.0.182' (ECDSA) to the list of known hosts.
Warning: Permanently added '10.0.0.160' (ECDSA) to the list of known hosts.
/root/.ssh/know_hosts: No such file or directory
/root/.ssh/know_hosts: No such file or directory
/root/.ssh/know_hosts: No such file or directory
/root/.ssh/know_hosts: No such file or directory
/root/.ssh/know_hosts: No such file or directory

为主机组指定python版本变量

报错

root@ubuntu:~#ansible zabbix -m ping 
10.0.0.83 | FAILED! => {
    "changed": false, 
    "module_stderr": "Shared connection to 10.0.0.83 closed.\r\n", 
    "module_stdout": "/bin/sh: 1: /usr/bin/python: not found\r\n", 
    "msg": "MODULE FAILURE", 
    "rc": 127
}

/usr/bin/python3.6无用
解决使用ansible提示python模块找不到

root@ubuntu:~#vim /etc/ansible/hosts 

[zabbix]
10.0.0.[82:85]
[zabbix:vars]
ansible_python_interpreter=/usr/bin/python3

测试单条命令指定解释器也行

root@ubuntu:~#ansible zabbix -m ping -e 'ansible_python_interpreter=/usr/bin/python3'
10.0.0.83 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}

模块

ping

一般情况下用来检测主机是否在线

[root@ansible-node1 ~]#ansible all -m ping
10.0.0.5 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": false,
    "ping": "pong"
}
10.0.0.7 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": false,
    "ping": "pong"
}
10.0.0.160 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": false,
    "ping": "pong"
}

command 模块

在/data/test创建文件夹

[root@ansible-node1 ~]#ansible websrvs -m command -a 'creates=/data/test mkdir /data/test'
[WARNING]: Consider using the file module with state=directory rather than running 'mkdir'.  If you need to use
command because file is insufficient you can add 'warn: false' to this command task or set 'command_warnings=False'
in ansible.cfg to get rid of this message.
10.0.0.7 | CHANGED | rc=0 >>

10.0.0.6 | SUCCESS | rc=0 >>
skipped, since /data/test exists
#验证
[root@ansible-node1 ~]#ansible websrvs -m command -a 'ls -l /data/test'
10.0.0.7 | CHANGED | rc=0 >>
total 0
10.0.0.6 | CHANGED | rc=0 >>
total 16
-rw-r--r-- 1 root root  17 Jun 29 19:35 a.txt.orig

#使用command模块创建文件夹
[root@ansible-node1 ~]#ansible websrvs -m command -a 'creates=/data/test mkdir /data/test'
10.0.0.7 | SUCCESS | rc=0 >>
skipped, since /data/test exists
10.0.0.6 | SUCCESS | rc=0 >>
skipped, since /data/test exists

shell 模块

支持command模块不支持的管道、重定向、通配符等

[root@ansible-node1 ~]#ansible websrvs -m shell -a 'echo hello > /data/hello.log'
10.0.0.7 | CHANGED | rc=0 >>

10.0.0.6 | CHANGED | rc=0 >>

[root@ansible-node1 ~]#ansible websrvs -m shell -a 'cat /data/hello.log'
10.0.0.7 | CHANGED | rc=0 >>
hello
10.0.0.6 | CHANGED | rc=0 >>
hello

#变量测试
[root@ansible-node1 ~]#ansible websrvs -m shell -a 'echo $HOSTNAME'
10.0.0.7 | CHANGED | rc=0 >>
centos8.magedu.org
10.0.0.6 | CHANGED | rc=0 >>
centos8.magedu.org

[root@ansible-node1 ~]#ansible websrvs -m command -a 'echo $HOSTNAME'
10.0.0.7 | CHANGED | rc=0 >>
$HOSTNAME
10.0.0.6 | CHANGED | rc=0 >>
$HOSTNAME

修改ansible的默认模块command为shell模块

[root@ansible-node1 ~]#vim /etc/ansible/ansible.cfg
# default module name for /usr/bin/ansible
#module_name = command
module_name = shell

script 模块

Run a script with arguments (free form)

[root@ansible-node1 ~]#chmod +x test.sh
[root@ansible-node1 ~]#cat test.sh
#!/bin/bash
ip a | grep -Eo '10.0.0.*'| awk -F'/.*' '{print $1,$2}'
[root@ansible-node1 ~]#ansible websrvs -m script -a '/root/test.sh'
10.0.0.6 | CHANGED => {
    "changed": true,
    "rc": 0,
    "stderr": "Shared connection to 10.0.0.6 closed.\r\n",
    "stderr_lines": [
        "Shared connection to 10.0.0.6 closed."
    ],
    "stdout": "10.0.0.6 \r\n",
    "stdout_lines": [
        "10.0.0.6 "
    ]
}
10.0.0.7 | CHANGED => {
    "changed": true,
    "rc": 0,
    "stderr": "Shared connection to 10.0.0.7 closed.\r\n",
    "stderr_lines": [
        "Shared connection to 10.0.0.7 closed."
    ],
    "stdout": "10.0.0.7 \r\n",
    "stdout_lines": [
        "10.0.0.7 "
    ]
}

copy 模块

[root@ansible-node1 ~]#ansible websrvs -m copy -a "src=ping.sh dest=/data/"
10.0.0.7 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": true,
    "checksum": "f3adc75ae43f5b248baa332e57319200d62c27f3",
    "dest": "/data/ping.sh",
    "gid": 0,
    "group": "root",
    "md5sum": "17e5ef4191a7a60771ae5af291870cf6",
    "mode": "0644",
    "owner": "root",
    "size": 179,
    "src": "/root/.ansible/tmp/ansible-tmp-1638770779.1338856-29496-4861295296932/source",
    "state": "file",
    "uid": 0
}

[root@ansible-node1 ~]#ansible websrvs -m copy -a "src=ping.sh dest=/data/ping_org1.sh owner=zhao mode=700 backup=yes"
10.0.0.7 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": true,
    "checksum": "f3adc75ae43f5b248baa332e57319200d62c27f3",
    "dest": "/data/ping_org1.sh",
    "gid": 0,
    "group": "root",
    "md5sum": "17e5ef4191a7a60771ae5af291870cf6",
    "mode": "0700",
    "owner": "zhao",
    "size": 179,
    "src": "/root/.ansible/tmp/ansible-tmp-1638770956.0187192-29672-24908092009240/source",
    "state": "file",
    "uid": 1000
}
10.0.0.6 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": true,
    "checksum": "f3adc75ae43f5b248baa332e57319200d62c27f3",
    "dest": "/data/ping_org1.sh",
    "gid": 0,
    "group": "root",
    "md5sum": "17e5ef4191a7a60771ae5af291870cf6",
    "mode": "0700",
    "owner": "zhao",
    "size": 179,
    "src": "/root/.ansible/tmp/ansible-tmp-1638770956.018376-29670-82547040607481/source",
    "state": "file",
    "uid": 1000
}
[root@ansible-node1 ~]#ansible websrvs -a "ls -l /data/ping_org1.sh"
10.0.0.7 | CHANGED | rc=0 >>
-rwx------ 1 zhao root 179 Dec  6 14:09 /data/ping_org1.sh
10.0.0.6 | CHANGED | rc=0 >>
-rwx------ 1 zhao root 179 Dec  6 14:09 /data/ping_org1.sh

#注:shell模块不支持别名alias
[root@ansible-node1 ~]#ansible websrvs -a "ll /data/ping_org1.sh"
10.0.0.7 | FAILED | rc=127 >>
/bin/sh: ll: command not foundnon-zero return code
10.0.0.6 | FAILED | rc=127 >>
/bin/sh: ll: command not foundnon-zero return code

get_url 模块

Downloads files from HTTP, HTTPS, or FTP to the remote server

#下载nginx到localhost
[root@ansible-node1 ~]#wget http://nginx.org/download/nginx-1.18.0.tar.gz
--2021-12-06 14:13:28--  http://nginx.org/download/nginx-1.18.0.tar.gz
Resolving nginx.org (nginx.org)... 3.125.197.172, 52.58.199.22, 2a05:d014:edb:5702::6, ...
Connecting to nginx.org (nginx.org)|3.125.197.172|:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 1039530 (1015K) [application/octet-stream]
Saving to: ‘nginx-1.18.0.tar.gz’

nginx-1.18.0.tar.gz                100%[================================================================>]   1015K  24.7KB/s    in 65s

2021-12-06 14:14:34 (15.5 KB/s) - ‘nginx-1.18.0.tar.gz’ saved [1039530/1039530]
#查看md5校验码
[root@ansible-node1 ~]#openssl md5 nginx-1.18.0.tar.gz
MD5(nginx-1.18.0.tar.gz)= b2d33d24d89b8b1f87ff5d251aa27eb8


[root@ansible-node1 ~]#ansible websrvs -m get_url -a 'url=http://nginx.org/download/nginx-1.18.0.tar.gz dest=/usr/local/src/nginx.tar.gz checksum="md5:b2d33d24d89b8b1f87ff5d251aa27eb8"'
10.0.0.7 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": true,
    "checksum_dest": null,
    "checksum_src": "47b2c5ccd12e2a7088b03d629ff6b9ab18215180",
    "dest": "/usr/local/src/nginx.tar.gz",
    "elapsed": 64,
    "gid": 0,
    "group": "root",
    "md5sum": "b2d33d24d89b8b1f87ff5d251aa27eb8",
    "mode": "0644",
    "msg": "OK (1039530 bytes)",
    "owner": "root",
    "size": 1039530,
    "src": "/root/.ansible/tmp/ansible-tmp-1638771750.6639423-30015-13731296880907/tmp9vmfchhs",
    "state": "file",
    "status_code": 200,
    "uid": 0,
    "url": "http://nginx.org/download/nginx-1.18.0.tar.gz"
}
10.0.0.6 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": true,
    "checksum_dest": null,
    "checksum_src": "47b2c5ccd12e2a7088b03d629ff6b9ab18215180",
    "dest": "/usr/local/src/nginx.tar.gz",
    "elapsed": 76,
    "gid": 0,
    "group": "root",
    "md5sum": "b2d33d24d89b8b1f87ff5d251aa27eb8",
    "mode": "0644",
    "msg": "OK (1039530 bytes)",
    "owner": "root",
    "size": 1039530,
    "src": "/root/.ansible/tmp/ansible-tmp-1638771750.6638336-30013-253786557679879/tmp05zzeroa",
    "state": "file",
    "status_code": 200,
    "uid": 0,
    "url": "http://nginx.org/download/nginx-1.18.0.tar.gz"
}

fetch 模块

It is used for fetching files from remote machines and storing them locally in a file tree, organized by hostname
不支持fetch文件夹

[root@ansible-node1 ~]#ansible websrvs -m fetch -a 'src=/var/log/messages dest=/root/log'
10.0.0.7 | CHANGED => {
    "changed": true,
    "checksum": "7713c605c9ad4faf3871ed43f06c1374780674bd",
    "dest": "/root/log/10.0.0.7/var/log/messages",
    "md5sum": "79158aaf6d171242de50f31bd7bcef2b",
    "remote_checksum": "7713c605c9ad4faf3871ed43f06c1374780674bd",
    "remote_md5sum": null
}
10.0.0.6 | CHANGED => {
    "changed": true,
    "checksum": "6270f7d551b512ae34206b191211457dcc741baa",
    "dest": "/root/log/10.0.0.6/var/log/messages",
    "md5sum": "cf8e7715a5a48a87dba053f8fb3c77e5",
    "remote_checksum": "6270f7d551b512ae34206b191211457dcc741baa",
    "remote_md5sum": null
}
[root@ansible-node1 ~]#tree /root/log
/root/log
├── 10.0.0.6
│   └── var
│       └── log
│           └── messages
└── 10.0.0.7
    └── var
        └── log
            └── messages

6 directories, 2 files

file 模块

Set attributes of files, symlinks or directories. Alternatively, remove files, symlinks or directories

#创建一个空文件
[root@ansible-node1 ~]#ansible websrvs -m file -a 'path=/data/a.txt state=touch owner=zhao'
10.0.0.6 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": true,
    "dest": "/data/a.txt",
    "gid": 0,
    "group": "root",
    "mode": "0644",
    "owner": "zhao",
    "size": 0,
    "state": "file",
    "uid": 1000
}
#创建目录
[root@ansible-node1 ~]#ansible websrvs -m file -a 'path=/data/mysql state=directory owner=zhao group=mysql'
10.0.0.6 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": true,
    "gid": 27,
    "group": "mysql",
    "mode": "0755",
    "owner": "zhao",
    "path": "/data/mysql",
    "size": 6,
    "state": "directory",
    "uid": 1000
}

#创建软链接
[root@ansible-node1 ~]#ansible websrvs -m file -a 'src=/data/mysql path=/data/mysql-link state=link'
10.0.0.7 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": true,
    "dest": "/data/mysql-link",
    "gid": 0,
    "group": "root",
    "mode": "0777",
    "owner": "root",
    "size": 11,
    "src": "/data/mysql",
    "state": "link",
    "uid": 0
}
#删除文件夹及软链接
[root@ansible-node1 ~]#ansible websrvs -m file -a 'path=/data/mysql state=absent'
10.0.0.7 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": true,
    "path": "/data/mysql",
    "state": "absent"
}

[root@ansible-node1 ~]#ansible websrvs -m file -a 'path=/data/mysql-link state=absent'
10.0.0.7 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": true,
    "path": "/data/mysql-link",
    "state": "absent"
}

unarchive 模块

将本机压缩文件复制到remote host并解压

[root@ansible-node1 ~]#ansible websrvs -m unarchive -a 'src=nginx-1.18.0.tar.gz dest=/usr/local/src owner=zhao group=bin'
10.0.0.7 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": true,
    "dest": "/usr/local/src",
    "extract_results": {
        "cmd": [
            "/usr/bin/gtar",
            "--extract",
            "-C",
            "/usr/local/src",
            "-z",
            "--owner=zhao",
            "--group=bin",
            "-f",
            "/root/.ansible/tmp/ansible-tmp-1638775916.6312943-31346-145071583875583/source"
        ],
        "err": "",
        "out": "",
        "rc": 0
    },
    "gid": 0,
    "group": "root",
    "handler": "TgzArchive",
    "mode": "0755",
    "owner": "root",
    "size": 46,
    "src": "/root/.ansible/tmp/ansible-tmp-1638775916.6312943-31346-145071583875583/source",
    "state": "directory",
    "uid": 0
}

要拷贝的包不在本地主机上要加参数copy=no

[root@ansible-node1 ~]#ansible websrvs -m unarchive -a 'src=http://nginx.org/download/nginx-1.18.0.tar.gz dest=/data copy=no'
10.0.0.7 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": true,
    "dest": "/data",
    "extract_results": {
        "cmd": [
            "/usr/bin/gtar",
            "--extract",
            "-C",
            "/data",
            "-z",
            "-f",
            "/root/.ansible/tmp/ansible-tmp-1638776649.2850542-31535-241461059542798/nginx-1.18.0.tarofvg1__b.gz"
        ],
        "err": "",
        "out": "",
        "rc": 0
    },
    "gid": 0,
    "group": "root",
    "handler": "TgzArchive",
    "mode": "0777",
    "owner": "root",
    "size": 134,
    "src": "/root/.ansible/tmp/ansible-tmp-1638776649.2850542-31535-241461059542798/nginx-1.18.0.tarofvg1__b.gz",
    "state": "directory",
    "uid": 0
}

cron 模块

计划任务

[root@ansible-node1 ~]#ansible 10.0.0.7 -m cron -a 'hour=2 minute=30 weekday=1-5 name="backup mysql" job=/root/mysql_backup.sh'
10.0.0.7 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": true,
    "envs": [],
    "jobs": [
        "backup mysql"
    ]
}

验证是否创建计划任务

[root@centos8 ~]#crontab -e

#Ansible: backup mysql
30 2 * * 1-5 /root/mysql_backup.sh

yum&apt 模块

[root@ansible-node1 ~]#ansible 10.0.0.7 -m yum -a 'name=httpd'
10.0.0.7 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": true,
    "msg": "",
    "rc": 0,
    "results": [
        "Installed: centos-logos-httpd-85.8-2.el8.noarch",
        "Installed: apr-util-openssl-1.6.1-6.el8.x86_64",
        "Installed: httpd-tools-2.4.37-43.module_el8.5.0+1022+b541f3b1.x86_64",
        "Installed: mod_http2-1.15.7-3.module_el8.4.0+778+c970deab.x86_64",
        "Installed: mailcap-2.1.48-3.el8.noarch",
        "Installed: apr-1.6.3-12.el8.x86_64",
        "Installed: apr-util-1.6.1-6.el8.x86_64",
        "Installed: apr-util-bdb-1.6.1-6.el8.x86_64",
        "Installed: httpd-2.4.37-43.module_el8.5.0+1022+b541f3b1.x86_64",
        "Installed: httpd-filesystem-2.4.37-43.module_el8.5.0+1022+b541f3b1.noarch"
    ]
}
[root@ansible-node1 ~]#ansible 10.0.0.7 -m yum -a 'name=httpd state=absent'
10.0.0.7 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": true,
    "msg": "",
    "rc": 0,
    "results": [
        "Removed: mod_http2-1.15.7-3.module_el8.4.0+778+c970deab.x86_64",
        "Removed: httpd-2.4.37-43.module_el8.5.0+1022+b541f3b1.x86_64"
    ]
}

#同时安装多个包
[root@ansible-node1 ~]#ansible 10.0.0.7 -m yum -a 'name=httpd,vsftpd state=present'
10.0.0.7 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": true,
    "msg": "",
    "rc": 0,
    "results": [
        "Installed: vsftpd-3.0.3-34.el8.x86_64",
        "Installed: httpd-2.4.37-43.module_el8.5.0+1022+b541f3b1.x86_64",
        "Installed: mod_http2-1.15.7-3.module_el8.4.0+778+c970deab.x86_64"
    ]
}

lineinfile 模块

This module ensures a particular line is in a file, or replace an existing line using a back-referenced regular expression
这个模块确保文件中有特定的行,或者使用特定的正则表达式来进行替换
修改主机上的某个配置文件

[root@centos8 ~]#grep Listen /etc/httpd/conf/httpd.conf
# Listen: Allows you to bind Apache to specific IP addresses and/or
# Change this to Listen on specific IP addresses as shown below to
#Listen 12.34.56.78:80
Listen 80

[root@ansible-node1 ~]#ansible 10.0.0.7 -m lineinfile -a "path=/etc/httpd/conf/httpd.conf regexp='^Listen' line='Listen 8080'"
10.0.0.7 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "backup": "",
    "changed": true,
    "msg": "line replaced"
}

验证

[root@centos8 ~]#grep Listen /etc/httpd/conf/httpd.conf
# Listen: Allows you to bind Apache to specific IP addresses and/or
# Change this to Listen on specific IP addresses as shown below to
#Listen 12.34.56.78:80
Listen 8080

删掉目的主机上配置文件中的注释行

[root@centos8 ~]#grep Listen /etc/httpd/conf/httpd.conf
# Listen: Allows you to bind Apache to specific IP addresses and/or
# Change this to Listen on specific IP addresses as shown below to
#Listen 12.34.56.78:80
Listen 8080

[root@ansible-node1 ~]#ansible 10.0.0.7 -m lineinfile -a 'dest=/etc/fstab state=absent regexp="^#"'
10.0.0.7 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "backup": "",
    "changed": true,
    "found": 10,
    "msg": "10 line(s) removed"
}

验证

[root@centos8 ~]#cat /etc/fstab

UUID=19608b8a-d5e1-4c0c-9a90-e8a5c5220c11 /                       xfs     defaults        0 0
UUID=a86f310b-93b1-4af4-b90e-8880983a085f /boot                   ext4    defaults        1 2
UUID=64bcd8dd-c7d2-4182-8bee-78c3027d8544 /data                   xfs     defaults        0 0
UUID=ac96e38b-997b-49a7-af32-6e7311e267a9 none                    swap    defaults        0 0

当文件中有多行相同内容的时候,只会更改最后匹配到的那个

[root@centos8 ~]#grep Listen /etc/httpd/conf/httpd.conf
#Listen 12.34.56.78:80
Listen 8080
Listen 8080
Listen 8080

#替换
[root@ansible-node1 ~]#ansible 10.0.0.7 -m lineinfile -a "path=/etc/httpd/conf/httpd.conf regexp='^Listen' line='Listen 99'"
10.0.0.7 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "backup": "",
    "changed": true,
    "msg": "line replaced"
}

验证

[root@centos8 ~]#grep Listen /etc/httpd/conf/httpd.conf
# Listen: Allows you to bind Apache to specific IP addresses and/or
# Change this to Listen on specific IP addresses as shown below to
#Listen 12.34.56.78:80
Listen 8080
Listen 8080
Listen 99

replace 模块

在lineinfile的基础上精确替换所有符合表达式匹配到的内容 推荐使用

示例:将上面的8080和99全部替换为80

[root@ansible-node1 ~]#ansible 10.0.0.7 -m replace -a "path=/etc/httpd/conf/httpd.conf regexp='^Listen.*' replace='Listen 80'"
10.0.0.7 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": true,
    "msg": "3 replacements made"
}

验证

[root@centos8 ~]#grep Listen /etc/httpd/conf/httpd.conf
# Listen: Allows you to bind Apache to specific IP addresses and/or
# Change this to Listen on specific IP addresses as shown below to
#Listen 12.34.56.78:80
Listen 80
Listen 80
Listen 80

SElinux 模块

启用关闭selinux,但是只是临时的从enforcing变为permissive模式,如果要生效要重启

[root@centos8 ~]#getenforce
Enforcing

[root@ansible-node1 ~]#ansible 10.0.0.7 -m selinux -a 'state=disabled'
#警告说更改selinux模式之后下次重启才会生效
[WARNING]: SELinux state temporarily changed from 'enforcing' to 'permissive'. State change will take effect next reboot.
10.0.0.7 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": true,
    "configfile": "/etc/selinux/config",
    "msg": "Running SELinux policy changed from 'targeted' to 'None', Config SELinux state changed from 'enforcing' to 'disabled'",
    "policy": null,
    "reboot_required": true,
    "state": "disabled"
}

验证

[root@centos8 ~]#getenforce
Permissive

reboot 模块

重启

[root@ansible-node1 ~]#ansible 10.0.0.7 -m reboot
10.0.0.7 | CHANGED => {
    "changed": true,
    "elapsed": 62,
    "rebooted": true
}

验证

[root@centos8 ~]#
Connection closed by foreign host.

Disconnected from remote host(Mage-CentOS8.3-03) at 12:24:21.

Type `help' to learn how to use Xshell prompt.

setup

查看远程主机的系统变量 比较详细的系统信息,诸如:主机硬件信息,网络信息,系统时间

查看remote host所有的信息

[root@ansible-node1 ~]#ansible all -m setup

过滤主机名

[root@ansible-node1 ~]#ansible all -m setup -a "filter=ansible_nodename"
10.0.0.182 | SUCCESS => {
    "ansible_facts": {
        "ansible_nodename": "localhost.localdomain",
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": false
}
10.0.0.5 | SUCCESS => {
    "ansible_facts": {
        "ansible_nodename": "ansible-node1",
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": false
}

查看主机的操作系统属于哪个家族

[root@ansible-node1 ~]#ansible websrvs -m setup -a "filter=ansible_os_family"
[DEPRECATION WARNING]: Distribution Ubuntu 18.04 on host 10.0.0.16 should use /usr/bin/python3, but is using /usr/bin/python for backward
compatibility with prior Ansible releases. A future Ansible release will default to using the discovered platform python for this host. See
 https://docs.ansible.com/ansible/2.9/reference_appendices/interpreter_discovery.html for more information. This feature will be removed in
 version 2.12. Deprecation warnings can be disabled by setting deprecation_warnings=False in ansible.cfg.
10.0.0.16 | SUCCESS => {
    "ansible_facts": {
        "ansible_os_family": "Debian",
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": false
}
10.0.0.6 | SUCCESS => {
    "ansible_facts": {
        "ansible_os_family": "RedHat",
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": false
}
10.0.0.7 | SUCCESS => {
    "ansible_facts": {
        "ansible_os_family": "RedHat",
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": false
}

查看主机的内存

[root@ansible-node1 ~]#ansible 10.0.0.7 -m setup -a "filter=ansible_memtotal_mb"
10.0.0.7 | SUCCESS => {
    "ansible_facts": {
        "ansible_memtotal_mb": 1950,
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": false
}

一些示例

卸载httpd

ansible websrvs:dbsrvs -m yum -a 'name=httpd state=absent'

Playbook

剧本

---
#This is a playbook file
- hosts: websrvs
  remote_user: root
  tasks: 
    - name: ping
      ping: 
    - name: wall
      shell: wall hello

语法检测,无报错即为正常

[root@ansible-node1 ansible_yaml]#ansible-playbook --syntax-check /data/ansible_yaml/test.yml

playbook: /data/ansible_yaml/test.yml

使用剧本创建一个用户和组

---
#创建mysql账户
- hosts: dbsrvs
  remote_user: root
  gather_facts: no

  tasks:
    - {name: create group, group: name=mysqldtest system=yes gid=306}
    - name: create user
      user: name=mysqltest shell=/sbin/nologin system=yes group=mysqldtest uid=306 home=/data/mysqltest create_home=no

执行

# --limit参数指定组中的某一个主机
[root@ansible-node1 ansible_yaml]#ansible-playbook play3.yml --limit 10.0.0.6

安装/删除nginx服务并配置文件

安装

拷贝本地nginx配置文件到playboo文件的存放路径中

[root@ansible-node1 ansible]#mkdir files
[root@ansible-node1 ansible]#ls
files  play1.yml  play2.yml  play3.yml  test.yml

[root@ansible-node1 ansible]#cp /etc/nginx/nginx.conf /data/ansible/files/
#编写一个nginx主页
[root@ansible-node1 ansible]#cat /data/ansible/files/index.html
<h1> nginx website </h1>

编写playbook文件

---
#install nginx
- hosts: websrvs
  remote_user: root
  gather_facts: no

  tasks:
    - name: add group nginx
      group: name=nginx state=present
    - name: add user nginx
      user: name=nginx state=present group=nginx
    - name: Install Nginx
      yum: name=nginx state=present
    - name: Config file
      copy: src=files/nginx.conf dest=/etc/nginx/nginx.conf
    - name: web page
      copy: src=files/index.html dest=/usr/share/nginx/html/index.html
    - name: Start Nginx
      service: name=nginx state=started enabled=yes

语法检测并假装运行 参数 -C

[root@ansible-node1 ansible]#ansible-playbook -C play4.yml

执行

[root@ansible-node1 ansible]#ansible-playbook play4.yml --limit 10.0.0.7
 ________________
< PLAY [websrvs] >
 ----------------
        \   ^__^
         \  (oo)\_______
            (__)\       )\/\
                ||----w |
                ||     ||

 ____________
< PLAY RECAP >
 ------------
        \   ^__^
         \  (oo)\_______
            (__)\       )\/\
                ||----w |
                ||     ||

10.0.0.7                   : ok=6    changed=6    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

验证

[root@ansible-node1 ansible]#curl 10.0.0.7:8080
<h1> nginx website </h1>
删除
---
#remove nginx
- hosts: websrvs
  remote_user: root
  gather_facts: no

  tasks:
    - name: stop Nginx
      service: name=nginx state=stopped enabled=no
    - name: remove Nginx
      yum: name=nginx state=absent
    - name: del user nginx
      user: name=nginx state=absent
    - name: del group nginx
      group: name=nginx state=absent
    - name: Config file
      file: path=/etc/nginx/nginx.conf state=absent
    - name: web page
      file: path=/usr/share/nginx/html/index.html state=absent

检测语法并假装执行

[root@ansible-node1 ansible]#ansible-playbook -C remove_nginx.yml --limit 10.0.0.7
10.0.0.7                   : ok=6    changed=6    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

执行

[root@ansible-node1 ansible]#ansible-playbook remove_nginx.yml --limit 10.0.0.7
 ________________
< PLAY [websrvs] >
 ----------------
        \   ^__^
         \  (oo)\_______
            (__)\       )\/\
                ||----w |
                ||     ||
10.0.0.7                   : ok=6    changed=3    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

验证

[root@ansible-node1 ansible]#curl 10.0.0.7:8080
curl: (7) Failed to connect to 10.0.0.7 port 8080: Connection refused

ansible配置文件优先级

配置文件优先级顺序
自定义目录下优先级最高
家目录下的配置文件优先级其次
/etc/ansible/下优先级最低

[root@ansible-node1 ansible]#ansible --version
ansible 2.9.27
  config file = /etc/ansible/ansible.cfg
  configured module search path = ['/root/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/lib/python3.6/site-packages/ansible
  executable location = /usr/bin/ansible
  python version = 3.6.8 (default, Mar 19 2021, 05:13:41) [GCC 8.4.1 20200928 (Red Hat 8.4.1-1)]

[root@ansible-node1 ansible]#cp /etc/ansible/ansible.cfg /root/.ansible.cfg

[root@ansible-node1 ansible]#ansible --version
ansible 2.9.27
  config file = /root/.ansible.cfg
  configured module search path = ['/root/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/lib/python3.6/site-packages/ansible
  executable location = /usr/bin/ansible
  python version = 3.6.8 (default, Mar 19 2021, 05:13:41) [GCC 8.4.1 20200928 (Red Hat 8.4.1-1)]
  
[root@ansible-node1 ansible]#cp /etc/ansible/ansible.cfg /data/ansible/

[root@ansible-node1 ansible]#ansible --version
ansible 2.9.27
  config file = /data/ansible/ansible.cfg
  configured module search path = ['/root/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/lib/python3.6/site-packages/ansible
  executable location = /usr/bin/ansible
  python version = 3.6.8 (default, Mar 19 2021, 05:13:41) [GCC 8.4.1 20200928 (Red Hat 8.4.1-1)]

ansible配置文件中的主机清单也可以设置为项目的相对路径,因为项目相对路径下的ansible.cfg的优先级高于/etc/ansible下的文件优先级,这样就简单实现了每个小项目下的主机清单列表和ansible配置文件自定义。

#ansible主配置文件修改主机列表为相对路径
[root@ansible-node1 ~]#vim /data/ansible/ansible.cfg
[defaults]
# some basic default values...
inventory      = ./hosts

更新本地配置文件的nginx默认监听端口为80之后重新执行install_nginx.yml

[root@ansible-node1 ansible]#ansible-playbook install_nginx.yml --limit 10.0.0.7
 ____________________
< TASK [Config file] >
 --------------------
        \   ^__^
         \  (oo)\_______
            (__)\       )\/\
                ||----w |
                ||     ||

ok: [10.0.0.6]
changed: [10.0.0.7]
10.0.0.7                   : ok=6    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

验证

[root@ansible-node1 ansible]#curl 10.0.0.7
curl: (7) Failed to connect to 10.0.0.7 port 80: Connection refused
[root@ansible-node1 ansible]#curl 10.0.0.7:8080
<h1> nginx website </h1>

虽然更改了配置文件,也用ansible重新执行了,但是ansible只copy了配置文件过去更新了,并未重启

ansible的handlers和notify

配置类似于数据库中的trigger作用 handlers 和notify

handlers负责定义操作
notify负责触发通知

---
# install&update nginx v2
#add the config file update trigger
- hosts: websrvs
  remote_user: root
  gather_facts: no

  tasks:
    - name: add group nginx
      group: name=nginx state=present
    - name: add user nginx
      user: name=nginx state=present group=nginx
    - name: install nginx
      yum: name=nginx state=present
    - name: config file
      copy: src=files/nginx.conf dest=/etc/nginx/nginx.conf
      notify: restart nginx service
    - name: web page
      copy: src=files/index.html dest=/usr/share/nginx/html/index.html
    - name: start nginx
      service: name=nginx state=started enabled=yes

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

修改本地的nginx.conf端口地址为80

[root@ansible-node1 ansible]#vim files/nginx.conf
    server {
        listen       8080 default_server;

执行playbook install_nginx_v2.yml

[root@ansible-node1 ansible]#ansible-playbook install_nginx_v2.yml --limit 10.0.0.7
< TASK [config file] >
 --------------------
        \   ^__^
         \  (oo)\_______
            (__)\       )\/\
                ||----w |
                ||     ||

changed: [10.0.0.7]
< RUNNING HANDLER [restart nginx service] >
 -----------------------------------------
        \   ^__^
         \  (oo)\_______
            (__)\       )\/\
                ||----w |
                ||     ||

changed: [10.0.0.7]
10.0.0.7                   : ok=7    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

验证80端口

[root@ansible-node1 ansible]#curl 10.0.0.7
<h1> nginx website </h1>

tags

给playbook中的任务打一个标签,执行时候可以以标签来执行某个任务

---
# tags example install nginx v3
- hosts: websrvs
  remote_user: root
  gather_facts: no
  force_handlers: yes

  tasks:
    - name: add group nginx
      group: name=nginx state=present
    - name: add user nginx
      user: name=nginx state=present group=nginx
    - name: install nginx
      yum: name=nginx state=present
    - name: config
      copy: src=files/nginx.conf dest=/etc/nginx/nginx.conf
      notify: restart nginx service
      tags: conf
    - name: web page
      copy: src=files/index.html dest=/usr/share/nginx/html/index.html
      tags: html
    - name: start nginx
      service: name=nginx state=started enabled=yes

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

[root@ansible-node1 ansible]#ansible-playbook -t conf nginx_tags.yml --limit 10.0.0.7
 ________________
< PLAY [websrvs] >
 ----------------
 _______________
< TASK [config] >
 ---------------

changed: [10.0.0.7]
 _________________________________________
< RUNNING HANDLER [restart nginx service] >
 -----------------------------------------

changed: [10.0.0.7]
 ____________
< PLAY RECAP >
 ------------

10.0.0.7                   : ok=2    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

playbook 变量

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值