2872 words
14 minutes
Ansible安装及使用
前言
AnsibleWorks成立于2012年,由自动化工具Cobbler及Func的开发者Michael DeHaan创建。其Ansible平台是一个开源的配置及计算机管理平台。可实现多节点的软件部署,执行特定任务并进行配置管理。
Ansible 跟其他IT自动化技术的区别在于其关注点并非配置管理、应用部署或IT流程工作流,而是提供一个统一的界面来协调所有的IT自动化功能,因此 Ansible的系统更加易用,部署更快。受管理的节点无需安装额外的远程控制软件,由平台通过SSH(Secure SHell)对其进行管理,因此十分方便。其模块支持JSON等标准输出格式,可采用任何编程语言重写。
Ansible可以让用户避免编写脚本或代码来管理应用,同时还能搭建工作流实现IT任务的自动化执行。IT自动化可以降低技术门槛及对传统IT的依赖,从而加快项目的交付速度。
Ansible有如下优点:
- 轻量级,他不需要去客户端安装agent,更新时,只需要在操作机上进行一次更新即可
- 批量任务执行可以写成脚本,而且不用分发到远程就可以执行
- 使用python编写的,维护更简单
- 支持sudo
安装Ansible
创建ansible用户
[root@node1 ~]# useradd ansible[root@node1 ~]# passwd ansible更改用户 ansible 的密码 。新的 密码:重新输入新的 密码:passwd: 所有的身份验证令牌已经成功更新。允许执行sudo
[root@node1 ~]# vi /etc/sudoers# Defaults requiretty //表示不需要控制终端ansible ALL=(ALL) NOPASSWD:ALL安装ansible
[root@node1 ~]# yum install PyYAML.x86_64 python-paramiko.noarch python-jinja2.x86_64 python-devel -y[root@node1 ~]# wget https://pypi.python.org/packages/source/s/setuptools/setuptools-7.0.tar.gz[root@node1 ~]# tar zxvf setuptools-7.0.tar.gz[root@node1 ~]# cd setuptools-7.0[root@node1 setuptools-7.0]# python setup.py install[root@node1 setuptools-7.0]# cd ..[root@node1 ~]# wget https://pypi.python.org/packages/source/a/ansible/ansible-1.7.2.tar.gz[root@node1 ~]# tar zxvf ansible-1.7.2.tar.gz[root@node1 ~]# cd ansible-1.7.2[root@node1 ansible-1.7.2]# python setup.py build[root@node1 ansible-1.7.2]# python setup.py install[root@node1 ansible-1.7.2]# mkdir /etc/ansible[root@node1 ansible-1.7.2]# cp examples/ansible.cfg /etc/ansible/[root@node1 ansible-1.7.2]# cp examples/hosts /etc/ansible/修改配置文件
[root@node1 ansible-1.7.2]# vi /etc/ansible/ansible.cfghostfile = /etc/ansible/hostslibrary = /usr/share/ansibleremote_tmp = $HOME/.ansible/tmppattern = *forks = 5poll_interval = 15sudo_user = ansible#ask_sudo_pass = True#ask_pass = Truetransport = smartremote_port = 22module_lang = C[root@node1 ansible-1.7.2]# vi /etc/ansible/hosts#server[localhost]127.0.0.1#client[client]172.16.0.112ssh互信
[root@node1 ansible-1.7.2]# su - ansible[ansible@node1 ~]$[ansible@node1 ~]$ ssh-keygen -t rsaGenerating public/private rsa key pair.Enter file in which to save the key (/home/ansible/.ssh/id_rsa):Created directory '/home/ansible/.ssh'.Enter passphrase (empty for no passphrase):Enter same passphrase again:Your identification has been saved in /home/ansible/.ssh/id_rsa.Your public key has been saved in /home/ansible/.ssh/id_rsa.pub.The key fingerprint is:dc:c9:ac:d8:46:81:37:72:08:f3:77:06:98:33:cb:5f ansible@node1The key's randomart image is:+--[ RSA 2048]----+| o o. || +=o . || .=+* o || o* OE. || .S.= || +.. || . + || . || |+-----------------+[ansible@node1 ~]$[ansible@node1 ~]$ ssh-keygen -t dsaGenerating public/private dsa key pair.Enter file in which to save the key (/home/ansible/.ssh/id_dsa):Enter passphrase (empty for no passphrase):Enter same passphrase again:Your identification has been saved in /home/ansible/.ssh/id_dsa.Your public key has been saved in /home/ansible/.ssh/id_dsa.pub.The key fingerprint is:b3:a6:94:bf:5c:21:a3:c5:8b:74:b8:a5:8c:62:34:d2 ansible@node1The key's randomart image is:+--[ DSA 1024]----+| || || || . o ||. E o S . || o . + X * . || o . O + . || . . . = . || . +. |+-----------------+[ansible@node1 ~]$[ansible@node1 ~]$ cd .ssh/[ansible@node1 .ssh]$ cat *.pub > authorized_keys[ansible@node1 .ssh]$ chmod -R 700 .
#测试本机互信[ansible@node1 .ssh]$ ssh 127.0.0.1The authenticity of host '127.0.0.1 (127.0.0.1)' can't be established.RSA key fingerprint is fa:73:59:f5:08:95:b2:2e:7f:3e:52:91:8a:e6:47:1f.Are you sure you want to continue connecting (yes/no)? yesWarning: Permanently added '127.0.0.1' (RSA) to the list of known hosts.[ansible@node1 ~]$ exitlogoutConnection to 127.0.0.1 closed.远程ssh互信配置测试
[ansible@node1 .ssh]$ scp authorized_keys ansible@172.16.0.112:The authenticity of host '172.16.0.112 (172.16.0.112)' can't be established.RSA key fingerprint is fa:73:59:f5:08:95:b2:2e:7f:3e:52:91:8a:e6:47:1f.Are you sure you want to continue connecting (yes/no)? yesWarning: Permanently added '192.168.253.131' (RSA) to the list of known hosts.ansible@172.16.0.112's password:authorized_keys100% 998 1.0KB/s 00:00
#测试是否互信成功[ansible@node1 .ssh]$ ssh 172.16.0.112[ansible@node2 ~]$ mkdir .ssh[ansible@node2 ~]$ mv authorized_keys .ssh/[ansible@node2 ~]$ chmod -R 700 .ssh/使用Ansible
使用ping模块测试是否成功
[ansible@node1 ~]$ ansible all -m ping127.0.0.1 | success >> { "changed": false, "ping": "pong"}
172.16.0.112 | success >> { "changed": false, "ping": "pong"}查看时间
[ansible@node1 ~]$ ansible all -m command -a "sudo date"127.0.0.1 | success | rc=0 >>Fri Apr 22 23:48:42 CST 2016
172.16.0.112 | success | rc=0 >>Fri Apr 22 23:48:42 CST 2016使用yum安装软件
[ansible@node1 ~]$ ansible all -m command -a "sudo yum install zip unzip -y"127.0.0.1 | success | rc=0 >>Loaded plugins: fastestmirror, securityLoading mirror speeds from cached hostfile * base: mirrors.btte.net * extras: mirrors.yun-idc.com * updates: mirrors.yun-idc.comSetting up Install ProcessPackage zip-3.0-1.el6_7.1.x86_64 already installed and latest versionPackage unzip-6.0-2.el6_6.x86_64 already installed and latest versionNothing to do #说明此软件之前在每台服务器都已经装过了
172.16.0.112 | success | rc=0 >>Loaded plugins: fastestmirror, securityLoading mirror speeds from cached hostfile * base: mirrors.btte.net * extras: mirrors.yun-idc.com * updates: mirrors.yun-idc.comSetting up Install ProcessResolving Dependencies--> Running transaction check---> Package unzip.x86_64 0:6.0-2.el6_6 will be installed---> Package zip.x86_64 0:3.0-1.el6_7.1 will be installed--> Finished Dependency Resolution
Dependencies Resolved
================================================================================ Package Arch Version Repository Size================================================================================Installing: unzip x86_64 6.0-2.el6_6 base 149 k zip x86_64 3.0-1.el6_7.1 updates 259 k
Transaction Summary================================================================================Install 2 Package(s)
Total download size: 408 kInstalled size: 1.1 MDownloading Packages:--------------------------------------------------------------------------------Total 2.5 MB/s | 408 kB 00:00Running rpm_check_debugRunning Transaction TestTransaction Test SucceededRunning Transaction Installing : zip-3.0-1.el6_7.1.x86_64 1/2 Installing : unzip-6.0-2.el6_6.x86_64 2/2 Verifying : unzip-6.0-2.el6_6.x86_64 1/2 Verifying : zip-3.0-1.el6_7.1.x86_64 2/2
Installed: unzip.x86_64 0:6.0-2.el6_6 zip.x86_64 0:3.0-1.el6_7.1
Complete! #安装成功查看ansible内置模块
[ansible@node1 ~]$ ansible-doc -lacl Sets and retrieves file ACL information.add_host add a host (and alternatively a group) to the ansible-playboairbrake_deployment Notify airbrake about app deploymentsalternatives Manages alternative programs for common commandsapache2_module enables/disables a module of the Apache2 webserverapt Manages apt-packagesapt_key Add or remove an apt keyapt_repository Add and remove APT repositoriesapt_rpm apt_rpm package managerarista_interface Manage physical Ethernet interfacesarista_l2interface Manage layer 2 interfacesarista_lag Manage port channel (lag) interfacesarista_vlan Manage VLAN resourcesassemble Assembles a configuration file from fragmentsassert Fail with custom messageat Schedule the execution of a command or script file via the aauthorized_key Adds or removes an SSH authorized keyazure create or terminate a virtual machine in azurebigip_facts Collect facts from F5 BIG-IP devicesbigip_monitor_http Manages F5 BIG-IP LTM http monitorsbigip_monitor_tcp Manages F5 BIG-IP LTM tcp monitorsbigip_node Manages F5 BIG-IP LTM nodesbigip_pool Manages F5 BIG-IP LTM poolsbigip_pool_member Manages F5 BIG-IP LTM pool membersboundary_meter Manage boundary metersbzr Deploy software (or files) from bzr branchescampfire Send a message to Campfirecapabilities Manage Linux capabilitiescloudformation create a AWS CloudFormation stackcommand Executes a command on a remote nodecomposer Dependency Manager for PHPcopy Copies files to remote locations.cpanm Manages Perl library dependencies.cron Manage cron.d and crontab entries.datadog_event Posts events to DataDog servicedebconf Configure a .deb packagedebug Print statements during executiondigital_ocean Create/delete a droplet/SSH_key in DigitalOceandigital_ocean_domain Create/delete a DNS record in DigitalOceandigital_ocean_sshkey Create/delete an SSH key in DigitalOceandjango_manage Manages a Django application.dnsimple Interface with dnsimple.com (a DNS hosting service).dnsmadeeasy Interface with dnsmadeeasy.com (a DNS hosting service).docker manage docker containersdocker_image manage docker imageseasy_install Installs Python librariesec2 create, terminate, start or stop an instance in ec2, returnec2_ami create or destroy an image in ec2, return imageidec2_ami_search Retrieve AWS AMI for a given operating system.ec2_asg Create or delete AWS Autoscaling Groupsec2_eip associate an EC2 elastic IP with an instance.ec2_elb De-registers or registers instances from EC2 ELBsec2_elb_lb Creates or destroys Amazon ELB. - Returns information aboutec2_facts Gathers facts about remote hosts within ec2 (aws)ec2_group maintain an ec2 VPC security group.ec2_key maintain an ec2 key pair.ec2_lc Create or delete AWS Autoscaling Launch Configurationsec2_metric_alarm Create/update or delete AWS Cloudwatch 'metric alarms'ec2_scaling_policy Create or delete AWS scaling policies for Autoscaling groupsec2_snapshot creates a snapshot from an existing volumeec2_tag create and remove tag(s) to ec2 resources.ec2_vol create and attach a volume, return volume id and device map.ec2_vpc configure AWS virtual private cloudsejabberd_user Manages users for ejabberd serverselasticache Manage cache clusters in Amazon Elasticache.facter Runs the discovery program `facter' on the remote system...fail Fail with custom messagefetch Fetches a file from remote nodesfile Sets attributes of filesfilesystem Makes file system on block devicefireball Enable fireball mode on remote nodefirewalld Manage arbitrary ports/services with firewalldflowdock Send a message to a flowdockgc_storage This module manages objects/buckets in Google Cloud Storage.gce create or terminate GCE instancesgce_lb create/destroy GCE load-balancer resourcesgce_net create/destroy GCE networks and firewall rulesgce_pd utilize GCE persistent disk resourcesgem Manage Ruby gemsget_url Downloads files from HTTP, HTTPS, or FTP to nodegit Deploy software (or files) from git checkoutsgithub_hooks Manages github service hooks.glance_image Add/Delete images from glancegroup Add or remove groupsgroup_by Create Ansible groups based on factsgrove Sends a notification to a grove.io channelhg Manages Mercurial (hg) repositories.hipchat Send a message to hipchathomebrew Package manager for Homebrewhomebrew_cask Install/uninstall homebrew casks.homebrew_tap Tap a Homebrew repository.hostname Manage hostnamehtpasswd manage user files for basic authenticationinclude_vars Load variables from files, dynamically within a task.ini_file Tweak settings in INI filesirc Send a message to an IRC channeljabber Send a message to jabber user or chat roomjboss deploy applications to JBossjira create and modify issues in a JIRA instancekernel_blacklist Blacklist kernel moduleskeystone_user Manage OpenStack Identity (keystone) users, tenants and rolelayman Manage Gentoo overlayslibrato_annotation create an annotation in libratolineinfile Ensure a particular line is in a file, or replace an existinlinode create / delete / stop / restart an instance in Linode Publilldp get details reported by lldplocale_gen Creates of removes locales.logentries Module for tracking logs via logentries.comlvg Configure LVM volume groupslvol Configure LVM logical volumesmacports Package manager for MacPortsmail Send an emailmodprobe Add or remove kernel modulesmongodb_user Adds or removes a user from a MongoDB database.monit Manage the state of a program monitored via Monitmount Control active and configured mount pointsmqtt Publish a message on an MQTT topic for the IoTmysql_db Add or remove MySQL databases from a remote host.mysql_replication Manage MySQL replicationmysql_user Adds or removes a user from a MySQL database.mysql_variables Manage MySQL global variablesnagios Perform common tasks in Nagios related to downtime and notifnetscaler Manages Citrix NetScaler entitiesnewrelic_deployment Notify newrelic about app deploymentsnexmo Send a SMS via nexmonova_compute Create/Delete VMs from OpenStacknova_keypair Add/Delete key pair from novanpm Manage node.js packages with npmohai Returns inventory data from `Ohai'open_iscsi Manage iscsi targets with open-iscsiopenbsd_pkg Manage packages on OpenBSD.openvswitch_bridge Manage Open vSwitch bridgesopenvswitch_port Manage Open vSwitch portsopkg Package manager for OpenWrtosx_say Makes an OSX computer to speak.ovirt oVirt/RHEV platform managementpacman Manage packages with `pacman'pagerduty Create PagerDuty maintenance windowspause Pause playbook executionping Try to connect to host and return `pong' on success.pingdom Pause/unpause Pingdom alertspip Manages Python library dependencies.pkgin Package manager for SmartOSpkgng Package manager for FreeBSD >= 9.0pkgutil Manage CSW-Packages on Solarisportage Package manager for Gentooportinstall Installing packages from FreeBSD's ports systempostgresql_db Add or remove PostgreSQL databases from a remote host.postgresql_privs Grant or revoke privileges on PostgreSQL database objects...postgresql_user Adds or removes a users (roles) from a PostgreSQL database..quantum_floating_ip Add/Remove floating IP from an instancequantum_floating_ip_associate Associate or disassociate a particular floating IP with an iquantum_network Creates/Removes networks from OpenStackquantum_router Create or Remove router from openstackquantum_router_gateway set/unset a gateway interface for the router with the specifquantum_router_interface Attach/Dettach a subnet's interface to a routerquantum_subnet Add/Remove floating IP from an instancerabbitmq_parameter Adds or removes parameters to RabbitMQrabbitmq_plugin Adds or removes plugins to RabbitMQrabbitmq_policy Manage the state of policies in RabbitMQ.rabbitmq_user Adds or removes users to RabbitMQrabbitmq_vhost Manage the state of a virtual host in RabbitMQraw Executes a low-down and dirty SSH commandrax create / delete an instance in Rackspace Public Cloudrax_cbs Manipulate Rackspace Cloud Block Storage Volumesrax_cbs_attachments Manipulate Rackspace Cloud Block Storage Volume Attachments.rax_clb create / delete a load balancer in Rackspace Public Cloud...rax_clb_nodes add, modify and remove nodes from a Rackspace Cloud Load Balrax_dns Manage domains on Rackspace Cloud DNSrax_dns_record Manage DNS records on Rackspace Cloud DNSrax_facts Gather facts for Rackspace Cloud Serversrax_files Manipulate Rackspace Cloud Files Containersrax_files_objects Upload, download, and delete objects in Rackspace Cloud Filerax_identity Load Rackspace Cloud Identityrax_keypair Create a keypair for use with Rackspace Cloud Serversrax_meta Manipulate metadata for Rackspace Cloud Serversrax_network create / delete an isolated network in Rackspace Public Clourax_queue create / delete a queue in Rackspace Public Cloudrax_scaling_group Manipulate Rackspace Cloud Autoscale Groupsrax_scaling_policy Manipulate Rackspace Cloud Autoscale Scaling Policyrds create, delete, or modify an Amazon rds instancerds_param_group manage RDS parameter groupsrds_subnet_group manage RDS database subnet groupsredhat_subscription Manage Red Hat Network registration and subscriptions usingredis Various redis commands, slave and flushreplace Replace all instances of a particular string in a file usingrhn_channel Adds or removes Red Hat software channelsrhn_register Manage Red Hat Network registration using the `rhnreg_ks' coriak This module handles some common Riak operationsrollbar_deployment Notify Rollbar about app deploymentsroute53 add or delete entries in Amazons Route53 DNS servicerpm_key Adds or removes a gpg key from the rpm dbs3 idempotent S3 module putting a file into S3.script Runs a local script on a remote node after transferring it..seboolean Toggles SELinux booleans.selinux Change policy and state of SELinuxservice Manage services.set_fact Set host facts from a tasksetup Gathers facts about remote hostsshell Execute commands in nodes.slack Send Slack notificationsslurp Slurps a file from remote nodessns Send Amazon Simple Notification Service (SNS) messagesstackdriver Send code deploy and annotation events to stackdriverstat retrieve file or file system statussubversion Deploys a subversion repository.supervisorctl Manage the state of a program or group of programs running vsvr4pkg Manage Solaris SVR4 packagesswdepot Manage packages with swdepot package manager (HP-UX)synchronize Uses rsync to make synchronizing file paths in your playbooksysctl Manage entries in sysctl.conf.template Templates a file out to a remote server.twilio Sends a text message to a mobile phone through Twilio.typetalk Send a message to typetalkufw Manage firewall with UFWunarchive Copies an archive to a remote location and unpack ituri Interacts with webservicesurpmi Urpmi manageruser Manage user accountsvirt Manages virtual machines supported by libvirtvsphere_guest Create/delete/manage a guest VM through VMware vSphere.wait_for Waits for a condition before continuing.win_feature Installs and uninstalls Windows Featureswin_get_url Fetches a file from a given URLwin_group Add and remove local groupswin_msi Installs and uninstalls Windows MSI fileswin_ping A windows version of the classic ping module.win_service Manages Windows serviceswin_stat returns information about a Windows filewin_user Manages local Windows user accountsxattr set/retrieve extended attributesyum Manages packages with the `yum' package managerzfs Manage zfszypper Manage packages on SuSE and openSuSEzypper_repository Add and remove Zypper repositories