部署Ansible

自动化运维工具Ansible

1构建Ansible清单

1.1定义清单文件

  • 清单定义Ansible将要管理的一批主机。这些主机也可以分配到组中,以进行集中管理。组可以包含子组,主机也可以是多个组的成员。清单还可以设置应用到它所定义的主机和组的变量。

  • 可以通过两种方式定义主机清单。静态主机清单可以通过文本文件定义。动态主机清单可以根据需要使用外部信息提供程序通过脚本或其他程序来生成。

  • ansible的主要功能在于批量主机操作,为了便捷的使用启动的部分主机,可以在inventory file中将其分组命名

1.2主机清单

  • Ansible主机清单文件:Ansible可同时操作属于一个组的多台主机,组和主机之间的关系通过inventory文件配置. 默认的文件路径为/etc/ansible/hosts
  1. 示例
cat /etc/ansible/hosts
# Ex 1: Ungrouped hosts, specify before any group headers.

## green.example.com
## blue.example.com
## 192.168.100.1
## 192.168.100.10

# Ex 2: A collection of hosts belonging to the 'webservers' group

## [webservers]
## alpha.example.org
## beta.example.org
## 192.168.1.100
## 192.168.1.110

# If you have multiple hosts following a pattern you can specify
# them like this:

## www[001:006].example.com

# Ex 3: A collection of database servers in the 'dbservers' group

## [dbservers]
## 
## db01.intranet.mydomain.net
## db02.intranet.mydomain.net
## 10.25.1.56
## 10.25.1.57

# Here's another example of host ranges, this time there are no 连续大量主机清单[start:end]
# leading 0s:

## db-[99:101]-node.example.com

2.主机清单讲解

  • “#”开始表示注释,空格行被忽略
  • 一个主机名或者IP地址可以出现在多个分组中
  • 主机列表可以使用主机名或者IP地址
  • 使用[start:end]表示连续的主机,只支持升序排列
  • 使用[]设置远程主机分组。[]内写的是组名
  • 分组支持嵌套,一个组可以包含其他组,新组名中以“:children“后缀

3.编写示例

#1.标准主机
green.example.com

#2.分组的
[webservers]
alpha.example.org
beta.example.org

#3.连续大量的清单
[web]
db-[99:101]-node.example.com
192.168.[1:5].[0:255] //192.168.1.0-192.168.5.255下的所有主机

#4.非标准端口下的主机清单这样写
blue.example.com:4399 

#5.组内还包含其他组:
[a]
1.example.com
[b]
2.example.com
[c:children]
a
b

#6.设置连接参数
[member]
localhost ansible_connection=local ansible_user=user

1.3覆盖清单的位置

  • 静态清单文件是指定Ansible目标受管主机的文本文件。可以使用多种不同的格式编写此文件,包括INI样式或YAML。
  • /etc/ansible/hosts文件被视为系统的默认静态清单文件。不过,通常的做法是不使用该文件,而是在Ansible配置文件中为清单文件定义一个不同的位置。
  1. 编辑主机清单

编辑ansible.cfg配置文件,将inventory = /etc/ansible/hosts改为inventory = /etc/ansible/inventory

[defaults]

# some basic default values...

#inventory      = /etc/ansible/hosts
inventory      = /etc/ansible/inventory
#library        = /usr/share/my_modules/
#module_utils   = /usr/share/my_module_utils/
#remote_tmp     = ~/.ansible/tmp
#local_tmp      = ~/.ansible/tmp
  1. 创建inventory文件
[root@zhaojie ansible]# touch inventory
[root@zhaojie ansible]# ls
ansible.cfg  hosts  inventory  roles
[root@zhaojie ansible]# 

1.4构建Ansible清单文件

  • 修改默认清单文件/etc/ansible/inventory添加受管主机
[root@zhaojie ansible]# cat inventory 
192.168.25.129

[webservers]
192.168.25.130
192.168.25.131

  • 使用以下命令列出默认清单文件中的所有受管主机
 [root@zhaojie ~]# ansible all --list-hosts
  hosts (3):
    192.168.25.129
    192.168.25.130
    192.168.25.131
  • 使用以下命令列出不属于任何组的受管主机
[root@zhaojie ~]# ansible ungrouped --list-hosts
  hosts (1):
    192.168.25.129

  • 使用以下命令列出属于某组的受管主机
[root@zhaojie ~]# ansible webservers --list-hosts
  hosts (2):
    192.168.25.130
    192.168.25.131

1.5使用静态清单指定受管主机

  • 静态清单文件是指定Ansible目标受管主机的文本文件。

进入inventory编写受管主机ip

