ansible部署

Ansible是一个基于Python的自动化工具,用于批量系统配置、程序部署和命令执行。它无需在远程节点安装客户端,依赖SSH并支持密钥认证进行免密登录。文章详细介绍了Ansible的架构、特点以及在三台Linux服务器上的安装和配置过程,包括生成密钥对、配置免密登录和使用Ansible执行命令。

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

ansible是什么

ansible是自动化运维工具,基于Python开发,集合了众多运维工具(puppet、cfengine、chef、func、fabric、saltstack)的优点,实现了批量系统配置、批量程序部署、批量运行命令等功能。

ansible架构

ansible组成

1.host inventory   主机清单 --》可以控制的其他的电脑的名单。

2.playbook   剧本(配置文件) --》让主机清单里的主机去批量完成的任务 --》脚本

3.module  模块  实现一个个功能的程序。

4.plugins  插件 :依附于ansible的一个小软件,实现某个小功能。

ansible特点

1.ansible不需要单独安装客户端,也不需要启动任何服务。

2.ansible是python中的一套完整的自动化执行任务模块。

3.ansible playbook 采用yaml配置,对于自动化任务执行过一目了然。

安装部署

准备3台linux服务器

ip系统主机名描述
192.168.102.135CentOS Linux release 7.6.1810ansiblemaster
192.168.102.139CentOS Linux release 7.6.1810web-2node
192.168.102.140CentOS Linux release 7.6.1810web-1node

一台做管理节点(安装 ansible),另外2台做远程节点(不需要安装ansible,但是需要安装openssh软件,默认情况下centos的系统都安装openssh)。

管理节点和远程节点之间需要配置免密通道。

配置无密码登录(基于密钥连接)

1.在ansible主机上生成密钥对

[root@ansible ~]# ssh-keygen -t ecdsa
Generating public/private ecdsa key pair.
Enter file in which to save the key (/root/.ssh/id_ecdsa): 
Created directory '/root/.ssh'.
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /root/.ssh/id_ecdsa.
Your public key has been saved in /root/.ssh/id_ecdsa.pub.
The key fingerprint is:
SHA256:JkGmVS3sb5gdH7YchnpxJTzm29Fq35hkxERIsOL4Th8 root@ansible
The key's randomart image is:
+---[ECDSA 256]---+
|      +o...+.o.  |
|     =  o ..* o  |
|    . .....+ * . |
|       +..+ B + .|
|      o S* O B o |
|       ++ = = *  |
|        ooE  + +.|
|       o . .  o o|
|        . .      |
+----[SHA256]-----+

[root@ansible ~]# cd /root/.ssh/
[root@ansible .ssh]# ls
id_ecdsa  id_ecdsa.pub

2.上传公钥到node1和node2节点服务器的root用户家目录下,同步到到两台node上    

2个节点服务器上开启ssh服务 ,开放22号端口,允许root用户登录,检查黑白名单是否拒绝登录,是否防火墙开启,进行了限制上传公钥到节点服务器。

[root@ansible .ssh]# ssh-copy-id -i id_ecdsa.pub root@192.168.102.139
/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "id_ecdsa.pub"
The authenticity of host '192.168.102.139 (192.168.102.139)' can't be established.
ECDSA key fingerprint is SHA256:GJLkvon/6JIxY0thYpMWcSIQBVdWFjwOZah+sPUmZ6E.
ECDSA key fingerprint is MD5:cb:bf:d9:ec:3d:33:6c:a4:5c:3c:e2:ce:b8:60:b8:33.
Are you sure you want to continue connecting (yes/no)? yes
/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/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.102.139's password: 

Number of key(s) added: 1

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

[root@ansible .ssh]# ssh-copy-id -i id_ecdsa.pub root@192.168.102.140
/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "id_ecdsa.pub"
The authenticity of host '192.168.102.140 (192.168.102.140)' can't be established.
ECDSA key fingerprint is SHA256:GJLkvon/6JIxY0thYpMWcSIQBVdWFjwOZah+sPUmZ6E.
ECDSA key fingerprint is MD5:cb:bf:d9:ec:3d:33:6c:a4:5c:3c:e2:ce:b8:60:b8:33.
Please type 'yes' or 'no': yes
/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/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.102.140's password: 

