Ansible部署

本文介绍了Ansible的配置管理,包括配置文件的位置、优先级和管理方式,详细讲解了如何通过command模块和user模块执行命令和管理用户,并提供了相关参数的使用示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、管理Ansible配置文件

清单文件位置

系统默认的清单文件位置是/etc/ansible/hosts,通常我们不使用该文件,而是在Ansible配置文件中为清单定义一个不同的位置。

[root@client ansible]# vim ansible.cfg 
#inventory      = /etc/ansible/hosts
inventory      = /etc/ansible/inventory		#资源清单inventory文件的位置

ansible配置文件设置
Ansible配置文件由几个部分组成,每一部分含有以键值对形式定义的设置。

  • [defaults] 部分设置Ansible操作的默认值
  • [privilege_escalation] 配置Ansible如何在受管主机上执行特权升级
#常见的参数
[defaults]
inventory = /etc/ansible/hosts		#指定清单路径
library = /usr/share/my_modules/		#指向存放ansible模块的路径
forks = 5		#开发连接数
sudo_user = root	#设置默认执行命令的用户
remote_port = 22		#指定连接被管节点的管理端口,默认为22端口

[privilege_escalation]
become = true	#连接后是否自动在受管主机上切换用户
become_method = sudo	#如何切换用户,默认sudo
become_user = root	#要在受管主机上切换到的用户,默认root
become_ask_pass = false	#是否需要为become_method提示输入密码,默认false

Ansible命令

ansible命令执行状态:

  • 绿色:执行成功并且不需要做改变
  • 黄色:执行成功并且对目标主机做更改
  • 红色:执行失败
[root@client ansible]# ansible -h
Usage: ansible <host-pattern> [options]
Options:
  -a MODULE_ARGS, --args=MODULE_ARGS    #模块的参数,如果执行默认COMMAND的模块
					module arguments	#m模块参数
  --list-hosts     #显示主机列表,可简写-list
  -m MODULE_NAME, --module-name=MODULE_NAME   #执行模块的名字,默认使用 command 模块,所以如果是只执行单一命令可以不用 -m参数
  -U SUDO_USER, --sudo-user=SUDO_USER    #sudo到哪个用户,默认为 root 
  --version             show program's version number and exit   #输出ansible的版本
  -v, --verbose         verbose mode (-vvv for more, -vvvv to enable connection debugging)		#详细信息
  -h, --help            show this help message and exit   #打开帮助文档API
  -k, --ask-pass        ask for SSH password  #登录密码,提示输入SSH密码而不是假设基于密钥的验证

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

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

连接设置
默认情况下Ansible使用ssh协议连接受管主机。控制Ansible连接受管主机的重要参数在[defaults]部分中。

默认情况下Ansible连接受管主机时使用的用户名与运行ansible命令的本地用户相同。若要指定不同的用户,将remote_user参数设置该用户名。

如果运行Ansible的本地用户配置了SSH私钥,使得他们能够在受管主机上进行远程用户的身份验证,则Ansible将自动登录。如果没有配置私钥,可以通过指令ask_pass = true,将Ansible配置为提示本地用户输入由远程用户使用的密码。

remote_user = root
ask_pass = true

升级特权
鉴于安全性和审计原因,Ansible可能需要先以非特权用户身份连接远程主机,然后再通过特权升级获得root用户身份的管理权限。这可以在Ansible配置文件的[privilege_escalation]部分中设置。

要默认启用特权升级,可以在配置文件中设置指令become = true。即使默认为该设置,也可以在运行临时命令或Ansible Playbook时通过各种方式覆盖它。(例如,有时候可能要运行一些不需要特权升级的任务或play。)

become_method指令指定如何升级特权。有多个选项可用,但默认为使用sudo。类似地,become_user指令指定要升级到的用户,但默认为root。

如果所选的become_method机制要求用户输入密码才能升级特权,可以在配置文件中设置become_ask_pass = true指令。

通过基于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

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

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

[root@client ansible]# vim ansible.cfg
[root@client ansible]# ansible --version
ansible 2.9.23
config file = /etc/ansible/ansible.cfg

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

[root@client ~]# ansible --version
ansible 2.9.23
config file = /root/.ansible.cfg

  • ./ansible.cfg 执行ansible命令的目录中存在ansilbe.cfg文件,则使用它,而不适用全局文件或用户的个人文件。管理员可以创建一种目录结构,将不同环境或项目存储在单独的目录中,并为其设置独特的配置文件

[root@client opt]# ls
ansible.cfg
[root@client opt]# ansible --version
ansible 2.9.23
config file = /opt/ansible.cfg

  • ANSIBLE_CONFIG环境变量 通过环境变量定义配置文件的位置。 定义此变量时,Ansible将使用变量所指定的配置文件,而不用其他的任何配置文件。

[root@client ~]# export ANSIBLE_CONFIG=/etc/ansible/ansible.cfg
[root@client ~]# ansible --version
ansible 2.9.23
config file = /etc/ansible/ansible.cfg

二、配置文件优先级

ANSIBLE_CONFIG环境变量指定的任何文件将覆盖所有其他配置文件。如果没有设置该环境变量,则检查运行ansible命令的目录中是否有ansible.cfg文件。如果不存在该文件,则检查用户的加目录是否有.ansible.cfg文件。只有在找不到其他配置文件时,才使用全局/etc/ansible/ansible.cfg文件,如果该配置文件不存在,Ansible包含它使用的默认值。
因为Ansible配置文件存储位置有多种,我们可以用以下命令来确认ansible正在使用的配置文件。

ansible --version

Ansible配置文件优先级:

