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、本系列教程用到的环境


# 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系统下进行


yum install ansible

2、方式二 源码安装

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


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

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


pip install ansible

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

Ansible 安装成功之后的验证


(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 没有启动服务一说,说明配置文件的更改是即时生效的。

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

[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 配置几个测试主机,类似

test-01-vpc
test-02-vpc

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

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

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

(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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 151,829评论 1 331
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 64,603评论 1 273
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 101,846评论 0 226
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 42,600评论 0 191
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 50,780评论 3 272
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 39,695评论 1 192
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,136评论 2 293
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 29,862评论 0 182
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 33,453评论 0 229
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 29,942评论 2 233
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,347评论 1 242
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 27,790评论 2 236
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,293评论 3 221
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 25,839评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,448评论 0 181
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 34,564评论 2 249
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 34,623评论 2 249

推荐阅读更多精彩内容