Number of key(s) added: 1

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

验证是否实现免密码密钥认证。

[root@ansible .ssh]# ssh root@192.168.102.139
Last login: Sun Apr  9 18:43:35 2023 from 192.168.102.1
[root@web-2 ~]# exit
登出
Connection to 192.168.102.139 closed.

[root@ansible .ssh]# ssh root@192.168.102.140
Last login: Sun Apr  9 18:43:36 2023 from 192.168.102.1
[root@web-1 ~]# 

3、安装ansible,在管理节点上

目前,只要机器上安装了 Python 2.6 或 Python 2.7 (windows系统不可以做控制主机),都可以运行Ansible。

[root@ansible .ssh]# yum install epel-release -y

[root@ansible .ssh]# yum  install ansible -y

查看ansible的帮助文档

[root@ansible .ssh]# ansible -h
usage: ansible [-h] [--version] [-v] [-b] [--become-method BECOME_METHOD]
               [--become-user BECOME_USER] [-K] [-i INVENTORY] [--list-hosts]
               [-l SUBSET] [-P POLL_INTERVAL] [-B SECONDS] [-o] [-t TREE] [-k]
               [--private-key PRIVATE_KEY_FILE] [-u REMOTE_USER]
               [-c CONNECTION] [-T TIMEOUT]
               [--ssh-common-args SSH_COMMON_ARGS]
               [--sftp-extra-args SFTP_EXTRA_ARGS]
               [--scp-extra-args SCP_EXTRA_ARGS]
               [--ssh-extra-args SSH_EXTRA_ARGS] [-C] [--syntax-check] [-D]
               [-e EXTRA_VARS] [--vault-id VAULT_IDS]
               [--ask-vault-pass | --vault-password-file VAULT_PASSWORD_FILES]
               [-f FORKS] [-M MODULE_PATH] [--playbook-dir BASEDIR]
               [-a MODULE_ARGS] [-m MODULE_NAME]
               pattern

Define and run a single task 'playbook' against a set of hosts

positional arguments:
  pattern               host pattern

optional arguments:
  --ask-vault-pass      ask for vault password
  --list-hosts          outputs a list of matching hosts; does not execute
                        anything else
  --playbook-dir BASEDIR
                        Since this tool does not use playbooks, use this as a
                        substitute playbook directory.This sets the relative
                        path for many features including roles/ group_vars/
                        etc.
  --syntax-check        perform a syntax check on the playbook, but do not
                        execute it
  --vault-id VAULT_IDS  the vault identity to use
  --vault-password-file VAULT_PASSWORD_FILES
                        vault password file
  --version             show program's version number, config file location,
                        configured module search path, module location,
                        executable location and exit
  -B SECONDS, --background SECONDS
                        run asynchronously, failing after X seconds
                        (default=N/A)
  -C, --check           don't make any changes; instead, try to predict some
                        of the changes that may occur
  -D, --diff            when changing (small) files and templates, show the
                        differences in those files; works great with --check
  -M MODULE_PATH, --module-path MODULE_PATH
                        prepend colon-separated path(s) to module library (def
                        ault=~/.ansible/plugins/modules:/usr/share/ansible/plu
                        gins/modules)
  -P POLL_INTERVAL, --poll POLL_INTERVAL
                        set the poll interval if using -B (default=15)
  -a MODULE_ARGS, --args MODULE_ARGS
                        module arguments
  -e EXTRA_VARS, --extra-vars EXTRA_VARS
                        set additional variables as key=value or YAML/JSON, if
                        filename prepend with @
  -f FORKS, --forks FORKS
                        specify number of parallel processes to use
                        (default=5)
  -h, --help            show this help message and exit
  -i INVENTORY, --inventory INVENTORY, --inventory-file INVENTORY
                        specify inventory host path or comma separated host
                        list. --inventory-file is deprecated
  -l SUBSET, --limit SUBSET
                        further limit selected hosts to an additional pattern
  -m MODULE_NAME, --module-name MODULE_NAME
                        module name to execute (default=command)
  -o, --one-line        condense output
  -t TREE, --tree TREE  log output to this directory
  -v, --verbose         verbose mode (-vvv for more, -vvvv to enable
                        connection debugging)