ANSIBLE_CONFIG环境变量 > 当前目录下ansible.cfg > ~/.ansible.cfg > /etc/ansible/ansible.cfg

三、Ansible帮助文档

ansible-doc -l    #获取模块信息

[root@client ansible]# ansible-doc -l | grep user  #查看某一个模块名单
aci_aaa_user                                                  Manage AAA users (aaa:User)           
aci_aaa_user_certificate                                      Manage AAA user certificates (aaa:User...
avi_cloudconnectoruser                                        Module for setup of CloudConnectorUser...
avi_user                                                      Avi User Module                       
avi_useraccount                                               Avi UserAccount Module                
avi_useraccountprofile                                        Module for setup of UserAccountProfile...

[root@client ansible]# ansible-doc user		#查看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='''.
        Currently supported on Illumos/Solaris.
        [Default: (null)]
        type: str
        version_added: 2.8

- comment
        Optionally sets the description (aka `GECOS') of user account.
        [Default: (null)]
        type: str

- create_home
        Unless set to `no', a home directory will be made for the user when the
        account is created or if the home directory does not exist.
        Changed from `createhome' to `create_home' in Ansible 2.5.
        (Aliases: createhome)[Default: True]
        type: bool
:


ansible-doc -s MOD_NAME    #获取指定模块的使用帮助
[root@client ansible]# ansible-doc -s user
- name: Manage user accounts
  user:
      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'
      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='''.
                               Currently supported on Illumos/Solaris.
      comment:               # Optionally sets the description (aka `GECOS') of user account.
      create_home:           # Unless set to `no', a home directory will be made for the user when the
                               account is created or if the home
                               directory does not exist. Changed from
                               `createhome' to `create_home' in Ansible
                               2.5.
      expires:               # An expiry time for the user in epoch, it will be ignored on platforms
                               that do not support this. Currently
                               supported on GNU/Linux, FreeBSD, and
                               DragonFlyBSD. Since Ansible 2.6 you can
                               remove the expiry time specify a negative
                               value. Currently supported on GNU/Linux
                               and FreeBSD.
      force:                 # This only affects `state=absent', it forces removal of the user and
                               associated directories on supported
                               platforms. The behavior is the same as
                               `userdel --force', check the man page for
                               `userdel' on your system for details and
                               support. When used with
                               `generate_ssh_key=yes' this forces an
                               existing key to be overwritten.
      generate_ssh_key:      # Whether to generate a SSH key for the user in question. This will *not*
                               overwrite an existing SSH key unless used
                               with `force=yes'.
      group:                 # Optionally sets the user's primary group (takes a group name).
      groups:                # List of groups user will be added to. When set to an empty string `''',
:

ansible常用模块

模块描述
copy将本地文件复制到受管主机
file设置文件的权限和其他属性
lineinfile确保特定行是否在文件中
synchronize使用rsync同步内容
package使用操作系统本机的自动检测软件包管理器
yum使用yum管理软件包
apt使用apt管理软件包
dnf
pip从pypi管理Python软件包
firewalld使用firewalld管理防火墙
reboot重启计算机
server管理服务
user添加、删除和管理用户账户
get_url通过http、https或ftp下载文件
nmcli管理网络
uri与web服务交互

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

四、模块的使用

command模块

command模块允许管理员在受管主机上运行任意命令。

[root@client ansible]# ansible all -m command -a "mkdir ABC"	
[WARNING]: Consider using the file module with state=directory rather than running 'mkdir'.  If you need
to use command because file is insufficient you can add 'warn: false' to this command task or set
'command_warnings=False' in ansible.cfg to get rid of this message.
192.168.8.128 | CHANGED | rc=0 >>  #0表示成功

[root@server ~]# ls
ABC		anaconda-ks.cfg

user模块

user模块可以帮助我们管理远程主机上的用户,比如创建,修改和删除用户,为用户创建密钥等操作

常用的参数

  • name参数:用于指定要操作的用户名称
  • group参数:此参数用于指定用户所在的组
  • comment参数:此参数用于指定用户的注释信息
  • state参数:此参数用于指定用户是否存在于远程主机中,可选值有present、absent,默认为present,表示用户需要存在,当设置为absent时表示删除用户
  • remove参数:当state的值设置为absent时表示删除远程主机中的用户,但不会删除用户的家目录等信息,这是因为remove参数的默认值为no,如果设置为yes,在删除用户时会删除用户家目录
  • password参数:此参数用于指定用户密码。但这个密码不能是明文密码,而是一个加密后的字符串

创建用户

[root@client ansible]# ansible all -m user -a "name=yun"
192.168.8.128 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": true,
    "comment": "",
    "create_home": true,
    "group": 1002,
    "home": "/home/yun",
    "name": "yun",
    "shell": "/bin/bash",
    "state": "present",
    "system": false,
    "uid": 1002
}

删除用户

# 删除用户不删除其家目录
[root@client ansible]# ansible all -m user -a "name=ding state=absent"
192.168.8.128 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": true,
    "force": false,
    "name": "ding",
    "remove": false,
    "state": "absent"
}

# 删除用户及其家目录
[root@client ansible]# ansible all -m user -a "name=yun state=absent remove=yes"
192.168.8.128 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": true,
    "force": false,
    "name": "yun",
    "remove": true,
    "state": "absent"
}

修改用户组

[root@client ansible]# ansible all -m user -a "name=yun group=ding"
192.168.8.128 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "append": false,
    "changed": true,
    "comment": "",
    "group": 1001,
    "home": "/home/yun",
    "move_home": false,
    "name": "yun",
    "shell": "/bin/bash",
    "state": "present",
    "uid": 1002
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值