安装 yum -y install ansible 或者 pip install ansible
需要把托管机的ip加入到hosts文件里
/etc/ansible/hosts
这里我只做个单机测试,使用用户名密码登录,我使用root用户, 尝试让ansible使用vagrant用户
使用用户名密码的话还需要安装 yum install sshpass
[web] 172.28.128.4 ansible_ssh_user=vagrant ansible_ssh_pass=vagrant |
运行
[root@vagrant ansible]# ansible web -a “hostname” 172.28.128.4 | success | rc=0 >> vagrant |
秘钥登录的话直接去掉ansible_ssh_pass参数就可以了,当然你需要先提供免密码登录
可以参考http://lizhe.name.csdn.net/node/24里的免密码登录
如果是机器A登录到机器B, 在A上生成秘钥对 ssh-keygen -t rsa -P ”
将机器A上的 公钥 复制到机器B , 内容直接cat给 .ssh/authorzied_keys
记得确认/etc/ssh/sshd_config 中的key文件位置和文件名
/root/.ssh/id_rsa
/root/.ssh/id_rsa.pub
ansible默认使用5个线程执行, 如果需要指定线程数需要使用 -f 参数
[root@vagrant ansible]# ansible web -a “hostname” -f 1 172.28.128.4 | success | rc=0 >> vagrant |
上面的例子实际上使用了 command 模块,这个模块是默认提供的,它接收 -a 参数提供的命令,所以下面两行命令实际上是等价的
ansible web -a “hostname”
ansible web -m command -a “hostname”
这里我决定还是请出我们的老朋友, docker和它的容器们
docker run -t -i –name ansible_vm_1 docker.io/centos /bin/bash
docker run -t -i –name ansible_vm_2 docker.io/centos /bin/bash
docker run -t -i –name ansible_vm_3 docker.io/centos /bin/bash
创建了3个容器

虽然docker不鼓励使用ssh登录进容器,也不鼓励修改容器用户的密码, 但是这里实在不想做一遍免密登录了,所以打算直接用用户名密码登录容器, 因为ansible是基于ssh的,所以还是要去给容器安装一下sshd服务
yum -y install openssh-server openssh-clients
/etc/ssh/sshd_config 文件中打开root用户远程登录 PermitRootLogin yes
修改完之后手动启动sshd服务 /usr/sbin/sshd
如果出现找不到key的错误
[root@7c6125cedfd3 /]# /usr/sbin/sshd
Could not load host key: /etc/ssh/ssh_host_rsa_key
Could not load host key: /etc/ssh/ssh_host_dsa_key
Could not load host key: /etc/ssh/ssh_host_ecdsa_key
Could not load host key: /etc/ssh/ssh_host_ed25519_key
把其他的key注释掉,保留一个rsa_key 然后使用ssh-keygen -t rsa -b 2048 -f /etc/ssh/ssh_host_rsa_key 重新生成一个就行了
passwd root改个密码
把三个容器都配置完成以后在宿主机上尝试添加这3个容器
查看一下容器ip
docker inspect -f ‘{{.NetworkSettings.IPAddress}}’ ansible_vm_1

把ip加进ansible的配置文件里 /etc/ansible/hosts
[dockers] 172.17.0.2 ansible_ssh_user=root ansible_ssh_pass=root 172.17.0.3 ansible_ssh_user=root ansible_ssh_pass=root 172.17.0.4 ansible_ssh_user=root ansible_ssh_pass=root |

要屏蔽第一次连接出现yes/no的情况
/etc/ansible/ansible.cfg
# uncomment this to disable SSH key host checking
host_key_checking = False