Privilege Escalation Options:
  control how and which user you become as on target hosts

  --become-method BECOME_METHOD
                        privilege escalation method to use (default=sudo), use
                        `ansible-doc -t become -l` to list valid choices.
  --become-user BECOME_USER
                        run operations as this user (default=root)
  -K, --ask-become-pass
                        ask for privilege escalation password
  -b, --become          run operations with become (does not imply password
                        prompting)

Connection Options:
  control as whom and how to connect to hosts

  --private-key PRIVATE_KEY_FILE, --key-file PRIVATE_KEY_FILE
                        use this file to authenticate the connection
  --scp-extra-args SCP_EXTRA_ARGS
                        specify extra arguments to pass to scp only (e.g. -l)
  --sftp-extra-args SFTP_EXTRA_ARGS
                        specify extra arguments to pass to sftp only (e.g. -f,
                        -l)
  --ssh-common-args SSH_COMMON_ARGS
                        specify common arguments to pass to sftp/scp/ssh (e.g.
                        ProxyCommand)
  --ssh-extra-args SSH_EXTRA_ARGS
                        specify extra arguments to pass to ssh only (e.g. -R)
  -T TIMEOUT, --timeout TIMEOUT
                        override the connection timeout in seconds
                        (default=10)
  -c CONNECTION, --connection CONNECTION
                        connection type to use (default=smart)
  -k, --ask-pass        ask for connection password
  -u REMOTE_USER, --user REMOTE_USER
                        connect as this user (default=None)

Some modules do not make sense in Ad-Hoc (include, meta, etc)

4.使用ansible

[root@ansible ~]# cd /etc/ansible
[root@ansible ansible]# ls
ansible.cfg  hosts  roles

[root@ansible ansible]# vim hosts
## 192.168.1.100
## 192.168.1.110
[web]
192.168.102.140
192.168.102.139

[root@ansible ansible]# ansible all -m shell -a "ip add"
192.168.102.139 | 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: ens33: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
    link/ether 00:0c:29:76:f7:50 brd ff:ff:ff:ff:ff:ff
    inet 192.168.102.139/24 brd 192.168.102.255 scope global noprefixroute dynamic ens33
       valid_lft 1764sec preferred_lft 1764sec
    inet6 fe80::cb26:250d:bed5:7336/64 scope link tentative noprefixroute dadfailed 
       valid_lft forever preferred_lft forever
    inet6 fe80::bbf5:76fa:b1b6:d5cd/64 scope link tentative noprefixroute dadfailed 
       valid_lft forever preferred_lft forever
    inet6 fe80::c722:692f:64d2:42e7/64 scope link noprefixroute 
       valid_lft forever preferred_lft forever
192.168.102.140 | 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: ens33: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
    link/ether 00:0c:29:82:3e:f1 brd ff:ff:ff:ff:ff:ff
    inet 192.168.102.140/24 brd 192.168.102.255 scope global noprefixroute dynamic ens33
       valid_lft 1688sec preferred_lft 1688sec
    inet6 fe80::cb26:250d:bed5:7336/64 scope link tentative noprefixroute dadfailed 
       valid_lft forever preferred_lft forever
    inet6 fe80::bbf5:76fa:b1b6:d5cd/64 scope link noprefixroute 
       valid_lft forever preferred_lft forever

[root@ansible ansible]# ansible all -m shell -a "mkdir /root/sc"
[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.102.139 | CHANGED | rc=0 >>

192.168.102.140 | CHANGED | rc=0 >>

[root@ansible ansible]# ansible all -m shell -a "ls /root/"
192.168.102.139 | CHANGED | rc=0 >>
anaconda-ks.cfg
sc
192.168.102.140 | CHANGED | rc=0 >>
anaconda-ks.cfg
sc

基于密码连接

[root@ansible ~]# vim /etc/ansible/hosts
[web]
192.168.102.140 ansible_ssh_port=22 ansible_ssh_user=root ansible_ssh_pass="123456"
192.168.102.139 ansible_ssh_port=22 ansible_ssh_user=root ansible_ssh_pass="123456"
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

韩未零

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值