Ansible部署

Ansible部署

一、Ansible主机清单

[root@hhr ~]# vim /etc/ansible/inventory 
192.168.129.250
192.168.129.135	//直接指明主机地址或主机名

[webservers]	//定义一个主机组[组名]把地址或主机名加进去
192.168.129.133
db-[1:5]-node.example.com

[hhr]
172.17.254.[1:6]	//组成员可以使用通配符来匹配,表示匹配从172.17.254.1——172.17.254.6的主机

效果如下:
[root@hhr ~]# ansible ungrouped --list-hosts
  hosts (1):
    192.168.129.250

[root@hhr ansible]# ansible hhr --list-hosts
  hosts (6):
    172.17.254.1
    172.17.254.2
    172.17.254.3
    172.17.254.4
    172.17.254.5
    172.17.254.6

[root@hhr ansible]# ansible webservers --list-hosts
  hosts (6):
    192.168.129.133
    db-1-node.example.com
    db-2-node.example.com
    db-3-node.example.com
  • 列出默认清单文件中的所有受管主机:
[root@hhr ~]# ansible all --list-hosts
  hosts (13):
    192.168.129.250
    192.168.129.133
    db-1-node.example.com
    db-2-node.example.com
    db-3-node.example.com
    db-4-node.example.com
    db-5-node.example.com
    172.17.254.1
    172.17.254.2
    172.17.254.3
    172.17.254.4
    172.17.254.5
    172.17.254.6
  • 列出不属于任何组的受管主机:
[root@hhr ~]# ansible ungrouped --list-hosts
  hosts (1):
    192.168.129.250
  • 列出属于某组的受管主机:
[root@hhr ~]# ansible webservers --list-hosts
  hosts (6):
    192.168.129.133
    db-1-node.example.com
    db-2-node.example.com
    db-3-node.example.com
    db-4-node.example.com
    db-5-node.example.com

二、管理Ansible配置文件

1、Ansible配置文件

More Actions配置文件或指令描述
/etc/ansible/ansible.cfg主配置文件
/etc/ansible/hosts主机清单
/usr/bin/ansible主程序,临时命令执行工具
/usr/bin/ansible主程序,临时命令执行工具
/usr/bin/ansible-doc查看配置文档,模块功能查看工具
/usr/bin/ansible-galaxy下载/上传代码或roles模块官网
/usr/bin/ansible-playbook定制自动化任务,编排剧本工具
/usr/bin/ansible-pull运程执行命令工具
/usr/bin/ansible-vault文件加密工具
/usr/bin/ansible-consoleconsole界面与用户执行的工具

2、默认配置文件信息

[root@hhr ansible]# cat ansible.cfg 
[defaults]                   #默认值
#inventory      = /etc/ansible/hosts      		#主机列表配置文件
#library        = /usr/share/my_modules/  		#库文件存放目录
#module_utils   = /usr/share/my_module_utils/ 	#模块应用程序路径
#remote_tmp     = ~/.ansible/tmp   				#临时py命令文件存放在远程主机目录
#local_tmp      = ~/.ansible/tmp   				#本机的临时命令执行目录
#plugin_filters_cfg = /etc/ansible/plugin_filters.yml #插件过滤器
#forks          = 5								#默认并发数	
#poll_interval  = 15							#查询间隔数
#sudo_user      = root      					#默认sudo用户
#ask_sudo_pass = True							#每次执行是否询问密码
#ask_pass      = True							#连接时提升输入ssh密码
#transport      = smart		
#remote_port    = 22							#远程默认端口 生产中可能会不同
#module_lang    = C			
#module_set_locale = False   					#模块设置区域默认为关闭

3、配置文件优先级

/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命令的目录中创建ansible.cfg文件。此目录中也将包含任何供Ansible项目使用的文件,如清单和playbook。这是用于Ansible配置文件的最常用位置。实践中不常使用~/.ansible.cfg或/etc/ansible/ansible.cfg文件

