Ansible知识点整理——Ad-Hoc,ansiblead-hoc


Ansible Ad-Hoc

    • 简介
    • Ad-Hoc包含以下模块
    • 附上使用ad-hoc配置多台主机间免登陆的步骤

简介

Ad-Hoc 是指使用ansible临时执行命令,要结合着模块使用。
通用格式为:

ansible <pattern_goes_here> -m <module_name> -a <arguments>

-m 模块名,默认不指定,使用的是command模块。
-a 模块参数,可通过 ansible-doc 模块名 查看具体使用方法
如果需要查看模块列表,可以使用ansible-doc -l。模块列表很长,建议配合使用grep查找需要的命令,如ansible-doc -l | grep copy

示例如下:

ansible webservers -m service -a "name=httpd state=restarted"
ansible ftpservers -m featch -a "src=/data/*.csv dest=/data/featch/"

Ad-Hoc包含以下模块

  • 命令行相关
    不传模块名称时默认使用命令行。如ansible webservice -a 'ls /data'
  • 文件相关
    一般涉及文件的有:1. 修改文件属性 2. 上传文件 3. 下载文件
    举例:
    # 设置文件权限
    ansible webservice -m file -a "path=/tmp/keygen.sh owner=teset group=test mode=0755"
    # 上传文件
    ansible webservice -m copy -a "src=/Users/cheer/Desktop/test/keygen.sh dest=/tmp/keygen.sh mode=0755"
    # 下载文件
    ansible goinsight-passwd -m fetch -a 'src=~/.ssh/id_rsa.pub dest=/Users/cheer/Desktop/test/id_rsa'
    
  • 软件包相关
    一般用来检查某软件是否安装或更新软件
    # 检查是否存在
    ansible webserver -m yum -a "name=vim state=present"
    # 检查最新
    ansible webserver -m yum -a "name=vim state=latest"
    # 确保软件没有安装
    ansible webserver -m yum -a "name=vim state=absent"
    
  • 用户和组管理
  • 服务管理
    启动、关闭、重启服务
    # state可以是started、restarted、stopped
    ansible webserver -m service -a "name=httpd state=started"
    
  • 执行自定义脚本
    ansible webserver -m script -a "/tmp/keygen.sh"
    

附上使用ad-hoc配置多台主机间免登陆的步骤

  1. 先把需要配置免登陆的机器配置好主机名,不然生成的id_rsa.pub最后面都是localhost.localdomain
  2. 安装
sudo easy_install pip
sudo pip install ansible
  1. 配置ssh
# 先安装sshpass。这里我设置了代理和下载路径,如果没有代理请去掉-e参数
wget -e "http_proxy=http://127.0.0.1:1087" -P /Users/cheer/Downloads/ http://sourceforge.net/projects/sshpass/files/sshpass/1.05/sshpass-1.05.tar.gz
tar -zxf sshpass-1.05.tar.gz
cd sshpass-1.05
./configure
make
sudo make install
  1. 批量ssh-keygen
    sudo vim /etc/ansible/hosts
[goinsight-passwd]
172.16.21.30
172.16.11.124

[goinsight-passwd:vars]
ansible_ssh_user=root
ansible_ssh_pass=123456

[goinsight]
172.16.21.30
172.16.11.124
ansible goinsight-passwd -m copy -a "src=/Users/cheer/Desktop/test/keygen.sh dest=/tmp/keygen.sh mode=0755"
ansible goinsight-passwd -m shell -a "/tmp/keygen.sh"
  1. 配置主机间免登陆
ansible goinsight-passwd -m fetch -a 'src=~/.ssh/id_rsa.pub dest=/Users/cheer/Desktop/test/id_rsa'
# 合并id_rsa.pub
cd /Users/cheer/Desktop/test/id_rsa
find . -type f -exec cat {} \; > ../authorized_keys
# 把本机也添加到authorized_keys中
cat ~/.ssh/id_rsa.pub >> ../authorized_keys
ansible goinsight-passwd -m copy -a 'src=/Users/cheer/Desktop/test/authorized_keys dest='~/.ssh/'

相关内容

    暂无相关文章