0%

ansible 简单使用

最近遇到一点问题需要在不配置证书的,的多台服务器上部署程序,然后我想起了很久之前了解过的 ansible,感觉这个可以胜任,所以就查了一下资料下面是我的使用过程

安装 ansible

1
pip3 install ansible

生成配置文件

1
ansible-config init --disabled > ansible.cfg

关于配置文件的说明请参考
https://raw.githubusercontent.com/ansible/ansible/devel/examples/ansible.cfg
https://docs.ansible.com/ansible/latest/reference_appendices/config.html

将配置文件移动到 etc,因为 hosts 好像要放在 etc

1
2
3
sudo mkdir /etc/ansible/ 
sudo mv ansible.cfg /etc/ansible/
sudo chown root:root /etc/ansible/ansible.cfg

创建 /etc/ansible/hosts 并写入以下内容,这里我使用的是密码方式进行连接
ansible_user 是用户名
ansible_password 是密码

1
2
3
4
5
6
7
8
9
10
11
[web]
192.168.31.100

[node]
192.168.31.101
192.168.31.102

[all:vars]
ansible_connection=ssh
ansible_user=root
ansible_password=123456

到这里 ansible 就配置好了

如果链接的目标机器的握手证书没有存在于 ~/.ssh/known_hosts 那么可以通过以下命令忽略证书验证

1
export ANSIBLE_HOST_KEY_CHECKING=False

运行命令

1
ansible all -a "date"

上传文件

src 本地文件路径
dest 远程 服务器文件路径
owner 文件所属用户(可选)
group 文件所属组(可选)
mode 文件权限(可选)

1
ansible all -m copy -a "src=/home/hello/cache/aa.txt dest=/root/ owner=root group=root mode=0644"