自动化运维-Ansible(redhat 8)

在控制节点安装Ansible

redhat 8自带python 3;如果没有安装,需要自行安装

  • 查看是否安装python3
[root@localhost ~]# yum list installed|grep platform-python
模块依赖问题

 问题 1: conflicting requests
  - nothing provides module(perl:5.26) needed by module perl-DBD-SQLite:1.58:8010020190322125518:073fa5fe-0.x86_64
 问题 2: conflicting requests
  - nothing provides module(perl:5.26) needed by module perl-DBI:1.641:8010020190322130042:16b3ab4d-0.x86_64
platform-python.x86_64                             3.6.8-15.1.el8                                     @anaconda 
platform-python-coverage.x86_64                    4.5.1-7.el8                                        @AppStream
platform-python-pip.noarch                         9.0.3-15.el8                                       @anaconda 
platform-python-setuptools.noarch                  39.2.0-5.el8 
  • 关闭防火墙
[root@localhost ~]# systemctl disable --now firewalld
Removed /etc/systemd/system/multi-user.target.wants/firewalld.service.
Removed /etc/systemd/system/dbus-org.fedoraproject.FirewallD1.service.
  • 关闭selinux
[root@localhost ~]# setenforce 0
[root@localhost ~]# sed -i 's|enforcing|diabled|g' /etc/selinux/config
  • 更改主机名
[root@Ansibleconsole ~]# hostnamectl set-hostname Ansibleconsole
  • 安装网络源以及epel源
