白日依山尽,黄河入海流。欲穷千里目,更上一层楼。 -- 唐·王之涣

Ansible系列-基础篇-Ansible 的安装、配置和基本使用

欢迎关注个人公众号 DailyJobOps

原文地址: Ansible系列-基础篇-Ansible 的安装、配置和基本使用

在这里插入图片描述


说在之前

文章比较详细比较长,建议收藏哦

1、Ansible 目前支持Linux和MacOS作为控制节点,管理节点可以是Linux、MacOS、其他类Unix系统和Windows。

2、Ansible 节点主要分为两类,管理节点和被管理节点

  • 管理节点,就是安装了 Ansible 的节点,Ansible 所有的指令都是这里发出,类似指挥部下发通知指令
  • 被管理节点,或者叫目标节点一般是业务主机等,需要在这些节点上批量的部署一些软件、执行命令、添加定义任务等等

需要主要的是 管理节点被管理节点 之间需要配置好 SSH免密通道

3、如果可以的话,个人建议Python还是使用3.0以上版本,虽然系统预装了2.7.5 但是官方都宣布不再维护该版本了,其他类似 opensslgit 等系统默认的版本就已经满足

4、本系列教程用到的环境

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

# python
(kfz-ansible) [jumproot@devops-jumpserver-vm]$ python -V
Python 3.9.8

# git
(kfz-ansible) [jumproot@devops-jumpserver-vm ~ Sat Nov 20 16:05:10]$ git --version
git version 1.8.3.1

# Linux system
(kfz-ansible) [jumproot@devops-jumpserver-vm ~ Sat Nov 20 16:05:13]$ cat /etc/redhat-release
CentOS Linux release 7.4.1708 (Core)
(kfz-ansible) [jumproot@devops-jumpserver-vm ~ Sat Nov 20 16:05:26]$ uname -a
Linux devops-jumpserver-vm 3.10.0-693.el7.x86_64 #1 SMP Tue Aug 22 21:09:27 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux

Ansible 安装

1、方式一 包管理器安装
比如 CentOSFedoraRedhat等系统下使用yum, Mac下使用brew, Ubuntu、Debian等系统使用 apt-get,如上说明,本系列都是在Centos系统下进行

1
2
3

yum install ansible

2、方式二 源码安装

源码安装一般是为了尝鲜安装的最新版本,用的较少

1
2
3
4
5
6

yum install git gcc-c++
git clone https://github.com/ansible/ansible.git
cd ansible
make install

3、方式三 采用Python PIP包安装

1
2
3

pip install ansible

这里建议采用方式三安装,Python可以通过 pyenv 来管理虚拟环境,同时后续可以通过Ansible API 进行Python集成,方便平台化定制开发

Ansible 安装成功之后的验证

1
2
3
4
5
6
7
8
9
10
11
12