ANSIBLE_CONFIG(环境变量)

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

总结:

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

4、ansible命令详解

命令格式:
ansible <host-pattern> [-f forks] [-m module_name] [-a args]

本段中所有以“**”开头的参数,均表示是重要的
[root@hhr ~]# ansible -h
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	#输出ansible的版本
  -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	#要执行的模块的路径,默认为/usr/share/ansible/

-o, --one-line 
	condense output #压缩输出,摘要输出.尝试一切都在一行上输出。

-P POLL_INTERVAL, --poll=POLL_INTERVAL 	
	set the poll interval if using -B (default=15) #调查背景工作每隔数秒。

--private-key=PRIVATE_KEY_FILE 
	use this file to authenticate the connection #私钥路径,使用这个文件来验证连接

** -S, --su
	run operations with su #用 su 命令

** -R SU_USER, --su-user=SU_USER
	run operations with su as this user (default=root) #指定SU的用户,默认是root用户

** -s, --sudo
	run operations with sudo (nopasswd)

** -U SUDO_USER, --sudo-user=SUDO_USER
	desired sudo user (default=root)(deprecated, use become) #sudo到哪个用户,默认为 root

** -T TIMEOUT, --timeout=TIMEOUT
	override the SSH timeout in seconds (default=10) #指定SSH默认超时时间, 默认是10S

-t TREE, --tree=TREE 
	log output to this directory #将日志内容保存在该输出目录,结果保存在一个文件中在每台主机上。

** -u REMOTE_USER, --user=REMOTE_USER
	connect as this user (default=root) #远程用户, 默认是root用户 

--vault-password-file=VAULT_PASSWORD_FILE 
	vault password file

** -v, --verbose
	verbose mode (-vvv for more, -vvvv to enable 详细信息connection debugging)

--version 
	show program's version number and exit  #输出ansible的版本

5、ansible-doc命令详解

#一般用法:(也是常用的用法)
ansible-doc -l 				#获取模块信息
ansible-doc -s MOD_NAME 	#获取指定模块的使用帮助

#ansible-doc
[root@hhr ~]# ansible-doc  -h
usage: ansible-doc [-h] [--version] [-v] [-M MODULE_PATH]
                   [--playbook-dir BASEDIR]
                   [-t {become,cache,callback,cliconf,connection,httpapi,inventory,lookup,netconf,shell,module,strategy,vars}]
                   [-j] [-F | -l | -s | --metadata-dump]
                   [plugin [plugin ...]]
optional arguments:
  --metadata-dump       **For internal testing only** Dump json metadata for
                        all plugins.
  --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.
  --version             show program's version number, config file location,
                        configured module search path, module location,
                        executable location and exit	#显示ansible-doc的版本号查看模块
  -F, --list_files      Show plugin names and their source files without
                        summaries (implies --list)
  -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)	#指定模块的路径specify path(s) to module library (default=None)
  -h, --help            show this help message and exit	#显示命令参数API文档
  -j, --json            Change output into json format.
  -l, --list            List available plugins	#列出可用的模块
  -s, --snippet         Show playbook snippet for specified plugin(s)	#显示playbook制定模块的用法

6、ansible常用模块

1、ping模块:(使用免密登录)

1、	控制端:192.168.129.133
	受管端:192.168.129.250
	
2、生成一对密钥
[root@133 ~]# 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:zOVt6wwRLSiQr5E3Q6B0MJbvt8gkHsMERu3YKNGszvI root@133
The key's randomart image is:
+---[RSA 3072]----+
|.+*o+o           |
|o++=...  . .     |
|.+*. +. . + .    |
|oo.o+ =+ o +     |
|+o . + oS o o    |
|.o= + .    o .   |
|.o * o .  . .    |
|  E o .    +     |
|            o    |
+----[SHA256]-----+/

