【星海出品】ansible入门(一)

1.安装ansible

1.1安装

sudo apt-get install -y ansible

1.2.配置时需要生成秘钥

ssh-keygen
#推荐秘钥

1.3.推送秘钥

ssh-copy-id 10.0.0.7
ssh-copy-id 10.0.0.8

1.4配置hosts

vim /etc/ansible/hosts
[web_group]
web01
web02

1.5配置hosts(和ansible没太大关系,只是为了自己方便。)

vim /etc/hosts
10.0.0.7 web01
10.0.0.8 web02

1.6测试

ansible 'web_group' -m ping

2.配置文件

文件路径为:/etc/ansible
配置文件 /etc/ansible/ansible.cfg

有相关的主机列表配置文件位置,库文件位置,默认并发数,远程登录用户,远程端口,日志位置等。

全局设置:修改 ansible.cfg

interpreter_python = /usr/bin/python3  
<<<[defaults] 部分添加选项,指定 Python 解释器

针对设备(组)单独设置:修改 hosts 文件

ansible_python_interpreter=/usr/bin/python3  
<<<[xxx:vars] 部分添加属性,指定 Python 解释器
ansible ASA -m ping -o -e 'ansible_python_interpreter=/usr/bin/python3'
#手工指定

可以创建一个inventory文件,用于定义管理的服务器列表的文件。
这个文件可以命名为任何名字(不要与关键名字冲突)。
通常命名为hosts或者项目的名称。
/etc/ansible/hosts
例如:

[web]
192.168.22.10
192.168.22.11

如果需要还可以定义多个组。
通过命令可以查看组内成员
ansible web --list-host

2.2运行命令

ansible -i ./hosts web -v -m ping -u root --private-key=~/.ssh/id_rsa

说明

-i 设置库存文件
-m 使用的模块
-c local | --connection=local - 在本地服务器上运行命令,而不是ssh
-a 具体模块的参数,模块的具体动作
–syntax-check #验证语法是否正确,是否有明显错误处。

常用命令

ansible all -m ping -u root

3.常用模块

command
command模块命令将不会使用shell执行,因此想$HOME这样的变量是不可用的。还有向 <, >, | , ; , & 都将不可用

ansible all -m command -a "ls"

shell模块
shell 模块通过shell程序执行, 默认是/bin/sh, <, >, |, ;, & 可用。但这样有潜在的 shell 注入风险

ansible all -m shell -a "chdir=/root ls"

copy模块

ansible web -m copy -a 'src=/root/a.sh dest=/tmp/'
#也可以实现备份
ansible web -m copy -a 'src=/root/file.txt  owner=root  group=root  dest=/tmp/file.txt  backup=yes'

find模块

ansible all -m find -a 'path=/root,/home patterns="*.json"'

group模块

创建用户组
ansible all -m group -a 'name=testgroup gid=6666 state=present'

user模块
使用ansible命令调用 user 模块,为受控主机创建一个名为testuser的用户

ansible all -m user -a 'name=testuser group=1001 groups=48'
#指定其所属附加组gid为48,可以看到命令执行成功且对远程受控主机做出改变。

服务管理模块

ansible-doc service
ansible all -m service -a 'name=nginx state=started'

4.附录

python3不支持的ansible组件 package
支持dnf模块
使用ansible命令调用 dnf 模块,为所有受控主机安装httpd和php软件包

ansible all -m dnf -a 'name="httpd,php" state=present'
# absent 

卸载的话state = absent autoremove = yes

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值