[root@zhaojie ansible]# cat inventory 
192.168.25.130

给受管主机加入组

[root@zhaojie ansible]# cat inventory 
[webservers]
192.168.25.130

1.6验证主机清单

  • 使用 ansible 命令验证计算机是否存在于清单中

1.针对组(webservers)

[root@zhaojie ~]# ansible webservers --list-hosts
  hosts (1):
    192.168.25.130

2.针对主机(IP)

[root@zhaojie ~]# ansible 192.168.25.130 --list-hosts
  hosts (1):
    192.168.25.130

1.7自定义清单文件

  • 编辑/etc/ansible/inventory文件,将主机加入受管主机序列
[root@zhaojie ansible]# cat inventory 
[webservers]
192.168.25.130  ansible_user=root ansible_password=runtime

2管理Ansible配置文件

2.1配置Ansible

  • 可以通过修改 Ansible 配置文件中的设置来自定义Ansible安装的行为。Ansible从控制节点上多个可能的位置之一选择其配置文件。

使用/etc/ansible/ansible.cfg

  • ansible软件包提供一个基本的配置文件,它位于/etc/ansible/ansible.cfg。如果找不到其他配置文件,则使用此文件。

使用~/.ansible.cfg

  • Ansible在用户的家目录中查找.ansible.cfg文件。如果存在此配置文件并且当前工作目录中也没有ansible.cfg文件,则使用此配置取代/etc/ansible/ansible.cfg。

使用./ansible.cfg

  • 如果执行ansible命令的目录中存在ansible.cfg文件,则使用它,而不使用全局文件或用户的个人文件。这样,管理员可以创建一种目录结构,将不同的环境或项目存储在单独的目录中,并且每个目录包含为独特的一组设置而定制的配置文件。

使用ANSIBLE_CONFIG环境变量

  • 我们可以通过将不同的配置文件放在不同的目录中,然后从适当的目录执行Ansible命令,以此利用配置文件。但是,随着配置文件数量的增加,这种方法存在局限性并且难以管理。有一个更加灵活的选项,即通过ANSIBLE_CONFIG环境变量定义配置文件的位置。定义了此变量时,Ansible将使用变量所指定的配置文件,而不用上面提到的任何配置文件。

推荐用法

  • 推荐的做法是在需要运行Ansible命令的目录中创建ansible.cfg文件。此目录中也将包含任何供Ansible项目使用的文件,如清单和playbook。这是用于Ansible配置文件的最常用位置。实践中不常使用~/.ansible.cfg或/etc/ansible/ansible.cfg文件

2.2配置文件的优先级

  • 由于Ansible配置文件可以放入的位置有多种,因此Ansible当前使用哪一个配置文件可能会令人困惑。我们可以运行以下命令来清楚地确认所安装的Ansible版本以及正在使用的配置文件。
