基于docker使用ansible测试示例

一、新建4个虚拟主机

3个节点当作服务器

docker run -d --name node2 -p 2223:22 chenqionghe/ubuntu
docker run -d --name node3 -p 2224:22 chenqionghe/ubuntu
docker run -d --name node4 -p 2225:22 chenqionghe/ubuntu

一个节点安装ansible

docker run -d --name node1 -p 2222:22 \
--link node2:node2 \
--link node3:node3 \
--link node4:node4 \
chenqionghe/ubuntu

  

二、ssh连接node1进行准备操作

密码lightWeightBaby!

ssh [email protected] -p 2222

安装ssh-copy-id

curl -L https://raw.githubusercontent.com/beautifulcode/ssh-copy-id-for-OSX/master/install.sh | sh
chmod 755 /usr/local/bin/ssh-copy-id

生成ssh公钥

ssh-keygen

安装ssh客户端

yum update && yum -y install openssh-clients

设置3个节点免密码登录

ssh-copy-id -i ~/.ssh/id_rsa.pub root@node2
ssh-copy-id -i ~/.ssh/id_rsa.pub root@node3
ssh-copy-id -i ~/.ssh/id_rsa.pub root@node4

安装ansible

yum install ansible

配置ansible的hosts,编辑/etc/ansible/hosts,加入

[web]
node2
node3
node4

三、使用ansible

列出所有命令

ansible-doc -l

列出指定命令使用方法,如ansible-doc -s command

ansible-doc -s 命令名

 使用command模块

[root@6fe45a21f868 tmp]# ansible web -m command -a 'date'
node3 | SUCCESS | rc=0 >>
Mon Jan 14 08:38:57 UTC 2019

node2 | SUCCESS | rc=0 >>
Mon Jan 14 08:38:57 UTC 2019

node4 | SUCCESS | rc=0 >>
Mon Jan 14 08:38:57 UTC 2019

使用ping模块

[root@6fe45a21f868 tmp]# ansible all -m ping

node2 | SUCCESS => {
    "changed": false,
    "ping": "pong"
}
node4 | SUCCESS => {
    "changed": false,
    "ping": "pong"
}
node3 | SUCCESS => {
    "changed": false,
    "ping": "pong"
}

使用user模块,添加用户cqh

ansible web -m user -a "name=cqh"

 使用shell模块,给cqh设定密码

ansible web -m shell -a 'echo superman|passwd --stdin cqh'

使用script模块(相对路径)

cd /tmp
echo "echo \"hello cqh\" > /tmp/test.txt"  > test.sh
ansible web -m script -a "test.sh"
#查看是否生效
ansible web -a "cat /tmp/test.txt"

  

猜你喜欢

转载自www.cnblogs.com/chenqionghe/p/10267636.html