本文将从无到有注明ansible的基础使用, 以三个例子进行教学
首先更新ansible主目录下的hosts文件用作测试
由于在生产中, 出于安全性考虑, 不使用ssh互信进行ansible通信, 可以在配置文件中通过键值对的方式定义变量, 注明用户名与密码
[all:vars]
ansible_python_interpreter='/usr/bin/python3'
[test:vars]
ansible_ssh_user='username'
ansible_ssh_pass='password'
[test]
10.122.1.77
10.122.1.78
命令格式: ansible group_name/ip -m moudle_name [-a moudel_args]
[root@localhost ansible]# ansible test -m ping
10.122.1.77 | SUCCESS => {
"changed": false,
"ping": "pong"
}
10.122.1.78 | SUCCESS => {
"changed": false,
"ping": "pong"
}
以确认时区为例子
[root@localhost ansible]# ansible test -m shell -a 'timedatectl| grep Time'
10.122.1.78 | CHANGED | rc=0 >>
Time zone: Etc/UTC (UTC, +0000)
10.122.1.77 | CHANGED | rc=0 >>
Time zone: Asia/Shanghai (CST, +0800)
此步可以有两种方式进行完成, 以下将一一实现
[root@localhost ansible]# ansible test -m shell -a 'apt update'
10.122.1.78 | FAILED | rc=100 >>
Reading package lists...
WARNING: apt does not have a stable CLI interface. Use with caution in scripts.
E: Could not open lock file /var/lib/apt/lists/lock - open (13: Permission denied)
E: Unable to lock directory /var/lib/apt/lists/
W: Problem unlinking the file /var/cache/apt/pkgcache.bin - RemoveCaches (13: Permission denied)
W: Problem unlinking the file /var/cache/apt/srcpkgcache.bin - RemoveCaches (13: Permission denied)non-zero return code
vim /etc/ansible/ansible.cfg
become=True
become_method=sudo
become_user=root
become_ask_pass=False
# 默认注释, 解除注释即可, 意义很明显, 就不赘述了
[root@localhost ansible]# ansible test -m shell -a 'apt update'
10.122.1.77 | CHANGED | rc=0 >>
Hit:1 http://cn.archive.ubuntu.com/ubuntu bionic InRelease
Hit:2 http://cn.archive.ubuntu.com/ubuntu bionic-updates InRelease
Hit:3 http://cn.archive.ubuntu.com/ubuntu bionic-backports InRelease
Hit:4 http://cn.archive.ubuntu.com/ubuntu bionic-security InRelease
Reading package lists...
Building dependency tree...
Reading state information...
12 packages can be upgraded. Run 'apt list --upgradable' to see them.
WARNING: apt does not have a stable CLI interface. Use with caution in scripts.
[root@localhost test]# vim apt_update.yml
---
- hosts: test
tasks:
- name: update apt source
apt:
update_cache: yes
cache_valid_time: 86400
inventory = /home/test/hosts
此时/home/test/hosts下的任何inventory文件都可以被ansible识别并使用
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。