wget -O /etc/yum.repos.d/CentOS-Base.repo https://mirrors.aliyun.com/repo/Centos-8.repo
sed -i 's|$relesever|8|g' /etc/yum.repo.d/*
yum install -y https://mirrors.aliyun.com/epel/epel-release-latest-8.noarch.rpm
sed -i 's|^#baseurl=https://download.fedoraproject.org/pub|baseurl=https://mirrors.aliyun.com|' /etc/yum.repos.d/epel*
sed -i 's|^metalink|#metalink|' /etc/yum.repos.d/epel*
  • 安装ansible
yum install -y ansible
ansible --version
  • 查看当前版本
[root@Ansibleconsole yum.repos.d]# ansible --version
ansible 2.9.11
  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, Oct 11 2019, 15:04:54) [GCC 8.3.1 20190507 (Red Hat 8.3.1-4)]
#config file=ansible主配置文件绝对路径
#configure module search path=ansible相关配置模块存放路径
#ansible python module location=本地python模块路径
#executable location=ansible命令的绝对路径
  • 通过使用setup模块验证localhost上的ansible_python_version
[root@Ansibleconsole ~]# ansible -m setup localhost | grep ansible_python_version
        "ansible_python_version": "3.6.8",

部署Ansible

构建ansible清单

定义清单

  • 定义清单Ansible将要管理的一批主机。这些主机也可以分配到组中,以进行集中管理。组可以包含子
    组,主机也可以是多个组的成员。清单还可以设置应用到它所定义的主机和组的变量。
  • 可以通过两种方式定义主机清单。静态主机清单可以通过文本文件定义。动态主机清单可以根据需要使
    用外部信息提供程序通过脚本或其他程序来生成。

使用定义的静态清单指定受管理的主机

  • 静态清单文件是指定Ansible目标受管主机的文本文件。可以使用多种不同的格式编写此文件,包括INI
    样式或YAML。
  • 在最简单的形式中。INI样式的静态清单文件是受管主机的主机名或IP地址的列表,每行一个:
alpha.example.org
beta.example.org
192.168.1.100
[root@Ansibleconsole ~]# cd /etc/ansible/
[root@Ansibleconsole ansible]# ll
总用量 24
-rw-r--r--. 1 root root 19985 7月  21 20:33 ansible.cfg
-rw-r--r--. 1 root root  1016 7月  21 20:33 hosts
drwxr-xr-x. 2 root root     6 7月  21 20:33 roles
[root@Ansibleconsole ansible]# vim hosts

hosts文件解读:

  • 指定的主机既可以用IP地址表示又可以用域名表示
## green.example.com
## blue.example.com
## 192.168.100.1
## 192.168.100.10
  • 可以根据不同主机安装的服务类型划分成组
## [webservers]
## alpha.example.org
## beta.example.org
## 192.168.1.100
## 192.168.1.110
  • 可以用通配符指定多台主机
## ## www[001:006].example.com	这里意为:www.1.example.com到www.6.example.com的主机
## db-[99:101]-node.example.com 这里意为:db-99-node.example.com到db-101-node.example.com的主机

验证清单

[root@Ansibleconsole ansible]# ansible 192.168.72.4 --list-hosts
  hosts (1):
    192.168.72.4
  • 倘若主机地址不存在于hosts文件中
[root@Ansibleconsole ansible]# ansible 192.168.72.2 --list-hosts
[WARNING]: provided hosts list is empty, only localhost is available. Note that the implicit localhost does not match
'all'
[WARNING]: Could not match supplied host pattern, ignoring: 192.168.72.2
  hosts (0):
  • 检测清单组
[root@Ansibleconsole ansible]# ansible test --list-hosts
  hosts (3):
    192.168.72.4
    192.168.72.6
    192.168.72.8
  • 如果清单中含有名称相同的主机和主机组,ansible命令将显示警告并以主机作为其目标。主机组则被
    忽略。
  • 应对这种情况的方法有多种,其中最简单的是确保主机组不使用与清单中主机相同的名称。

覆盖清单位置

  • /etclansible/hosts文件被视为系统的默认静态清单文件。不过,通常的做法是不使用该文件,而是在
    Ansible配置文件中为清单文件定义一个不同的位置。
  • 通常情况下/etc/ansible/ansible.cfg将默认清单文件路径更改为自己建立的清单文件路径
[root@Ansibleconsole ansible]# vim ansible.cfg

在这里插入图片描述
再创建对应的文件

[root@Ansibleconsole ansible]# touch /etc/ansible/inventory

更改了ansible.cfg后原来hosts中的配置不再生效了;原因是新建的inventory文件是空的

[root@Ansibleconsole ansible]# ansible test --list-hosts
[WARNING]: provided hosts list is empty, only localhost is available. Note that the implicit localhost does not match
'all'
[WARNING]: Could not match supplied host pattern, ignoring: test
  hosts (0):

向inventory中写入IP地址
在这里插入图片描述
再次查看test清单组;由结果可知现在有效的清单文件为inventory

[root@Ansibleconsole ansible]# ansible test --list-hosts
  hosts (3):
    192.168.72.4
    192.168.72.6
    192.168.72.8
  • 查看没有加入到清单组的主机
[root@Ansibleconsole ansible]# ansible ungrouped --list-hosts
  hosts (2):
    172.11.10.2
    172.11.10.5

管理配置文件

ansible配置文件默认目录:/etc/ansible/ansible.cfg

[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
#plugin_filters_cfg = /etc/ansible/plugin_filters.yml
#forks          = 5
#poll_interval  = 15
#sudo_user      = root
#ask_sudo_pass = True
#ask_pass      = True
#transport      = smart
#remote_port    = 22
#module_lang    = C
#module_set_locale = False

[inventory] #清单文件配置
#enable inventory plugins, default: 'host_list', 'script', 'auto', 'yaml', 'ini', 'toml'		
enable_plugins = host_list, virtualbox, yaml, constructed		#允许使用插件;默认注释

#ignore these extensions when parsing a directory as inventory source
ignore_extensions = .pyc, .pyo, .swp, .bak, ~, .rpm, .md, .txt, ~, .orig, .ini, .cfg, .retry	#当目录解析为目录源时,忽略这些扩展;默认注释

#ignore files matching these patterns when parsing a directory as inventory source
ignore_patterns=			#当将目录解析为目录源时,忽略匹配这些模式的文件;默认注释

#If 'true' unparsed inventory sources become fatal errors, they are warnings otherwise.
unparsed_is_failed=False	#如果未解析的库存源的“true”成为致命错误,则它们是否则的警告;默认注释

[privilege_escalation]		#权限设置
become=True					#是否选用特权指定
become_method=sudo			#是否使用sudo
become_user=root			#是否使用Root用户指定
become_ask_pass=False		#登陆时是否需要输入密码

配置ansible

Ansible的配置文件是/etc/ansible/ansible.cfg

  • 可以通过修改Ansible配置文件中的设置来自定义Ansible安装的行为。Ansible从控制节点上多个可能
    的位置之一选择其配置文件。
    使用/etc/ansible/ansible.cfg
    ansible软件包提供一个基本的配置文件,它位于letc/ansible/ansible.cfg。如果找不到其他配置文件,则使用此文件。
    使用~/.ansible.cfg
    Ansible在用户的家目录中查找.ansible.cfg文件。如果存在此配置文件(~/ansible.cfg)并且当前工作目录中也没有ansible.cfg文件,则使用此配置取代/etc/ansible/ansible.cfg。
    使用./ansible.cfg
    如果执行ansible命令的目录中存在ansible.cfg文件,则使用它,而不使用全局文件或用户的个人文件。这样,管理员可以创建一种目录结构,将不同的环境或项目存储在单独的目录中,并且每个目录包含为一组独特的设置而制定的配置文件
    使用ANSIBLE_CONFIG环境变量
    我们可以通过将不同的配置文件放在不同的目录中,然后从适当的目录执行Ansible命令,以此利用配置文件。但是,随着配置文件数量的增加,这种方法存在局限性并且难以管理。有一个更加灵活的选项,即通过ANSIBLE_CONFIG环境变量定义配置文件的位置。定义了此变量时,Ansible将使用变量所指定的配置文件,而不用上面提到的任何配置文件。ansible.cfg文件,则使用此配置取代/etc/ansible/ansible.cfg。
    使用./ansible.cfg

配置文件优先级

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

由于Ansible配置文件可以放入的位置有多种,因此Ansible当前使用哪一个配置文件可能会令人困惑。我们可以运行以下命令来清楚地确认所安装的Ansible版本以及正在使用的配置文件。

ansible --version

Ansible仅使用具有最高优先级的配置文件中的设置。即使存在优先级较低的其他配置文件,其设置也会被忽略,不会与选定配置文件中的设置结合。因此,如果你选择自行创建配置文件来取代全局/etc/ansible/ansible.cfg配置文件,就需要将该文件中所有需要的设置复制到自己的用户级配置文件中。用户组配置文件中未定义的设置将保持设为内置默认值,即使已在全局配置文件中设为某个其他值也是如此。

管理配置文件中的设置

Ansible配置文件由几个部分组成,每一部分含有以键值对形式定义的设置。部分的标题以中括号括起来。对于基本操作,请使用以下两部分:

  • [defaults]部分设置Ansible操作的默认值
  • [privilege_escalation]配置Ansible如何在受管主机上执行特权升级
    例如,下面是典型的ansible.cfg文件:
[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
#plugin_filters_cfg = /etc/ansible/plugin_filters.yml
#forks          = 5
#poll_interval  = 15
#sudo_user      = root
#ask_sudo_pass = True
#ask_pass      = True
#transport      = smart
#remote_port    = 22
#module_lang    = C
#module_set_locale = False

Ansible配置

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

配置连接

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

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

清单位置

在[defaults]部分中,inventory指令可以直接指向某一静态清单文件,或者指向含有多个静态清单文件和动态清单脚本的某一目录。

[defaults]
inventory = ./inventory

连接设置

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

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

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

[defaults]
inventory = ./inventory

remote_user = root
ask_pass = true

假设在使用一个Linux控制节点,并对受管主机使用OpenSSH,如果可以使用密码以远程用户身份登录,那么我们可以设置基于SSH密钥的身份验证,从而能够设置ask_pass = false

第一步是确保在~/.ssh中为控制节点上的用户配置了SSH密钥对。并且使用ssh-copy-id命令将本地的公钥复制到受管主机中。此过程请参考文章openssh

升级特权

鉴于安全性和审计原因,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

使用公钥私钥建立连接

在控制节点执行

[root@ansible_control ~]# ssh-keygen
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:VnOs2jZMC+ZrhlJr4fpT2GzkQnJDo/ZxrNRZFiiZJBI root@ansible_control
The key's randomart image is:
+---[RSA 3072]----+
|  E....o ...     |
|   . .* . o.     |
|     o = +o o    |
|    + * *. +     |
|   . * @S o      |
|      B+** .     |
|     o Bo *      |
|    . * oo .     |
|    .=.+.        |
+----[SHA256]-----+
[root@ansible_control ~]# ssh-copy-id root@192.168.23.128			#ssh-copy-id 用户名@受控主机IP地址/域名
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
The authenticity of host '192.168.23.128 (192.168.23.128)' can't be established.
ECDSA key fingerprint is SHA256:vdTBLO1HN+1URrZjAQxoghxNzosGcdJNHPa596p5Hns.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes			#必须输入yes
/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.23.128's password: 

Number of key(s) added: 1

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

非SSH连接

默认情况下,Ansible用于连接受管主机的协议设置为smart,它会确定使用SHH的最高效方式。可以通过多种方式将其设置为其他的值。

例如,默认使用SSH的规则有一个例外。如果目录中没有localhost,Ansible将设置一个隐式localhost条目以便允许运行以localhost为目标的临时命令和playbook。这一特殊清单条目不包括在all或ungrouped主机组中。此外,Ansible不使用smart SSH连接类型,而是利用默认的特殊local连接类型来进行连接。

ansible localhost --list-hosts

local连接类型忽略remote_user设置,并且直接在本地系统上运行命令。如果使用特权升级,它会在运行sudo时使用运行Ansible命令的用户,而不是remote_user。如果这两个用户具有不同的sudo特权,这可能会导致混淆。

如果你要确保像其他受管主机一样使用SSH连接localhost,一种方法是在清单中列出它。但是,这会将它包含在all和ungrouped组中,而你可能不希望如此。

另一种方法是更改用于连接localhost的协议。执行此操作的最好方法是为localhost设置ansible_connection主机变量。为此,你需要在运行Ansible命令的目录中创建host_vars子目录。在该子目录中,创建名为localhost的文件,其应含有ansible_connection: smart这一行。这将确保对localhost使用smart(SSH)连接协议,而非local。

你也可以通过另一种变通办法来使用它。如果清单中列有127.0.0.1,则默认情况下,将会使用smart来连接它。也可以创建一个含有ansible_connection: local这一行的host_vars/127.0.0.1文件,它会改为使用local。

配置文件注释

Ansible配置文件允许使用两种注释字符:井号或分号。

位于行开头的#号会注释掉整行。它不能和指令位于同一行中。

分号字符可以注释掉所在行中其右侧的所有内容。它可以和指令位于同一行中,只要该指令在其左侧。

运行临时命令(ad-hoc command)

使用临时命令可以快速执行单个Ansible任务,不需要将它保存下来供以后再次运行。它们是简单的在线操作,无需编写playbook即可运行。

临时命令对快速测试和更改很有用。例如,可以使用临时命令确保一组服务器上的/etc/hosts文件中存在某一特定的行。可以使用另一个临时命令在许多不同的计算机上高效的重启服务,或者确保特定的软件包为最新版本。

临时命令对于通过Ansible快速执行简单的任务非常有用。它们确实也存在局限,而且总体而言,要使用Ansible Playbook来充分发挥Ansible的作用。但在许多情形中,临时命令正是快速执行简单任务所需要的工具。

运行临时命令

Ansible运行临时命令的语法如下:

ansible host-pattern -m module [-a 'module arguments'] [-i inventory]

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

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

一种最简单的临时命令使用ping模块。此模块不执行ICMP ping,而是检查能否在受管主机上运行基于Python的模块。例如,以下临时命令确定清单中的所有受管主机能否运行标准的模块:

[root@localhost ~]# ansible all -m ping
172.16.103.131 | SUCCESS => {
   
    "ansible_facts": {
   
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": false,
    "ping": "pong"
}
......
  • 测试Root用户登陆受管主机
    将受管主机IP加入清单文件
[root@Ansibleconsole ~]# echo '192.168.72.4' > /etc/ansible/inventory
[root@Ansibleconsole ~]# ansible all --list-hosts
  hosts (1):
    192.168.72.4

如果只在清单文件中加入受管主机IP地址,会导致访问拒绝

[root@Ansibleconsole ~]# ansible 192.168.72.4 -m ping
The authenticity of host '192.168.72.4 (192.168.72.4)' can't be established.
ECDSA key fingerprint is SHA256:jraKZY+BP5xdCBUFfRVnMPYz96iH3YzTfd83GcKVbuY.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
192.168.72.4 | UNREACHABLE! => {
    "changed": false,
    "msg": "Failed to connect to the host via ssh: Warning: Permanently added '192.168.72.4' (ECDSA) to the list of known hosts.\r\nroot@192.168.72.4: Permission denied (publickey,gssapi-keyex,gssapi-with-mic,password).",
    "unreachable": true
}
[root@Ansibleconsole ~]# ansible 192.168.72.4 -m ping
192.168.72.4 | UNREACHABLE! => {
    "changed": false,
    "msg": "Failed to connect to the host via ssh: root@192.168.72.4: Permission denied (publickey,gssapi-keyex,gssapi-with-mic,password).",
    "unreachable": true
}

必须在配置文件中加入ansible_password [root用户密码]

[root@Ansibleconsole ~]# tail /etc/ansible/inventory
192.168.72.4 ansible_password=123456

再次执行临时命令

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

Are you sure you want to continue connecting (yes/no/[fingerprint])? yes此前如果选择了yes后,在.ssh目录下会产生一个名为known_hosts的文件

[root@Ansibleconsole ~]# cat .ssh/known_hosts
192.168.72.4 ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBDs1cmocgeZHejJhAH2POpinjXx5yPaSZC/ik9ISqQREcq2ly/y8kE/y1kVSYEdKKB3pWUuItinNTksQB6KWLgQ=

此文件记录的是主机192.168.72.4的指纹信息

  • 测试普通用户登陆受管主机
    在清单文件中加入普通用户名和用户名密码
[root@Ansibleconsole ~]# tail -1 /etc/ansible/inventory
192.168.72.4 ansible_user=wcl ansible_password=123

执行临时命令

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

如果用域名访问,需要在清单文件中加入ansible_host参数(记得在本地主机的hosts文件中加入域名与IP地址的对应关系)

cn.4.com ansible_host=192.168.72.4 ansible_password=123456
[root@Ansibleconsole ~]# ansible all -m ping
cn.4.com | SUCCESS => {
   
    "ansible_facts": {
   
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": false,
    "ping": "pong"
}

运行成功

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

Ansible模块在线文档:https://docs.ansible.com/ansible/latest/modules/modules_by_category.html
模块是临时命令用于完成任务的工具。Ansible提供了数百个能够完成不同任务的模块。通常我们可以查找一个经过测试的专用模块,作为标准安装的一部分来完成所需的任务。

ansible-doc -l命令可以列出系统上安装的所有模块。可以使用ansible-doc来按照名称查看特定模块的帮助文档,再查找关于模块将取什么参数作为选项的信息。例如以下命令显示ping模块的帮助文档,在帮助文档里面输入q命令表示退出:

ansible-doc ping

更多的模块信息请访问在线Ansible文档,网址:https://docs.ansible.com/ansible/latest/modules/modules_by_category.html。

Ansible常用模块

模块类别 模块
文件模块 copy:将本地文件复制到受管主机 file:设置文件的权限和其他属性 lineinfile:确保特定行是否在文件中 synchronize:使用rsync同步内容
软件包模块 package:使用操作系统本机的自动检测软件包管理器管理软件包 yum:使用yum管理软件包 apt:使用APT管理软件包 dnf:使用dnf管理软件包 gem:管理Ruby gem pip:从PyPI管理Python软件包
系统模块 firewalld:使用firewalld管理防火墙 reboot:重启计算机 service:管理服务 user:添加、删除和管理用户帐户
Net Tools模块 get_url:通过HTTP、HTTPS或FTP下载文件 nmcli:管理网络 uri:与Web服务交互
  • 使用临时命令添加普通用户
[root@Ansibleconsole ~]# ansible all -m user -a 'name=wei uid=7777 state=present'	#删除用户则将present改为absent
192.168.72.4 | CHANGED => {
   
    "ansible_facts": {
   
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": true,
    "comment": "",
    "create_home": true,
    "group": 7777,
    "home": "/home/wei",
    "name": "wei",
    "shell": "/bin/bash",
    "state": "present",
    "system": false,
    "uid": 7777
}

受管主机查看普通用户

[root@AnsibleClient1 ~]# id wei
id: “wei”:无此用户
[root@AnsibleClient1 ~]# id wei
uid=7777(wei) gid=7777(wei)=7777(wei)
  • 通过控制节点给受管主机创建系统用户
[root@Ansibleconsole ~]# ansible cn.4.com -m user -a 'name=wcl system=yes create_home=false shell=/sbin/nologin state=present'
cn.4.com | CHANGED => {
   
    "ansible_facts": {
   
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "append": false,
    "changed": true,
    "comment": "",
    "group": 1000,
    "home": "/home/wcl",
    "move_home": false,
    "name": "wcl",
    "shell": "/sbin/nologin",
    "state": "present",
    "uid": 1000
}

创建成功

在受管主机上运行任意命令

  • 使用控制节点查看受管主机用户名
[root@Ansibleconsole ~]# ansible all -m command -a 'hostname'
192.168.72.4 | CHANGED | rc=0 >>
AnsibleClient1

这条命令为每个受管主机返回两行输出。第一行是状态报告,显示对其运行临时操作的受管主机名称及操作的结果。第二行是使用Ansible command模块远程执行的命令的输出。

若要改善临时命令输出的可读性和解析,管理员可能会发现使对受管主机执行的每一项操作具有单行输出十分有用。使用-o选项以单行格式显示Ansible临时命令的输出。

  • 使用控制节点查看网络连接
[root@Ansibleconsole ~]# ansible all -m command -a 'ip addr'
192.168.72.4 | CHANGED | rc=0 >>
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host
       valid_lft forever preferred_lft forever
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000
    link/ether 00:0c:29:77:28:45 brd ff:ff:ff:ff:ff:ff
    inet 192.168.72.4/24 brd 192.168.72.255 scope global noprefixroute eth0
       valid_lft forever preferred_lft forever
  • 通过控制节点给受管主机挂载光驱
[root@Ansibleconsole ~]# ansible all -m command -a 'mount /dev/sr0 /mnt'
[WARNING]: Consider using the mount module rather than running 'mount'.  If you need to use command because mount 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.72.4 | CHANGED | rc=0 >>
mount: /mnt: WARNING: device write-protected, mounted read-only.
#关于[WARNING]的警告消息可以通过
[root@Ansibleconsole ~]# ansible all -m command -a 'hostname' -o		#-o:单行显示
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值