3、发送密钥到受管端
[root@133 ~]# ssh-copy-id root@192.168.129.250
/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.129.250's password: 

Number of key(s) added: 1

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


4、使用ssh-agent代理免密操作
[root@133 ~]# ssh-agent bash	#启动代理更新
[root@133 ~]# ssh-add
Enter passphrase for /root/.ssh/id_rsa: 
Identity added: /root/.ssh/id_rsa (root@133)
[root@133 ~]# ssh root@192.168.129.250
Last login: Thu Jul 15 21:52:21 2021 from 192.168.129.133
[root@hhr ~]# 	#不输入密码直接登录到受管主机界面了(重启生效)

效果如下:

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

2、command模块

  • action: command
  • chdir #在执行命令之前,先切换到该目录
  • creates #一个文件名,当这个文件存在,则该命令不执行,可以用来做判断
  • executable #切换shell来执行命令,需要使用命令的绝对路径
  • free_form #要执行的Linux指令,一般使用ansible的-a参数代替。
  • removes #一个文件名,这个文件不存在,则该命令不执行,与creates相反的判断
    效果如下:
[root@hhr ansible]# ansible localhost -m command -a 'ifconfig'
localhost | CHANGED | rc=0 >>
ens160: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 192.168.129.250  netmask 255.255.255.0  broadcast 192.168.129.255
        inet6 fe80::20c:29ff:fe20:9bda  prefixlen 64  scopeid 0x20<link>
        ether 00:0c:29:20:9b:da  txqueuelen 1000  (Ethernet)
        RX packets 392927  bytes 83244487 (79.3 MiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 601935  bytes 120595390 (115.0 MiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

lo: flags=73<UP,LOOPBACK,RUNNING>  mtu 65536
        inet 127.0.0.1  netmask 255.0.0.0
        inet6 ::1  prefixlen 128  scopeid 0x10<host>
        loop  txqueuelen 1000  (Local Loopback)
        RX packets 50  bytes 11618 (11.3 KiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 50  bytes 11618 (11.3 KiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

3、user模块管理

comment 			#用户的描述信息
createhome 			#是否创建家目录
force 				#在使用state=absent是, 行为与userdel –force一致.
group 				#指定基本组
groups 				#指定附加组,如果指定为(groups=)表示删除所有组
home 				#指定用户家目录
move_home 			#如果设置为home=时, 试图将用户主目录移动到指定的目录
name 				#指定用户名
non_unique 			#该选项允许改变非唯一的用户ID值
password 			#指定用户密码
remove 				#在使用state=absent时, 行为是与userdel –remove一致
shell 				#指定默认shell
state 				#设置帐号状态,不指定为创建,指定值为absent表示删除
system 				#当创建一个用户,设置这个用户是系统用户。这个设置不能更改现有用户
uid 				#指定用户的uid
update_password 	#更新用户密码

效果如下:
(1)创建一个用户,用户名为tom

[root@hhr ansible]# ansible localhost -m user -a "name=tom  state=present comment="致傻子""
localhost | CHANGED => {
    "changed": true,
    "comment": "致傻子",
    "create_home": true,
    "group": 1000,
    "home": "/home/tom",
    "name": "tom",
    "shell": "/bin/bash",
    "state": "present",
    "system": false,
    "uid": 1000
}

(2)修改tom用户的uid为1001

[root@hhr ansible]# ansible localhost -m user -a 'name=tom uid=1001' 
localhost | CHANGED => {
    "append": false,
    "changed": true,
    "comment": "致傻子",
    "group": 1000,
    "home": "/home/tom",
    "move_home": false,
    "name": "tom",
    "shell": "/bin/bash",
    "state": "present",
    "uid": 1001
}

(3)删除tom用户

[root@hhr ansible]# ansible localhost -m user -a 'name=tom state=absent'
localhost | CHANGED => {
    "changed": true,
    "force": false,
    "name": "tom",
    "remove": false,
    "state": "absent"
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值