(kfz-ansible) [jumproot@devops-jumpserver-vm]$ ansible --version
ansible [core 2.11.6]
config file = /etc/ansible/ansible.cfg
configured module search path = ['/home/jumproot/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
ansible python module location = /data/.pyenv/versions/3.9.8/envs/kfz-ansible/lib/python3.9/site-packages/ansible
ansible collection location = /home/jumproot/.ansible/collections:/usr/share/ansible/collections
executable location = /data/.pyenv/versions/kfz-ansible/bin/ansible
python version = 3.9.8 (main, Nov 8 2021, 15:17:00) [GCC 4.8.5 20150623 (Red Hat 4.8.5-16)]
jinja version = 3.0.2
libyaml = True


Ansible 配置

在正式聊 Ansible 配置之前,我们可以先仔细观察下上面 ansible --version 的输出结果,其中 config file 是 Ansible 配置文件存放的位置, 另外注意 jinjalibyaml ,其中 jinja 是 Ansible Role 中的 templates 用到的,而 libyamlAnsible playbook 编写时用到的文件格式,具体我们都会在后续文章中进行详细说明。这里先了解下就行。

其实这里还有个文件格式没有展示出来,就是 Ansible Inventory 文件的格式,采用的是 ini 格式

好了我们正式聊聊如果配置 Ansible,其实除了上面提到的 config file 制定的配置之外。Ansible 会从以下方式按照由上到下优先级加载配置

  • ANSIBLE_CONFIG 定义的变量
  • 当前目录下的 ansible.cfg
  • 当前用户家目录下的 ansible.cfg (~/.ansible.cfg)
  • 最后是config file 指向的配置文件 /etc/ansible/ansible.cfg

ansible.cfg 配置文件详解

ansible.cfg 的配置项很多,实际环境中其实不会所有的配置项都配置,遵循二八法则。而且 Ansible 没有启动服务一说,说明配置文件的更改是即时生效的。

这里先看看本环境中用到的配置,然后做详细说明

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
[root@baolei-sa-vm ~]# cat /etc/ansible/ansible.cfg  |egrep -v '^$|^#'
[defaults]
deprecation_warnings=False
inventory = /etc/ansible/inventory/pro.hosts
forks = 12
gathering = smart
fact_caching_timeout=14400
fact_caching=redis
fact_caching_connection=127.0.0.1:6379
gather_timeout = 15
host_key_checking = False
stdout_callback = debug
timeout = 30
log_path = /var/log/ansible.log
display_skipped_hosts = False
retry_files_save_path = ~/.ansible-retry

[inventory]

[privilege_escalation]
become=True
become_method=sudo
become_user=root

[paramiko_connection]

[ssh_connection]
ssh_args = -C -o ControlMaster=auto -o ControlPersist=5d
pipelining = False
transfer_method = scp

[persistent_connection]
command_timeout = 20

[accelerate]

[selinux]

[colors]

[diff]

  • defaults

    • inventory 配置主机、主机组等,一般采用默认值 /etc/ansible/hosts ,这里因为划分了不同的环境,所以做了定制配置
    • remote_tmp 远程主机可执行脚本临时存放位置,一般采用默认值 ~/.ansible/tmp
    • local_tmp 管理节点可执行脚本临时存放位置,一般采用默认值 ~/.ansible/tmp
    • retry_files_save_path 默认情况下,当playbook执行失败时,将创建 retry文件,默认为 ~/.ansible-retry; 可以通过 retry_files_enabled = False来关闭
    • forks Ansible执行的并发数,根据自己实际情况配置即可
    • log_path Ansible log 存放位置,默认是 /var/log/ansible.log
    • timeout Ansible ssh连接超时时间
    • gathering facts信息收集开关定义,smart默认收集,如果已经收集将不再收集;implicit默认收集,使用gather_facts=False可以取消收集;explicit默认情况不收集
    • gathering_timeout facts信息收集超时时间
    • fact_caching facts信息收集缓存的方式,默认是memory,建议采用redis
    • fact_caching_timeout facts信息收集缓存超时时间
    • fact_caching_connection 如果是Redis,127.0.0.1:6379;如果Redis有密码认证则则配置为 127.0.0.1:6379:10:password
    • host_key_checking 禁用主机的ssh的密钥检查,这个的主要目的是,ssh首次登录的时候有个公钥检查,需要手动确认之后写入known_hosts文件
    • private_key_file 使用公私钥对认证是,私钥的位置
    • stdout_callback ansible 输出的方式,这里配置为debug输出,也可以通过 bin_ansible_callbacks=True 然后加载定义的回调插件callback_plugins, 具体如何自定义回调,在提高篇详细说明
    • display_skipped_hosts 是否显示跳过的主机

在defaults部分除了上述配置之外,其他都采用默认配置,另外需要大家关注的几个配置选项是 remote_user / remote_port / sudo_user / ask_sudo_pass

  • inventory

    是对Inventory进行一些特殊配置,一般保持默认即可

  • privilege_escalation

    • become=True 开启become模式
    • become_method=sudo become方式为sudo
    • become_user=root become为root
    • become_ask_pass 默认为False不提示要密码
  • ssh_connection

    • ssh_args Ansible是通过远程ssh的方式管控目标主机,该选项定义ssh的参数关于ssh参数的定义可以参考 SSH Config 那些你所知道和不知道的
    • pipelining 默认情况下,禁用此选项以保持兼容性,sudoers默认配置requiretty;如果启用流水线操作可减少在远程服务器上执行模块所需的SSH操作数量,显着提高性能,但是当使用sudo时,必须先在 /etc/sudoers中禁用requiretty
    • transfer_method 控制传输文件的机制。配置sftp使用sftp传输文件,配置scp使用scp传输文件,配置piped通过SSH使用’dd’来传输文件,配置smart按顺序尝试sftp,scp和piped,默认为smart
  • persistent_connection

    • command_timeout 命令超时值定义在超时之前等待命令或RPC调用的时间。 命令超时的值必须小于持久连接空闲超时(connect_timeout)的值
    • connect_timeout 配置持久连接超时值。 此值是持久连接在销毁之前保持空闲的时间,如果连接在超时值到期之前未收到请求,则连接将关闭。默认是30秒
    • connect_retry_timeout 配置持久连接重试超时。 此值配置ansible-connection将等待连接到本地域套接字的重试超时。该值必须大于ssh timeout(超时)且小于持久连接空闲超时(connect_timeout)。默认值为15秒。

Ansible 免密登录

在配置之前,先说个运维规范,一般为了安全要求,Linux环境会禁用密码登录,采用公私钥对登录(特殊主机建议禁用root登录),因为通过ansible管理一般都是内网,这里默认是允许root登录的。

这里可能可能有人会问,为啥不统一也把root登录给全部禁用呢,这样岂不是更安全呢?

  • 是的,禁用root登录更加安全,但是如果是从Ansible管控角度,新增的主机,我们需要先给配置一个具有sudo免密权限 的SA用户,后面才可以使用该用户去执行ansible更加合理。新增主机新增用户肯定是需要用root的。

  • 当然这里也有替代方案。就是新增主机采用模板镜像的方式,镜像中内置一个不会删除的 具有sudo免密权限 的用户,比如 devops 账号,最好不能具体的某个员工账号,因为员工会离职的嘛

所以视自己实际环境而定哦

好了,我们回到正题,我们知道Ansible的调用是通过ssh远程执行,如果在配置文件中配置了private_key_file 那么不管你使用哪个账号去执行,对应的公钥就是该私钥匹配的, 这样就会导致不同账号得使用相同的公私钥,这样不安全,也不友好

实际中,在配置文件中不配置 private_key_file, 然后新增的SA账号单独配置免密登录,员工离职清理账号也不影响其他人。

至于如果配置SSH免密登录,网上教程一大堆,这里就不啰嗦了

Ansible 基本使用

这里我们在 /etc/ansible/inventory/pro.hosts 配置几个测试主机,类似

1
2
3
4
5
6
test-01-vpc
test-02-vpc

[devops_group]
devops-gitlab-vpc
devops-walle-vpc
  • 测试主机是否联通
    1
    ansible devops_group -m ping 
  • 收集远程主机信息
1
ansible devops-* -m setup
  • 检查远程主机程序是否启动Java程序
1
ansible test-* -m shell -a 'ps -ef|grep java'
  • 复制文件到远程主机
1
ansible test-* -m copy -a 'src=test.sh dest=/opt/scripts/test.sh mode=0755 owner=root
  • 执行远程主机上的脚本
1
ansible test-* -m shell -a 'bash /opt/scripts/test.sh'

这种命令执行的方式叫做 Ad-hoc , 具体 Ansible 都有哪些内置模块,可以参考 Ansible.Builtin

如果知道模块,但是不知道怎么用,可以尝试 ansible-doc -s module-name,比如上面的shell 模块

1
2
3
4
5
6
7
8
9
10
11
12
13
(kfz-ansible) [jumproot@devops-jumpserver-vm]$ ansible-doc -s shell
- name: Execute shell commands on targets
shell:
chdir: # Change into this directory before running the command.
cmd: # The command to run followed by optional arguments.
creates: # A filename, when it already exists, this step will *not* be run.
executable: # Change the shell used to execute the command. This expects an absolute path to the executable.
free_form: # The shell module takes a free form command to run, as a string. There is no actual parameter named 'free form'. See the examples on how to
use this module.
removes: # A filename, when it does not exist, this step will *not* be run.
stdin: # Set the stdin of the command directly to the specified value.
stdin_add_newline: # Whether to append a newline to stdin data.
warn: # Whether to enable task warnings.

下一篇我们来说说工作中常用的模块及其用法


参考:

1、https://www.cnblogs.com/yangmingxianshen/p/12655843.html
2、https://docs.ansible.com/ansible/latest/collections/ansible/builtin/index.html

作者

Colin

发布于

2021-05-01

许可协议