Ansible自动化运维笔记2(Ansible的组件介绍)
1.Ansible Inventory##
(1)静态主机文件
默认的ansible invetory是/etc/hosts文件,可以通过ANSIBLE_HOSTS环境变量或者通过运行命令的时候加上-i
vim /tmp/hosts
# 定义组
[webservers]
10.187.11.34
10.187.137.191
# 组变量
[webservers:vars]
ansible_ssh_pass = '123456'
多个静态文件,可以写不同的文件里,文件名字hosts不是必须
inventory可以指向一个目录,这样目录里面所有的文件都会被加载进来,可以通过--list-hosts()来验证
[admin@host-10-187-196-225 hosts_file]$ ansible -i /tmp/hosts_file/ webservers --list-hosts
10.187.109.116
10.189.92.46
(2)动态主机文件
ansible.cfg配置文件中的inventory配置项指向一个脚本
这个脚本有一定规范和参数要求
1.支持--list或者-l,这个参数运行后会显示所有的主机以及主机组的信息(JSON格式)
2.支持--host或者-H,这个参数后面需要指定一个host,运行结果会返回这台主机的所有信息(包括认证信息,主机变量等),也是json格式
#!/usr/bin/env python
# -*- coding=utf-8 -*-
#########################
import argparse
import sys
import json
def lists():
r = dict()
h = ['172.17.42.10' + str(i) for i in range(1,4)]
hosts = {'hosts':h}
r['docker'] = hosts
return json.dumps(r,indent=4)
def hosts(name):
r = {'ansible_ssh_pass':'123456'}
cpis = dict(r.items())
return json.dumps(cpis,indent=4)
if __name__ == "__main__":
'''添加argparse的参数类实例,添加一些-l和-H的帮助显示提示'''
parser = argparse.ArgumentParser()
parser.add_argument('-l','--list',help='hosts list',action='store_true')
parser.add_argument('-H','--host',help='hosts vars')
'''vars方法把parser.parse_args()字典转换过去判断用户输入的内容'''
args = vars(parser.parse_args())
if args['list']:
print lists()
elif args['host']:
print hosts(args['host'])
else:
parser.print_help()
用实际主机来跑一批任务
ansible -i hosts.py docker -m ping -k
(3)主机文件支持的变量
ansible_ssh_host 定义host ssh地址
ansible_ssh_port 定义host ssh端口
ansible_ssh_user 定义hosts ssh认证用户
ansible_ssh_pass 定义hosts ssh 认证密码
ansible_sudo 定义hosts sudo用户
ansible_sudo_pass 定义hosts sudo密码
ansible_sudo_exe 定义hosts sudo 路径
ansible_connection 定义hosts连接方式
ansible_ssh_private_key_file 定义hosts私钥
ansible_shell_type 定义hosts shell类型
ansible_python_interpreter 定义hosts任务执行python路径
ansible_*_interpreter 定义hosts其他语言解析器路径
2.Ansible Ad-Hoc##
命令行方式使用ansible模块,使用ad-Hoc形式,插件功能无法使用,比如loop,facts功能
2.1命令模式(shell)###
1.普通同步模式等待后端返回结果的
ansible -i /tmp/hosts docker -m shell -a 'uptime'
2.异步模式,放后台,每隔几秒去看下任务状态,取回来数据
# -B 120 :把执行slee 10的任务放到后台120秒,超过120秒后就报超时了
# -P 2: 放到后台后,每隔2秒去远程主机上获取下任务状态,有返回取回数据,没返回,隔2秒后再去取一次结果,直到都取完后,任务完成
ansible -i /tmp/hosts docker -m shell -a 'sleep 10' -B 120 -P 2
异步原理:使用-P 参数后,会返回一个job_id,然后针对主机根据job_id去查询执行结果,每台主机产生不同的job_id,可以通过async_status模块查看异步任务的状态和结果,当-P 0的时候返回job_id就没了,后续操作需要自己去调用async_status模块取结果
如果-P 参数大于0,ansible会根据job_id去轮训查询执行结果
2.2.1复制文件(copy)###
ansible -i /tmp/hosts webservers -m copy -a 'src=/tmp/hosts dest=/tmp/ owner=admin group=admin mode=644 backup=yes'
其余帮助参数如下
[admin@host-10-187-196-225 tmp]$ ansible-doc -s copy
less 436
Copyright (C) 1984-2009 Mark Nudelman
less comes with NO WARRANTY, to the extent permitted by law.
For information about the terms of redistribution,
see the file named README in the less distribution.
Homepage: http://www.greenwoodsoftware.com/less
- name: C o p i e s f i l e s t o r e m o t e l o c a t i o n s .
action: copy
backup # Create a backup file including the timestamp information so you can get the original file back if you somehow clobbered it incorrectly.
content # When used instead of 'src', sets the contents of a file directly to the specified value.
dest= # Remote absolute path where the file should be copied to. If src is a directory, this must be a directory too.
directory_mode # When doing a recursive copy set the mode for the directories. If this is not set we will use the system defaults. The mode is only set on directories which ar
follow # This flag indicates that filesystem links, if they exist, should be followed.
force # the default is `yes', which will replace the remote file when contents are different than the source. If `no', the file will only be transferred if the desti
group # name of the group that should own the file/directory, as would be fed to `chown'
mode # mode the file or directory should be, such as 0644 as would be fed to `chmod'. As of version 1.8, the mode may be specified as a symbolic mode (for example, `
owner # name of the user that should own the file/directory, as would be fed to `chown'
selevel # level part of the SELinux file context. This is the MLS/MCS attribute, sometimes known as the `range'. `_default' feature works as for `seuser'.
serole # role part of SELinux file context, `_default' feature works as for `seuser'.
setype # type part of SELinux file context, `_default' feature works as for `seuser'.
seuser # user part of SELinux file context. Will default to system policy, if applicable. If set to `_default', it will use the `user' portion of the policy if availab
src # Local path to a file to copy to the remote server; can be absolute or relative. If path is a directory, it is copied recursively. In this case, if path ends w
validate # The validation command to run before copying into place. The path to the file to validate is passed in via '%s' which must be present as in the visudo exampl
2.2.2拽文件(fetch)###
把远程节点的/tmp/1.txt文件拽到本机/tmp/目录下,最后一定要/结尾,flat=yes代表的是直接以原文件名在/tmp/目录下命名创建
[admin@host-10-187-196-225 tmp]$ ansible -i 1 all -m fetch -a "src=/tmp/1.txt dest=/tmp/ flat=yes" -k
SSH password:
10.185.12.10 | success >> {
"changed": true,
"checksum": "52db334a166050298648cb3ba63336d9e9a9ac09",
"dest": "/tmp/1.txt",
"md5sum": "c41da816ae05a847b668da48bf8653d5",
"remote_checksum": "52db334a166050298648cb3ba63336d9e9a9ac09",
"remote_md5sum": null
}
其余帮助参数
[admin@host-10-187-196-225 tmp]$ ansible-doc -s fetch
less 436
Copyright (C) 1984-2009 Mark Nudelman
less comes with NO WARRANTY, to the extent permitted by law.
For information about the terms of redistribution,
see the file named README in the less distribution.
Homepage: http://www.greenwoodsoftware.com/less
- name: F e t c h e s a f i l e f r o m r e m o t e n o d e s
action: fetch
dest= # A directory to save the file into. For example, if the `dest' directory is `/backup' a `src' file named `/etc/profile' on host `host.example.com', would be sa
fail_on_missing # Makes it fails when the source file is missing.
flat # Allows you to override the default behavior of prepending hostname/path/to/file to the destination. If dest ends with '/', it will use the basename of the so
src= # The file on the remote system to fetch. This `must' be a file, not a directory. Recursive fetching may be supported in a later release.
validate_checksum # Verify that the source and destination checksums match after the files are fetched.
dest:用来存放文件的目录,例如存放目录为backup,源文件名称为/etc/profile在主机pythonserver中,那么保存为/backup/pythonserver/etc/profile
Fail_on_missing:当源文件不存在的时候,标识为失败
Flat:允许覆盖默认行为从hostname/path到/file的,如果dest以/结尾,它将使用源文件的基础名称
Src:在远程拉取的文件,并且必须是一个file,不能是目录
Validate_checksum:当文件fetch之后进行md5检查
2.3包管理(yum)###
ansible -i /tmp/hosts webservers -m yum -a 'name=mysql state=latest'
其余帮助文档
> YUM
Installs, upgrade, removes, and lists packages and groups with the
`yum' package manager.
Options (= is mandatory):
- conf_file
The remote yum configuration file to use for the transaction.
[Default: None]
- disable_gpg_check
Whether to disable the GPG checking of signatures of packages
being installed. Has an effect only if state is `present' or
`latest'. (Choices: yes, no) [Default: no]
- disablerepo
`Repoid' of repositories to disable for the install/update
operation. These repos will not persist beyond the
transaction. When specifying multiple repos, separate them
with a ",". [Default: None]
- enablerepo
`Repoid' of repositories to enable for the install/update
operation. These repos will not persist beyond the
transaction. When specifying multiple repos, separate them
with a ",". [Default: None]
- list
Various (non-idempotent) commands for usage with
`/usr/bin/ansible' and `not' playbooks. See examples.
[Default: None]
= name
Package name, or package specifier with version, like
`name-1.0'. When using state=latest, this can be '*' which
means run: yum -y update. You can also pass a url or a local
path to a rpm file. [Default: None]
- state
Whether to install (`present', `latest'), or remove (`absent')
a package. (Choices: present, latest, absent) [Default:
present]
= name
Package name, or package specifier with version, like
`name-1.0'. When using state=latest, this can be '*' which
means run: yum -y update. You can also pass a url or a local
path to a rpm file. [Default: None]
- state
Whether to install (`present', `latest'), or remove (`absent')
a package. (Choices: present, latest, absent) [Default:
present]
- update_cache
Force updating the cache. Has an effect only if state is
`present' or `latest'. (Choices: yes, no) [Default: no]
Requirements: yum
EXAMPLES:
- name: install the latest version of Apache
yum: name=httpd state=latest
- name: remove the Apache package
yum: name=httpd state=absent
- name: install the latest version of Apache from the testing repo
yum: name=httpd enablerepo=testing state=present
- name: install one specific version of Apache
yum: name=httpd-2.2.29-1.4.amzn1 state=present
- name: upgrade all packages
yum: name=* state=latest
- name: install the nginx rpm from a remote repo
yum: name=http://nginx.org/packages/centos/6/noarch/RPMS/nginx-release-centos-6-0.el6.ngx.noarch.rpm state=present
- name: install nginx rpm from a local file
yum: name=/usr/local/src/nginx-release-centos-6-0.el6.ngx.noarch.rpm state=present
- name: install the 'Development tools' package group
yum: name="@Development tools" state=present
2.4用户管理(user)###
ansible -i /tmp/hosts webservers -m user -a 'name=diaodiao password="123456"'
其余帮助文档
> USER
Manage user accounts and user attributes.
Options (= is mandatory):
- append
If `yes', will only add groups, not set them to just the list
in `groups'. (Choices: yes, no) [Default: no]
- comment
Optionally sets the description (aka `GECOS') of user account.
- createhome
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. (Choices: yes, no) [Default: yes]
- expires
An expiry time for the user in epoch, it will be ignored on
platforms that do not support this. Currently supported on
Linux and FreeBSD. [Default: None]
- force
When used with `state=absent', behavior is as with `userdel
--force'. (Choices: yes, no) [Default: no]
- generate_ssh_key
Whether to generate a SSH key for the user in question. This
will *not* overwrite an existing SSH key. (Choices: yes, no)
[Default: no]
- group
Optionally sets the user's primary group (takes a group name).
- groups
Puts the user in this comma-delimited list of groups. When set
to the empty string ('groups='), the user is removed from all
groups except the primary group.
- home
Optionally set the user's home directory.
- login_class
Optionally sets the user's login class for FreeBSD, OpenBSD
and NetBSD systems.
- move_home
If set to `yes' when used with `home=', attempt to move the
user's home directory to the specified directory if it isn't
there already. (Choices: yes, no) [Default: no]
= name
Name of the user to create, remove or modify.
- non_unique
Optionally when used with the -u option, this option allows to
change the user ID to a non-unique value. (Choices: yes, no)
[Default: no]
- password
Optionally set the user's password to this crypted value. See
the user example in the github examples directory for what
this looks like in a playbook. The `FAQ
<http://docs.ansible.com/faq.html#how-do-i-generate-crypted-
passwords-for-the-user-module>`_ contains details on various
ways to generate these password values. Note on Darwin system,
this value has to be cleartext. Beware of security issues.
- remove
When used with `state=absent', behavior is as with `userdel
--remove'. (Choices: yes, no) [Default: no]
- shell
Optionally set the user's shell.
- ssh_key_bits
Optionally specify number of bits in SSH key to create.
[Default: 2048]
- ssh_key_comment
Optionally define the comment for the SSH key. [Default:
ansible-generated on $HOSTNAME]
- ssh_key_file
Optionally specify the SSH key filename. If this is a relative
filename then it will be relative to the user's home
directory. [Default: .ssh/id_rsa]
- ssh_key_passphrase
Set a passphrase for the SSH key. If no passphrase is
provided, the SSH key will default to having no passphrase.
- ssh_key_type
Optionally specify the type of SSH key to generate. Available
SSH key types will depend on implementation present on target
host. [Default: rsa]
- state
Whether the account should exist or not, taking action if the
state is different from what is stated. (Choices: present,
absent) [Default: present]
- system
When creating an account, setting this to `yes' makes the user
a system account. This setting cannot be changed on existing
users. (Choices: yes, no) [Default: no]
- uid
Optionally sets the `UID' of the user.
- update_password
`always' will update passwords if they differ. `on_create'
will only set the password for newly created users. (Choices:
always, on_create) [Default: always]
Requirements: useradd, userdel, usermod
EXAMPLES:
# Add the user 'johnd' with a specific uid and a primary group of 'admin'
- user: name=johnd comment="John Doe" uid=1040 group=admin
# Add the user 'james' with a bash shell, appending the group 'admins' and 'developers' to the user's groups
- user: name=james shell=/bin/bash groups=admins,developers append=yes
# Remove the user 'johnd'
- user: name=johnd state=absent remove=yes
# Create a 2048-bit SSH key for user jsmith in ~jsmith/.ssh/id_rsa
# added a consultant whose account you want to expire
- user: name=james18 shell=/bin/zsh groups=developers expires=1422403387
3.Ansible facts##
facts组件呢是ansible用于采集被管理机器设备信息的一个功能,可以使用setup检查机器的所有facts信息,用filter来查看指定信息.返回一个大json
ansible -i /tmp/hosts webservers -m setup
Ansible自动化运维笔记2(Ansible的组件介绍)的更多相关文章
- Ansible自动化运维笔记1(安装配置)
1.Ansible的安装 pip install ansible==1.9.1 ansible1.9.1版本依赖的软件有 Python2.6以上版本 paramiko模块 PyYAML Jinja2 ...
- Ansible自动化运维笔记3(playbook)
1.基本语法 playbook文件格式为yaml语法.示例如下: 1.1 nginx.yaml --- - hosts: all tasks: - name: Install Nginx Packag ...
- ansible 自动化运维
Ansible 自动化运维 ansible安装epel #yum list all *ansible*#yum install *ansible*#yum info ansible#rpm -ql a ...
- 自动化运维工具之ansible
自动化运维工具之ansible 一,ansible简介 ansible是新出现的自动化运维工具,基于Python开发,集合了众多运维工具(puppet.cfengine.chef.func.fab ...
- 自动化运维工具之 Ansible 介绍及安装使用
一.初识Ansible 介绍: Absible 使用 模块(Modules)来定义配置任务.模块可以用标准脚本语言(Python,Bash,Ruby,等等)编写,这是一个很好的做法,使每个模块幂等.A ...
- ansible自动化运维
ansible 系统架构 ansible简介 ansible是新出现的自动化运维工具,ansible是一个配置管理和应用部署工具,基于Python开发,集合了众多运维工具(puppet.cfengin ...
- Ansible自动化运维工具-上
[Ansible特点] 1)Ansible与saltstack均是基于Python语言开发的 2)安装使用简单,基于不同插件和模块实现各种软件,平台,版本的管理以及支持虚拟容器多层级的部署 3)不需要 ...
- Ansible 自动化运维工具
Ansible 自动化运维工具 Ansible是什么? Ansible是一个"配置管理工具"也是一个"自动化运维工具" Ansible 作用: Ansible是 ...
- ansible自动化运维03
ansible自动化运维常用模块 常用模块实现的功能:安装软件包:修改配置文件:创建程序用户组:创建目录,并修改所属和权限:挂载:启动服务:测试. command模块: shell模块: 注意:com ...
随机推荐
- Java为什么需要保留基本数据类型
基本数据类型对以数值计算为主的应用程序来说是必不可少的. 自从1996年Java发布以来,基本数据类型就是Java语言的一部分.John Moore通过对使用基本类型和不使用基本类型做java基准测试 ...
- awk 指定{}内x的替换
替换{}中的x为; 原字符串 oxo{axbxc}oxo{dxexf}oxo 结果 oxo{a;b;c}oxo{d;e;f}oxo awk '{for(i=1;i<=NF;i++){ ...
- 【转】linux grep命令
1.作用 Linux系统中grep命令是一种强大的文本搜索工具,它能使用正则表达式搜索文本,并把匹配的行打印出来 2.格式 grep [options] 3.主要参数 [options]主要参数: - ...
- 通过 ['1', '2', '3'].map(parseInt) 学习 map 和 parseInt 函数
看到一道笔试题: ['1', '2', '3'].map(parseInt) 这道题目中涉及到 map 和 parseInt 函数的运用,如果对这两个函数的理解不充分的话,是很难思考出正确的结果的. ...
- Python selenium 一个节点两个关联input
HTML代码: 一个节点两个关联input 多出现于密码框 先需要模拟点击进入第一个input,才能激活第二个input. 代码: driver.find_element_by_name('Text ...
- Win7系统下彻底删除无用服务的方法
win7系统下中有非常多的服务项,用户来满足不同行业用户间的所有需求,系统服务也是执行指定系统功能的程序,许多情况下我们想要运行软件或执行外接设备都无法离开系统服务,但并非所有系统服务都是我们用到的, ...
- javascript中的Date对象和Math对象
1.Date对象 1.创建Date对象 var time1=new Date() 方法1:不指定参数 var time1=new Date(); alert(time1.toLocaleString( ...
- ABP官方文档翻译 10.1 ABP Nuget包
ABP Nuget包 Packages Abp Abp.AspNetCore Abp.Web.Common Abp.Web Abp.Web.Mvc Abp.Web.Api Abp.Web.Api.OD ...
- 《Python网络编程》学习笔记--从例子中收获的计算机网络相关知识
从之前笔记的四个程序中(http://www.cnblogs.com/take-fetter/p/8278864.html),我们可以看出分别使用了谷歌地理编码API(对URL表示地理信息查询和如何获 ...
- Hadoop学习笔记五
一.uber(u:ber)模式 MapReduce以Uber模式运行时,所有的map,reduce任务都在一个jvm中运行,对于小的mapreduce任务,uber模式的运行将更为高效. uber模式 ...