ansible 简易教程

安装命令

pip3 install ansible

# 用密码登陆远程主机需要额外装sshpass
sudo apt install sshpass

配置

ansible --version

config_file = None

这时要在 /etc/ansible/ 目录下手动创建 ansible.cfg 和 hosts 文件。

在ansible.cfg中配置,跳过初次ssh时的客户端可信校验。

[defaults]
host_key_checking = False

添加hosts

hosts文件示例如下:

[group_name]
123.123.123.123:22 ansible_ssh_user=root ansible_ssh_pass='password'
123.123.123.124:22 ansible_ssh_user=root ansible_ssh_pass='password'

分别是IP,端口,账号和密码,一个[group]可以有多台服务器。

测试

ansible groupname -m ping

-m表示调用的模块名称。

实例

fetch: 从远程copy文件到本地,注意目前支持文件,不支持文件夹递归copy

拷贝单个文件:

ansible hosts -m fetch -a "src=/remote/dir/file dest=/local/dir" #-a表示模块的参数

copy:从本地到远程

shell:运行shell

find: 查找文件

unarchive: 解压

archive:压缩

ansible-playbook

ansible playbook 在 ansible命令行的基础上提供了跟家强大的流程编写功能。

写一个yaml文件 p.yml:

---  #固定格式, 这个脚本演示了把一个远程文件夹里的多个文件拷贝到本地的/tmp/目录

- name: Fetch_dir_from_remote
  hosts: IP or Groupname

  tasks:
    - name: find
      find:
        paths: /var/www/html
        patterns: "*"
        recurse: yes
      register: file_2_fetch  #注册变量

    - name: fetch_find
      fetch:
        src: "{{ item.path }}"
        dest: /tmp/
        flat: yes
      with_items: "{{ file_2_fetch.files }}"  #遍历find的结果

执行yml

ansible-playbook p.yml

posted @   爱知菜  阅读(103)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 上周热点回顾(3.3-3.9)
· AI 智能体引爆开源社区「GitHub 热点速览」
点击右上角即可分享
微信分享提示