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 ...
随机推荐
- 【总目录】——概率论与数理统计及Python实现
注:这是一个横跨数年的任务,标题也可以叫做“从To Do List上划掉学习统计学”.在几年前为p值而苦恼的时候,还不知道Python是什么:后来接触过Python,就喜欢上了这门语言.统计作为数据科 ...
- .NET框架(转)
三年前写的<.NET之美>的第六章,现在书名改为了<.NET专题解析>. 本书是一本讲解.NET技术的书籍,目标读者群也是在.NET框架(.NET Framework)下进行开 ...
- fopen()函数参数
摘自百度百科.... 1."r" = "rt" 打开一个文本文件,文件必须存在,只允许读 2."r+" = "rt+&qu ...
- 论事件驱动与异步IO
通常我们写服务器模型,有以下几种模型: 每收到一个请求,创建一个新的进程,来处理该请求 每收到一个请求,创建一个新的线程,来处理该请求 每收到一个请求,放入到一个事件中,让主程序通过非阻塞I/0方式来 ...
- Spring基础篇——bean的自动化装配
上篇博文讲Spring的IOC容器时说道,虽然容器功能强大,但容器本身只是个空壳,需要我们主动放入装配对象,并告诉它对象之间的协作关系,然后容器才能按照我们的指示发挥它的魔力,完成装配bean的使命. ...
- NOIP 2017 day -1 杂记
我几乎要崩溃了. 写任何板子都是第一遍一定写不对,后来发现是傻逼性错误. 好奇怪的,这些东西明明我都会,为什么现在我都忘了? 很烦.现在心里特别乱,写什么都写不下去. 可能我是真的无法放心这次的比赛. ...
- php 处理并发问题
对于商品抢购等并发场景下,可能会出现超卖的现象,这时就需要解决并发所带来的这些问题了 在PHP语言中并没有原生的提供并发的解决方案,因此就需要借助其他方式来实现并发控制. 方案一:使用文件锁排它锁 f ...
- 6.C++初步分析类
面向对象的意义在于: -将日常生活中习惯的思维方式引入程序设计中 -将需求中的慨念直观的映射到解决方案中 -以模块为中心构建可复用的软件系统 -提高软件产品的可维护性和可扩展性 其中类和对象是面向对象 ...
- 重写equals()和hashCode()
什么时候需要重写equals()? 只有当一个实例等于它本身的时候,equals()才会返回true值.通俗地说,此时比较的是两个引用是否指向内存中的同一个对象,也可以称做是否实例相 等.而我们在使用 ...
- 017 Java中的静态代理、JDK动态代理、cglib动态代理
一.静态代理 代理模式是常用设计模式的一种,我们在软件设计时常用的代理一般是指静态代理,也就是在代码中显式指定的代理. 静态代理由业务实现类.业务代理类两部分组成.业务实现类负责实现主要的业务方法,业 ...