[root@localhost ~]# ansible --version
ansible 2.9.23
  config file = /root/.ansible.cfg
  configured module search path = ['/root/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/lib/python3.6/site-packages/ansible
  executable location = /usr/bin/ansible
  python version = 3.6.8 (default, Dec  5 2019, 15:45:45) [GCC 8.3.1 20191121 (Red Hat 8.3.1-5)]

优先级如下:

  • 首先找执行ansible命令的当前目录中,是否有 ansible.cfg文件

  • 如果找不到,再找当前用户的家目录下是否有 .ansible.cfg

  • 如果还找不到,就找 /etc/ansible/ansible.cfg

  • ANSIBLE_CONFIG环境变量指定的任何文件将覆盖其他所有的Ansible配置文件,所以ANSIBLE_CONFIG指定的文件优先级最高

  • ANSIBLE_CONFIG > ./ansible.cfg > ~/.ansible.cfg > /etc/ansible/ansible.cfg

  • 当前目录下的配置文件

[root@localhost ~]# cd /opt/ll/
[root@localhost ll]# ls
ansible.cfg  inventory
[root@localhost ll]# ansible --version
ansible 2.9.23
  config file = /opt/ll/ansible.cfg
  configured module search path = ['/root/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/lib/python3.6/site-packages/ansible
  executable location = /usr/bin/ansible
  python version = 3.6.8 (default, Dec  5 2019, 15:45:45) [GCC 8.3.1 20191121 (Red Hat 8.3.1-5)]

  • 家目录下的配置文件【有.ansible.cfg文件时】
[root@localhost ~]# ansible --version
ansible 2.9.23
  config file = /root/.ansible.cfg
  configured module search path = ['/root/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/lib/python3.6/site-packages/ansible
  executable location = /usr/bin/ansible
  python version = 3.6.8 (default, Dec  5 2019, 15:45:45) [GCC 8.3.1 20191121 (Red Hat 8.3.1-5)]

  • 家目录下的配置文件【没有.ansible.cfg文件时】
[root@localhost ~]# ls -a
.      视频  anaconda-ks.cfg  .cache         initial-setup-ks.cfg  .Xauthority
..     图片  .ansible         .config        .local
1      文档  .bash_history    .cshrc         .pki
1.pub  下载  .bash_logout     .dbus          .ssh
公共   音乐  .bash_profile    .esd_auth      .tcshrc
模板   桌面  .bashrc          .ICEauthority  .viminfo
[root@localhost ~]# ansible --version
ansible 2.9.23
  config file = /etc/ansible/ansible.cfg
  configured module search path = ['/root/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/lib/python3.6/site-packages/ansible
  executable location = /usr/bin/ansible
  python version = 3.6.8 (default, Dec  5 2019, 15:45:45) [GCC 8.3.1 20191121 (Red Hat 8.3.1-5)]

  • 在默认路径/etc/ansible/absible.cfg时
[root@localhost ~]# cd /etc/ansible/
[root@localhost ansible]# ls
ansible.cfg  hosts  inventory  roles
[root@localhost ansible]# ansible --version
ansible 2.9.23
  config file = /etc/ansible/ansible.cfg
  configured module search path = ['/root/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/lib/python3.6/site-packages/ansible
  executable location = /usr/bin/ansible
  python version = 3.6.8 (default, Dec  5 2019, 15:45:45) [GCC 8.3.1 20191121 (Red Hat 8.3.1-5)]

  • 使用环境变量ANSIBLE_CONFIG指定文件时
[root@localhost ~]# ls -a
.      视频  anaconda-ks.cfg  .bashrc    .ICEauthority         .viminfo
..     图片  .ansible         .cache     initial-setup-ks.cfg  .Xauthority
1      文档  .ansible.cfg     .config    .local
1.pub  下载  .bash_history    .cshrc     .pki
公共   音乐  .bash_logout     .dbus      .ssh
模板   桌面  .bash_profile    .esd_auth  .tcshrc
[root@localhost ~]# export ANSIBLE_CONFIG=/etc/ansible/ansible.cfg 
[root@localhost ~]# ansible --version
ansible 2.9.23
  config file = /etc/ansible/ansible.cfg
  configured module search path = ['/root/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/lib/python3.6/site-packages/ansible
  executable location = /usr/bin/ansible
  python version = 3.6.8 (default, Dec  5 2019, 15:45:45) [GCC 8.3.1 20191121 (Red Hat 8.3.1-5)]

2.3 管理配置文件中的设置

  • [defaults]部分设置Ansible操作的默认值

  • [privilege_escalation]配置Ansible如何在受管主机上执行特权升级

ansible.cfg文件

[defaults]
inventory = ./inventory   清单文件
remote_user = user   远程用户
ask_pass = false   

[privilege_escalation]
become = true
become_method = sudo
become_user = root
become_ask_pass = false

对ansible.cfg文件的指令描述

指令描述
inventory指定清单文件的路径
remote_user要在受管主机上登录的用户名。如果未指定则使用当前用户名
become连接后是否自动在受管主机上切换用户(通常切换为root) 这也可以通过play来指定
become_method如何切换用户(通常为sudo,这也是默认设置,但可选择su)
become_user要在受管主机上切换到的用户(通常是root,这也是默认值)
become_ask_pass是否需要为become_method提示输入密码。默认为false
ask_pass是否提示输入SSH密码。如果使用SSH公钥身份验证则可以是false

2.4配置连接

Ansible需要知道如何与其受管主机通信。更改配置文件的一个最常见原因是为了控制Ansible使用什么方法和用户来管理受管主机。需要的一些信息包括

  • 列出受管主机和主机组的清单的位置
  • 要使用哪一种连接协议来与受管主机通信(默认为SSH),端口号为22,以及是否需要非标准网络端口来连接服务器
  • 要在受管主机上使用哪一远程用户;这可以是root用户或者某一非特权用户
  • 如果远程用户为非特权用户,Ansible需要知道它是否应尝试将特权升级为root以及如何进行升级(例如,通过sudo)
  • 是否提示输入SSH密码或sudo密码以进行登录或获取特权

2.5连接设置

  • 默认情况下,Ansible尝试连接受管主机时使用的用户名与运行ansible命令的本地用户相同。若要指定不同的远程用户,请将remote_user参数设置为该用户名。
# default user to use for playbooks if user is not specified
# (/usr/bin/ansible will use current user as default)
remote_user = root

# logging is off by default unless this path is defined
# if so defined, consider logrotate
#log_path = /var/log/ansible.log

# default module name for /usr/bin/ansible
#module_name = command

  • 如果为运行Ansible的本地用户配置了SSH私钥,使得它们能够在受管主机上进行远程用户的身份验证,则Ansible将自动登录。如果不是这种情况,可以通过设置指令ask_pass = true,将Ansible配置为提示本地用户输入由远程用户使用的密码。
【defaults]
inventory = ./inventory

remote_user = root
ask_pass = true
  • 也可以为受管主机设置免密登录
[root@localhost ansible]# ssh-keygen  -t  rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa): 
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:gEFH9AsWrct8inVeuhyx84vrQQiPZwu8q5LM/cyu9FU root@localhost.localdomain
The key's randomart image is:
+---[RSA 3072]----+
|   .oo=.         |
|     + o.        |
|    o +..        |
|   . =.+ .       |
|    +o=.SE       |
|     ==o+o.      |
|o....o.*=o       |
|oo..=.o.o*       |
| ..o=* .*oo.     |
+----[SHA256]-----+
[root@localhost ansible]# 
[root@localhost ansible]# 
[root@localhost ansible]# ssh-copy-id  192.168.25.130
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
root@192.168.25.130's password: 

Number of key(s) added: 1

Now try logging into the machine, with:   "ssh '192.168.25.130'"
and check to make sure that only the key(s) you wanted were added.

[root@localhost ansible]# 

再次测试是否能ping通


[root@localhost ansible]# ansible all -m ping
192.168.153.128 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": false,
    "ping": "pong"
}

2.6升级特权

  • 鉴于安全性和审计原因,Ansible可能需要先以非特权用户身份连接远程主机,然后再通过特权升级获得root用户身份的管理权限。这可以在Ansible配置文件的[privilege_escalation]部分中设置。
  • 要默认启用特权升级,可以在配置文件中设置指令become = true。即使默认为该设置,也可以在运行临时命令或Ansible Playbook时通过各种方式覆盖它。(例如,有时候可能要运行一些不需要特权升级的任务或play。)
  • become_method指令指定如何升级特权。有多个选项可用,但默认为使用sudo。类似地,become_user指令指定要升级到的用户,但默认为root。
  • 如果所选的become_method机制要求用户输入密码才能升级特权,可以在配置文件中设置become_ask_pass = true指令。

示例ansible.cfg文件假设你可以通过基于SSH密钥的身份验证以someuser用户身份连接受管主机,并且someuser可以使用sudo以root用户身份运行命令而不必输入密码

[defaults]
inventory = ./inventory
remote_user = someuser
ask_pass = false

[privilege_escalation]
become = true
become_method = sudo
become_user = root
become_ask_pass = false

2.7配置文件注释

  • Ansible配置文件允许使用两种注释字符:井号或分号。
  • 位于行开头的#号会注释掉整行。它不能和指令位于同一行中。
  • 分号字符可以注释掉所在行中其右侧的所有内容。它可以和指令位于同一行中,只要该指令在其左侧。

3临时命令

3.1运行临时命令

临时命令对于通过Ansible快速执行简单的任务非常有用。它们确实也存在局限,而且总体而言,要使用Ansible Playbook来充分发挥Ansible的作用

  • 语法:ansible host-pattern -m module [-a ‘module arguments’] [-i
    inventory]

  • host-pattern参数用于指定在其上运行临时命令的受管主机。它可以是清单中的特定受管主机或主机组。也可以用后面的-i选项指定特定的清单而不使用默认清单

  • -m选项将Ansible应在目标主机上运行的module名称作为参数。模块是为了实施任务而执行的小程序。一些模块不需要额外的信息,但其他模块需要使用额外的参数来指定其操作详情。-a选项以带引号字符串形式取这些参数的列表

使用临时命令使用ping模块,确定清单中的所有受管主机能否运行标准的模块

[root@zhaojie ansible]# ansible all -m ping
192.168.25.130 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": false,
    "ping": "pong"
}

3.2使用临时命令通过模块来执行任务

模块是Ansible执行的最小单位,可以是由Python编写,也可以是Shell编写,也可以是由其他语言编写。模块是临时命令用于完成任务的工具。Ansible提供了数百个能够完成不同任务的模块。通常我们可以查找一个经过测试的专用模块,作为标准安装的一部分来完成所需的任务。

  • ansible-doc -l命令可以列出系统上安装的所有模块
[root@localhost ~]# ansible-doc -l
a10_server                                                    Manage A10 Network...
a10_server_axapi3                                             Manage A10 Network...
a10_service_group                                             Manage A10 Network...
a10_virtual_server                                            Manage A10 Network...
aci_aaa_user                                                  Manage AAA users (...
aci_aaa_user_certificate                                      Manage AAA user ce...
aci_access_port_block_to_access_port                          Manage port blocks...
aci_access_port_to_interface_policy_leaf_profile              Manage Fabric inte...
aci_access_sub_port_block_to_access_port                      Manage sub port bl...
aci_aep                                                       Manage attachable ...
aci_aep_to_domain                                             Bind AEPs to Physi...
aci_ap                                                        Manage top level A...
aci_bd                                                        Manage Bridge Doma...
aci_bd_subnet                                                 Manage Subnets (fv...
aci_bd_to_l3out                                               Bind Bridge Domain...
aci_config_rollback                                           Provides rollback ...
aci_config_snapshot                                           Manage Config Snap...
aci_contract                                                  Manage contract re...
aci_contract_subject                                          Manage initial Con...
aci_contract_subject_to_filter                                Bind Contract Subj...
aci_domain            
......
               
  • 使用ansible-doc来按照名称查看特定模块的帮助文档,再查找关于模块将取什么参数作为选项的信息
    查看user模块的帮助文档
[root@localhost ~]# ansible-doc user
> USER    (/usr/lib/python3.6/site-packages/ansible/modules/system/user.py)

        Manage user accounts and user attributes. For Windows targets,
        use the [win_user] module instead.

  * This module is maintained by The Ansible Core Team
OPTIONS (= is mandatory):

- append
        If `yes', add the user to the groups specified in `groups'.
        If `no', user will only be added to the groups specified in
        `groups', removing them from all other groups.
        Mutually exclusive with `local'
        [Default: False]
        type: bool

- authorization
        Sets the authorization of the user.
        Does nothing when used with other platforms.
        Can set multiple authorizations using comma separation.
        To delete all authorizations, use `authorization='''.
......

过滤user模块

[root@localhost ~]# ansible-doc -l|grep user
aci_aaa_user                                                  Manage AAA users (...
aci_aaa_user_certificate                                      Manage AAA user ce...
avi_cloudconnectoruser                                        Module for setup o...
avi_user                                                      Avi User Module   
avi_useraccount                                               Avi UserAccount Mo...
avi_useraccountprofile                                        Module for setup o...
bigip_apm_acl                                                 Manage user-define...
bigip_remote_user                                             Manages default se...
bigip_user                                                    Manage user accoun...
ce_snmp_user                                                  Manages SNMP user ...
cnos_user                                                     Manage the collect...
cpm_user                                                      Get various status...
......
user                                                          Manage user accoun...
vertica_user                                                  Adds or removes Ve...
vmware_local_user_facts                                       Gather facts about...
vmware_local_user_info                                        Gather info about ...
vmware_local_user_manager                                     Manage local users...
vultr_user                                                    Manages users on V...
vultr_user_facts                                              Gather facts about...
vultr_user_info                                               Get information ab...
vyos_user                                                     Manage the collect...
win_domain_user                                               Manages Windows Ac...
win_user                                                      Manages local Wind...
win_user_profile                                              Manages the Window...
win_user_right                                                Manage Windows Use...
xattr                                                         Manage user define...
[root@localhost ~]# 

大部分模块会取用参数。可在模块的文档中找到可用于该模块的参数列表。临时命令可以通过-a选项向模块传递参数。无需参数时,可从临时命令中省略-a选项。如果需要指定多个参数,请以引号括起的空格分隔列表形式提供。

  • 使用临时命令user模块来创建runtime用户存在于192.168.25.130并且uid为4000
[root@node1 ~]# id runtime
id: “runtime”:无此用户
[root@node1 ~]# 
[root@localhost ansible]# ansible 192.168.25.130 -m user -a 'name=runtime uid=4000 state=present'
192.168.25.130 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": true,
    "comment": "",
    "create_home": true,
    "group": 4000,
    "home": "/home/runtime",
    "name": "runtime",
    "shell": "/bin/bash",
    "state": "present",
    "system": false,
    "uid": 4000
}
[root@node1 ~]# id runtime
uid=4000(runtime) gid=4000(runtime) 组=4000(runtime)
[root@node1 ~]# 


  • 删除runtime用户
[root@localhost ansible]# ansible 192.168.25.130 -m user -a 'name=runtime  state=absent'
192.168.25.130 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": true,
    "force": false,
    "name": "runtime",
    "remove": false,
    "state": "absent"
}
[root@node1 ~]# id runtime
id: “runtime”:无此用户
[root@node1 ~]# 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值