ansible常用命令

本文介绍ansible常用命令,基于ad-hoc模式。
Ansible官网:https://www.ansible.com/

1. 常规使用

不建议使用playbook。

1
2
3
4
5
6
7
8
9
#执行shell,my_all是一个服务器组,可以配置在/etc/ansible/hosts文件里
ansible my_all -m shell -a "curl -s icanhazip.com"
# 修改配置:
vim /etc/ansible/hosts
# 配置模板如下
[my_all]
192.168.1.1 ansible_user=tom ansible_port=22 ansible_ssh_extra_args='-i /root/.ssh/key1 -o StrictHostKeyChecking=no'
192.168.1.2 ansible_user=jerry ansible_port=22 ansible_ssh_extra_args='-i /root/.ssh/key2 -o StrictHostKeyChecking=no'
192.168.1.3 ansible_user=root ansible_port=22 ansible_ssh_extra_args='-i /root/.ssh/key3 -o StrictHostKeyChecking=no'

hosts配置文件里,除了ip,其他可以使用默认值。参数说明:

  1. ansible_user ssh的登录用户
  2. ansible_port ssh的端口,有些服务器不使用22端口,可以通过这个参数指定
  3. ansible_ssh_extra_args 是ssh自有参数,例如指定密钥,跳过host检查等。

2.其他有用的说明

2.1 格式化json输出

1
ANSIBLE_PYTHON_INTERPRETER=/usr/bin/python3 ANSIBLE_COMMAND_WARNINGS=false ANSIBLE_LOAD_CALLBACK_PLUGINS=true ANSIBLE_STDOUT_CALLBACK=json ansible  my_all -m shell -a "curl -s -6 icanhazip.com" 
  1. ANSIBLE_PYTHON_INTERPRETER 指定python路径
  2. ANSIBLE_COMMAND_WARNINGS 不输出warning
  3. ANSIBLE_LOAD_CALLBACK_PLUGINSANSIBLE_STDOUT_CALLBACK 指定json返回

效果参考:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
{
"custom_stats": {},
"global_custom_stats": {},
"plays": [
{
"play": {
"duration": {
"end": "2022-10-01T01:00:01.000001",
"start": "2022-10-01T01:00:02.000001"
},
"id": "aaaaaaa-44cc-6117-16e4-cccccccccccc",
"name": "Ansible Ad-Hoc"
},
"tasks": [
{
"hosts": {
"192.168.1.1": {
"_ansible_no_log": false,
"action": "command",
"changed": true,
"cmd": "curl -s icanhazip.com",
"delta": "0:00:01.486400000145",
"end": "2022-10-01 11:01:02.000001",
"invocation": {
"module_args": {
"_raw_params": "curl -s icanhazip.com",
"_uses_shell": true,
"argv": null,
"stdin_add_newline": true,
"strip_empty_ends": true,
"warn": false
}
},
"rc": 0,
"start": "2022-10-01 11:01:01.000001",
"stderr": "",
"stderr_lines": [],
"stdout": "180.101.49.11",
"stdout_lines": [
"180.101.49.11"
]
}
},
"task": {
"duration": {
"end": "2022-10-01T01:00:01.000001",
"start": "2022-10-01T01:00:02.000001"
},
"id": "aaaaaaa-44cc-6117-16e4-cccccccccccc",
"name": "shell"
}
}
]
}
],
"stats": {
"192.168.16.225": {
"changed": 1,
"failures": 0,
"ignored": 0,
"ok": 1,
"rescued": 0,
"skipped": 0,
"unreachable": 0
}
}
}

2.2.1 文件相关操作

1
2
3
4
5
6
#创建一个/opt/new_folder/的文件夹
ansible 192.168.1.1 -m ansible.builtin.file -a "dest=/opt/new_folder/ mode=755 owner=root group=root state=directory"
# 把当前服务器/tmp/index.html文件copy到目标服务器的/opt/new_folder/index.html文件
ansible 192.168.1.1 -b -m copy -a "dest=/opt/new_folder/index.html src=/tmp/index.html"
# 把远程服务器的/opt/new_folder/index.html拉取到本机/tmp/index.html
ansible 192.168.1.1 -m fetch -a "src=/opt/new_folder/index.html dest=/tmp/index.html fail_on_missing=no validate_checksum=no flat=true"