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的组件介绍)的更多相关文章

  1. Ansible自动化运维笔记1(安装配置)

    1.Ansible的安装 pip install ansible==1.9.1 ansible1.9.1版本依赖的软件有 Python2.6以上版本 paramiko模块 PyYAML Jinja2 ...

  2. Ansible自动化运维笔记3(playbook)

    1.基本语法 playbook文件格式为yaml语法.示例如下: 1.1 nginx.yaml --- - hosts: all tasks: - name: Install Nginx Packag ...

  3. ansible 自动化运维

    Ansible 自动化运维 ansible安装epel #yum list all *ansible*#yum install *ansible*#yum info ansible#rpm -ql a ...

  4. 自动化运维工具之ansible

    自动化运维工具之ansible   一,ansible简介 ansible是新出现的自动化运维工具,基于Python开发,集合了众多运维工具(puppet.cfengine.chef.func.fab ...

  5. 自动化运维工具之 Ansible 介绍及安装使用

    一.初识Ansible 介绍: Absible 使用 模块(Modules)来定义配置任务.模块可以用标准脚本语言(Python,Bash,Ruby,等等)编写,这是一个很好的做法,使每个模块幂等.A ...

  6. ansible自动化运维

    ansible 系统架构 ansible简介 ansible是新出现的自动化运维工具,ansible是一个配置管理和应用部署工具,基于Python开发,集合了众多运维工具(puppet.cfengin ...

  7. Ansible自动化运维工具-上

    [Ansible特点] 1)Ansible与saltstack均是基于Python语言开发的 2)安装使用简单,基于不同插件和模块实现各种软件,平台,版本的管理以及支持虚拟容器多层级的部署 3)不需要 ...

  8. Ansible 自动化运维工具

    Ansible 自动化运维工具 Ansible是什么? Ansible是一个"配置管理工具"也是一个"自动化运维工具" Ansible 作用: Ansible是 ...

  9. ansible自动化运维03

    ansible自动化运维常用模块 常用模块实现的功能:安装软件包:修改配置文件:创建程序用户组:创建目录,并修改所属和权限:挂载:启动服务:测试. command模块: shell模块: 注意:com ...

随机推荐

  1. 在eclispe的类中快速打出main方法

    在java类中快速打出main方法有两种途径: 1. 在新建类时,在New Java Class窗口中,将public static void main ( String[ ] args ) 前面打上 ...

  2. 布衣之路(一):VMware虚拟机+CentOS系统安装

    前言:布衣博主乃苦逼的Java程序猿一枚,虽然工作中不会涉及系统运维,但是开发的项目总还是要部署到服务器做一些负载均衡.系统兼容性测试.系统集成等等骚操作,而这些测试性的操作不可能直接SSH远程运维的 ...

  3. 权限问题导致zabbix无法监控mysql

    说说一个困扰自已两天的问题. 首先是用常规的方法安装上了mysql数据库.做了主从. 在监控从库的时候,发现所有的监控数据库的监控项都获取不到key值 . zabbix server端也不报错.获取到 ...

  4. 关系类型字段 -- Django从入门到精通系列教程

    该系列教程系个人原创,并完整发布在个人官网刘江的博客和教程 所有转载本文者,需在顶部显著位置注明原作者及www.liujiangblog.com官网地址. Python及Django学习QQ群:453 ...

  5. linux服务器配置pyspark解决py4j报错等问题

    1.下载spark,python包 略 2.环境变量配置 打开 ~/.bashrc配置文件 如图添加下列环境变量及path 3.退出配置文件,输入 source ~/.bashrc 来执行你添加的一些 ...

  6. 从jvm源码看synchronzied

    synchronized的使用 synchronized关键字是Java中解决并发问题的一种常用方法,也是最简单的一种方法,其作用有三个:(1)互斥性:确保线程互斥的访问同步代码(2)可见性:保证共享 ...

  7. 备忘:Junit单元测试

    junit 目前测试都是在main方法中调用目前的结果都需要人工对比是否是想要的 1.使用Junit测试方法,绿色条条代表方法测试成功,没有bug,如果是红色条条代表有异常,测试不通过2.点击方法名. ...

  8. c#结构体、打他table、excel、csv互转

    1.csv相关 public static class CsvHelper { /// <summary> /// 根据csv路径获取datatable /// </summary& ...

  9. Halcon一日一练:图像、变量实时更新

    某些场合,我们需要刷新图像来识别图像处理过程的差异性,便于调试判断问题和预测.Halcon提供了图像刷新操作,这些操作不会改变程序的最终处理结果. 例程: **实时刷新图像 dev_update_wi ...

  10. Go笔记-结构体

    [定义] type identifier struct{ field1 type1 field2 type2 ... } // 声明 var s identifier identifier.field ...