- 准备工作
- 准备两台机器ansible-01,ansible-02
只需要在ansible-01上安装ansible,先安装epel仓库 - 两台机器关闭 防火墙和selinux
#配置两台机器的hosts文件- 安装ansible
- ansible远程执行命令
- ansible拷贝文件或者目录
- ansible远程执行脚本
- ansible管理任务计划
- ansible安装rpm包/管理服务
- ansible playbook的使用
- ansible playbook中的循环
- ansible playbook中的条件判断
- ansible playbook中的handlers
- playbook实战-Nginx安装1(环境准备)
- 可以提前把第二台机器的Nginx依赖也安装上
- playbook实战-Nginx安装2(文件编辑)
- 首先要把所有用到的文档拷贝到目标机器
4、建立一个拷贝文档的yml - playbook实战-Nginx安装3(执行)
- 管理配置文件
准备工作
准备两台机器ansible-01,ansible-02
只需要在ansible-01上安装ansible,先安装epel仓库
[root@ansible-01 ~]# yum install -y epel-release
两台机器关闭 防火墙和selinux
#配置两台机器的hosts文件
10.30.59.220 ansible-01
10.30.59.230 ansible-02
安装ansible
[root@ansible-01 ~]# yum install -y ansible
两台机器配置免密
[root@ansible-01 ~]# ssh-keygen -t rsa
[root@ansible-01 ~]# ssh-cope-id 10.30.59.230
Are you sure you want to continue connecting (yes/no)? yes
在ansible的hosts文件添加一个组
[root@ansible-01 ~]# vi /etc/ansible/hosts
[testhost]
127.0.0.1
10.30.59.230
在配置一个127.0.0.1的免密
[root@ansible-01 ~]# ssh-copy-id 127.0.0.1
ansible远程执行命令
ansible testhost -m command -a ‘hostname’
-m 后面用的是模块名字
-a 后面跟的是命令
远程执行命令可以是组也可以是对单个主机进行操作
#例子
[root@ansible-01 ~]# ansible 127.0.0.1 -m command -a 'hostname'
127.0.0.1 | CHANGED | rc=0 >>
ansible-01
[root@ansible-01 ~]# ansible 10.30.59.230 -m command -a 'hostname'
10.30.59.230 | CHANGED | rc=0 >>
ansible-02
[root@ansible-01 ~]# ansible testhost -m command -a 'hostname'
10.30.59.230 | CHANGED | rc=0 >>
ansible-02
127.0.0.1 | CHANGED | rc=0 >>
ansible-01
[root@ansible-01 ~]# ansible testhost -m shell -a 'hostname'
127.0.0.1 | CHANGED | rc=0 >>
ansible-01
10.30.59.230 | CHANGED | rc=0 >>
ansible-02
ansible拷贝文件或者目录
andible absible-02 -m copy -a “src=/etc/ansible dest=/tmp/ansibletest owner=root group=root mode=0755”
copy 拷贝文件或者目录的模块
src 源地址
dest 目的地址
owner 所属用户
group 所属组
mode 文件权限
源目录会放到目标目录下面去,如果目标指定的目录不存在,它会自动创建。
如果拷贝的是文件,dest指定的名字和源不同,并且它不是已存在的目录,相当于拷贝过去后又重命名。
[root@ansible-01 ~]# ansible 10.30.59.230 -m copy -a "src=test.txt dest=/tmp/123"
10.30.59.230 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"checksum": "c4f9375f9834b4e7f0a528cc65c055702bf5f24a",
"dest": "/tmp/123",
"gid": 0,
"group": "root",
"md5sum": "f447b20a7fcbf53a5d5be013ea0b15af",
"mode": "0644",
"owner": "root",
"secontext": "unconfined_u:object_r:admin_home_t:s0",
"size": 7,
"src": "/root/.ansible/tmp/ansible-tmp-1621387918.16-22883-133805763690663/source",
"state": "file",
"uid": 0
}
ansible远程执行脚本
首先创建一个shell脚本
[root@ansible-01 ~]# cat /tmp/test.sh
#!/bin/bash
echo `date` > /tmp/ansible_test.txt
然后把脚本发送到各个机器上
[root@ansible-01 ~]# ansible testhost -m copy -a "src=/tmp/test.sh dest=/tmp/test.sh mode=0755"
127.0.0.1 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"checksum": "1a6e4af02dba1bda6fc8e23031d4447efeba0ade",
"dest": "/tmp/test.sh",
"gid": 0,
"group": "root",
"mode": "0755",
"owner": "root",
"path": "/tmp/test.sh",
"secontext": "unconfined_u:object_r:user_tmp_t:s0",
"size": 48,
"state": "file",
"uid": 0
}
10.30.59.230 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"checksum": "1a6e4af02dba1bda6fc8e23031d4447efeba0ade",
"dest": "/tmp/test.sh",
"gid": 0,
"group": "root",
"md5sum": "edfaa4371316af8c5ba354e708fe8a97",
"mode": "0755",
"owner": "root",
"secontext": "unconfined_u:object_r:admin_home_t:s0",
"size": 48,
"src": "/root/.ansible/tmp/ansible-tmp-1621389757.94-23230-63542395933892/source",
"state": "file",
"uid": 0
}
最后是批量执行该shell脚本
[root@ansible-01 ~]# ansible testhost -m shell -a "/tmp/test.sh"
127.0.0.1 | CHANGED | rc=0 >>
10.30.59.230 | CHANGED | rc=0 >>
shell模块,还支持远程执行命令并且带管道
[root@ansible-01 ~]# ansible testhost -m shell -a "cat /etc/passwd|wc -l"
127.0.0.1 | CHANGED | rc=0 >>
33
10.30.59.230 | CHANGED | rc=0 >>
21
ansible管理任务计划
ansible testhost -m cron -a “nane=’test cron’ job=’/bin/touch /tmp/1212.txt’ weekday=6”
cron模块 管理任务计划
name 任务的名字
job 任务
若要删除该cron只需要加一个字段state=absent
ansible testhost -m cron -a “nane=’test cron’ state=absent”
其他的时间表示:分钟minute 小时hour 日期day 月份 mouth
#例子创建
[root@ansible-01 ~]# ansible testhost -m cron -a "name='test cron' job='/bin/touch /tmp/1212.txt' weekday=6"
10.30.59.230 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"envs": [],
"jobs": [
"test cron"
]
}
127.0.0.1 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"envs": [],
"jobs": [
"test cron"
]
}
#例子删除
[root@ansible-01 ~]# ansible testhost -m cron -a "name='test cron' state=absent"
127.0.0.1 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"envs": [],
"jobs": []
}
10.30.59.230 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"envs": [],
"jobs": []
}
ansible安装rpm包/管理服务
ansible testhost -m yum -a “name=httpd”
在name后面还可以加上state=installed/removed
andible testhost -m service -a “name=httpd state=started enabled=yes”
name是centos系统里的服务名可以通过chkconfig —list查到
#例子,给一个组的所有机器安装httpd服务
[root@ansible-01 ~]# ansible testhost -m yum -a "name=httpd"
127.0.0.1 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"msg": "",
"rc": 0,
"results": [
"httpd-2.4.6-97.el7.centos.x86_64 providing httpd is already installed"
]
}
10.30.59.230 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"changes": {
"installed": [
"httpd"
]
},
"msg": "",
"rc": 0,
"results": [
"Loaded plugins: fastestmirror\nLoading mirror speeds from cached hostfile\n * base: mirrors.163.com\n * extras: mirrors.163.com\n * updates: mirrors.163.com\nResolving Dependencies\n--> Running transaction check\n---> Package httpd.x86_64 0:2.4.6-97.el7.centos will be installed\n--> Processing Dependency: httpd-tools = 2.4.6-97.el7.centos for package: httpd-2.4.6-97.el7.centos.x86_64\n--> Processing Dependency: /etc/mime.types for package: httpd-2.4.6-97.el7.centos.x86_64\n--> Processing Dependency: libaprutil-1.so.0()(64bit) for package: httpd-2.4.6-97.el7.centos.x86_64\n--> Processing Dependency: libapr-1.so.0()(64bit) for package: httpd-2.4.6-97.el7.centos.x86_64\n--> Running transaction check\n---> Package apr.x86_64 0:1.4.8-7.el7 will be installed\n---> Package apr-util.x86_64 0:1.5.2-6.el7 will be installed\n---> Package httpd-tools.x86_64 0:2.4.6-97.el7.centos will be installed\n---> Package mailcap.noarch 0:2.1.41-2.el7 will be installed\n--> Finished Dependency Resolution\n\nDependencies Resolved\n\n================================================================================\n Package Arch Version Repository Size\n================================================================================\nInstalling:\n httpd x86_64 2.4.6-97.el7.centos updates 2.7 M\nInstalling for dependencies:\n apr x86_64 1.4.8-7.el7 base 104 k\n apr-util x86_64 1.5.2-6.el7 base 92 k\n httpd-tools x86_64 2.4.6-97.el7.centos updates 93 k\n mailcap noarch 2.1.41-2.el7 base 31 k\n\nTransaction Summary\n================================================================================\nInstall 1 Package (+4 Dependent packages)\n\nTotal download size: 3.0 M\nInstalled size: 10 M\nDownloading packages:\n--------------------------------------------------------------------------------\nTotal 7.2 MB/s | 3.0 MB 00:00 \nRunning transaction check\nRunning transaction test\nTransaction test succeeded\nRunning transaction\n Installing : apr-1.4.8-7.el7.x86_64 1/5 \n Installing : apr-util-1.5.2-6.el7.x86_64 2/5 \n Installing : httpd-tools-2.4.6-97.el7.centos.x86_64 3/5 \n Installing : mailcap-2.1.41-2.el7.noarch 4/5 \n Installing : httpd-2.4.6-97.el7.centos.x86_64 5/5 \n Verifying : httpd-2.4.6-97.el7.centos.x86_64 1/5 \n Verifying : apr-1.4.8-7.el7.x86_64 2/5 \n Verifying : mailcap-2.1.41-2.el7.noarch 3/5 \n Verifying : httpd-tools-2.4.6-97.el7.centos.x86_64 4/5 \n Verifying : apr-util-1.5.2-6.el7.x86_64 5/5 \n\nInstalled:\n httpd.x86_64 0:2.4.6-97.el7.centos \n\nDependency Installed:\n apr.x86_64 0:1.4.8-7.el7 apr-util.x86_64 0:1.5.2-6.el7 \n httpd-tools.x86_64 0:2.4.6-97.el7.centos mailcap.noarch 0:2.1.41-2.el7 \n\nComplete!\n"
]
}
#例子,管理一个组里所有机器的服务
[root@ansible-01 ~]# ansible testhost -m service -a "name=httpd state=started enabled=yes"
127.0.0.1 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"enabled": true,
"name": "httpd",
"state": "started",
"status": {
"ActiveEnterTimestamp": "四 2021-05-13 11:59:54 CST",
"ActiveEnterTimestampMonotonic": "154863259386",
"ActiveExitTimestampMonotonic": "0",
"ActiveState": "active",
"After": "-.mount basic.target systemd-journald.socket system.slice nss-lookup.target remote-fs.target network.target",
"AllowIsolate": "no",
"AssertResult": "yes",
"AssertTimestamp": "四 2021-05-13 11:59:54 CST",
"AssertTimestampMonotonic": "154863193726",
"Before": "shutdown.target",
"BlockIOAccounting": "no",
"BlockIOWeight": "18446744073709551615",
"CPUAccounting": "no",
"CPUQuotaPerSecUSec": "infinity",
"CPUSchedulingPolicy": "0",
"CPUSchedulingPriority": "0",
"CPUSchedulingResetOnFork": "no",
"CPUShares": "18446744073709551615",
"CanIsolate": "no",
"CanReload": "yes",
"CanStart": "yes",
"CanStop": "yes",
"CapabilityBoundingSet": "18446744073709551615",
"ConditionResult": "yes",
"ConditionTimestamp": "四 2021-05-13 11:59:54 CST",
"ConditionTimestampMonotonic": "154863193725",
"Conflicts": "shutdown.target",
"ControlGroup": "/system.slice/httpd.service",
"ControlPID": "0",
"DefaultDependencies": "yes",
"Delegate": "no",
"Description": "The Apache HTTP Server",
"DevicePolicy": "auto",
"Documentation": "man:httpd(8) man:apachectl(8)",
"EnvironmentFile": "/etc/sysconfig/httpd (ignore_errors=no)",
"ExecMainCode": "0",
"ExecMainExitTimestampMonotonic": "0",
"ExecMainPID": "13848",
"ExecMainStartTimestamp": "四 2021-05-13 11:59:54 CST",
"ExecMainStartTimestampMonotonic": "154863198187",
"ExecMainStatus": "0",
"ExecReload": "{ path=/usr/sbin/httpd ; argv[]=/usr/sbin/httpd $OPTIONS -k graceful ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }",
"ExecStart": "{ path=/usr/sbin/httpd ; argv[]=/usr/sbin/httpd $OPTIONS -DFOREGROUND ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }",
"ExecStop": "{ path=/bin/kill ; argv[]=/bin/kill -WINCH ${MAINPID} ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }",
"FailureAction": "none",
"FileDescriptorStoreMax": "0",
"FragmentPath": "/usr/lib/systemd/system/httpd.service",
"GuessMainPID": "yes",
"IOScheduling": "0",
"Id": "httpd.service",
"IgnoreOnIsolate": "no",
"IgnoreOnSnapshot": "no",
"IgnoreSIGPIPE": "yes",
"InactiveEnterTimestampMonotonic": "0",
"InactiveExitTimestamp": "四 2021-05-13 11:59:54 CST",
"InactiveExitTimestampMonotonic": "154863198261",
"JobTimeoutAction": "none",
"JobTimeoutUSec": "0",
"KillMode": "control-group",
"KillSignal": "18",
"LimitAS": "18446744073709551615",
"LimitCORE": "18446744073709551615",
"LimitCPU": "18446744073709551615",
"LimitDATA": "18446744073709551615",
"LimitFSIZE": "18446744073709551615",
"LimitLOCKS": "18446744073709551615",
"LimitMEMLOCK": "65536",
"LimitMSGQUEUE": "819200",
"LimitNICE": "0",
"LimitNOFILE": "4096",
"LimitNPROC": "23147",
"LimitRSS": "18446744073709551615",
"LimitRTPRIO": "0",
"LimitRTTIME": "18446744073709551615",
"LimitSIGPENDING": "23147",
"LimitSTACK": "18446744073709551615",
"LoadState": "loaded",
"MainPID": "13848",
"MemoryAccounting": "no",
"MemoryCurrent": "18446744073709551615",
"MemoryLimit": "18446744073709551615",
"MountFlags": "0",
"Names": "httpd.service",
"NeedDaemonReload": "no",
"Nice": "0",
"NoNewPrivileges": "no",
"NonBlocking": "no",
"NotifyAccess": "main",
"OOMScoreAdjust": "0",
"OnFailureJobMode": "replace",
"PermissionsStartOnly": "no",
"PrivateDevices": "no",
"PrivateNetwork": "no",
"PrivateTmp": "yes",
"ProtectHome": "no",
"ProtectSystem": "no",
"RefuseManualStart": "no",
"RefuseManualStop": "no",
"RemainAfterExit": "no",
"Requires": "basic.target -.mount",
"RequiresMountsFor": "/tmp /var/tmp",
"Restart": "no",
"RestartUSec": "100ms",
"Result": "success",
"RootDirectoryStartOnly": "no",
"RuntimeDirectoryMode": "0755",
"SameProcessGroup": "no",
"SecureBits": "0",
"SendSIGHUP": "no",
"SendSIGKILL": "yes",
"Slice": "system.slice",
"StandardError": "inherit",
"StandardInput": "null",
"StandardOutput": "journal",
"StartLimitAction": "none",
"StartLimitBurst": "5",
"StartLimitInterval": "10000000",
"StartupBlockIOWeight": "18446744073709551615",
"StartupCPUShares": "18446744073709551615",
"StatusErrno": "0",
"StatusText": "Total requests: 0; Current requests/sec: 0; Current traffic: 0 B/sec",
"StopWhenUnneeded": "no",
"SubState": "running",
"SyslogLevelPrefix": "yes",
"SyslogPriority": "30",
"SystemCallErrorNumber": "0",
"TTYReset": "no",
"TTYVHangup": "no",
"TTYVTDisallocate": "no",
"TimeoutStartUSec": "1min 30s",
"TimeoutStopUSec": "1min 30s",
"TimerSlackNSec": "50000",
"Transient": "no",
"Type": "notify",
"UMask": "0022",
"UnitFilePreset": "disabled",
"UnitFileState": "disabled",
"Wants": "system.slice",
"WatchdogTimestamp": "四 2021-05-13 11:59:54 CST",
"WatchdogTimestampMonotonic": "154863259297",
"WatchdogUSec": "0"
}
}
10.30.59.230 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"enabled": true,
"name": "httpd",
"state": "started",
"status": {
"ActiveEnterTimestampMonotonic": "0",
"ActiveExitTimestampMonotonic": "0",
"ActiveState": "inactive",
"After": "system.slice -.mount network.target basic.target nss-lookup.target remote-fs.target systemd-journald.socket",
"AllowIsolate": "no",
"AssertResult": "no",
"AssertTimestampMonotonic": "0",
"Before": "shutdown.target",
"BlockIOAccounting": "no",
"BlockIOWeight": "18446744073709551615",
"CPUAccounting": "no",
"CPUQuotaPerSecUSec": "infinity",
"CPUSchedulingPolicy": "0",
"CPUSchedulingPriority": "0",
"CPUSchedulingResetOnFork": "no",
"CPUShares": "18446744073709551615",
"CanIsolate": "no",
"CanReload": "yes",
"CanStart": "yes",
"CanStop": "yes",
"CapabilityBoundingSet": "18446744073709551615",
"ConditionResult": "no",
"ConditionTimestampMonotonic": "0",
"Conflicts": "shutdown.target",
"ControlPID": "0",
"DefaultDependencies": "yes",
"Delegate": "no",
"Description": "The Apache HTTP Server",
"DevicePolicy": "auto",
"Documentation": "man:httpd(8) man:apachectl(8)",
"EnvironmentFile": "/etc/sysconfig/httpd (ignore_errors=no)",
"ExecMainCode": "0",
"ExecMainExitTimestampMonotonic": "0",
"ExecMainPID": "0",
"ExecMainStartTimestampMonotonic": "0",
"ExecMainStatus": "0",
"ExecReload": "{ path=/usr/sbin/httpd ; argv[]=/usr/sbin/httpd $OPTIONS -k graceful ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }",
"ExecStart": "{ path=/usr/sbin/httpd ; argv[]=/usr/sbin/httpd $OPTIONS -DFOREGROUND ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }",
"ExecStop": "{ path=/bin/kill ; argv[]=/bin/kill -WINCH ${MAINPID} ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }",
"FailureAction": "none",
"FileDescriptorStoreMax": "0",
"FragmentPath": "/usr/lib/systemd/system/httpd.service",
"GuessMainPID": "yes",
"IOScheduling": "0",
"Id": "httpd.service",
"IgnoreOnIsolate": "no",
"IgnoreOnSnapshot": "no",
"IgnoreSIGPIPE": "yes",
"InactiveEnterTimestampMonotonic": "0",
"InactiveExitTimestampMonotonic": "0",
"JobTimeoutAction": "none",
"JobTimeoutUSec": "0",
"KillMode": "control-group",
"KillSignal": "18",
"LimitAS": "18446744073709551615",
"LimitCORE": "18446744073709551615",
"LimitCPU": "18446744073709551615",
"LimitDATA": "18446744073709551615",
"LimitFSIZE": "18446744073709551615",
"LimitLOCKS": "18446744073709551615",
"LimitMEMLOCK": "65536",
"LimitMSGQUEUE": "819200",
"LimitNICE": "0",
"LimitNOFILE": "4096",
"LimitNPROC": "23147",
"LimitRSS": "18446744073709551615",
"LimitRTPRIO": "0",
"LimitRTTIME": "18446744073709551615",
"LimitSIGPENDING": "23147",
"LimitSTACK": "18446744073709551615",
"LoadState": "loaded",
"MainPID": "0",
"MemoryAccounting": "no",
"MemoryCurrent": "18446744073709551615",
"MemoryLimit": "18446744073709551615",
"MountFlags": "0",
"Names": "httpd.service",
"NeedDaemonReload": "no",
"Nice": "0",
"NoNewPrivileges": "no",
"NonBlocking": "no",
"NotifyAccess": "main",
"OOMScoreAdjust": "0",
"OnFailureJobMode": "replace",
"PermissionsStartOnly": "no",
"PrivateDevices": "no",
"PrivateNetwork": "no",
"PrivateTmp": "yes",
"ProtectHome": "no",
"ProtectSystem": "no",
"RefuseManualStart": "no",
"RefuseManualStop": "no",
"RemainAfterExit": "no",
"Requires": "-.mount basic.target",
"RequiresMountsFor": "/tmp /var/tmp",
"Restart": "no",
"RestartUSec": "100ms",
"Result": "success",
"RootDirectoryStartOnly": "no",
"RuntimeDirectoryMode": "0755",
"SameProcessGroup": "no",
"SecureBits": "0",
"SendSIGHUP": "no",
"SendSIGKILL": "yes",
"Slice": "system.slice",
"StandardError": "inherit",
"StandardInput": "null",
"StandardOutput": "journal",
"StartLimitAction": "none",
"StartLimitBurst": "5",
"StartLimitInterval": "10000000",
"StartupBlockIOWeight": "18446744073709551615",
"StartupCPUShares": "18446744073709551615",
"StatusErrno": "0",
"StopWhenUnneeded": "no",
"SubState": "dead",
"SyslogLevelPrefix": "yes",
"SyslogPriority": "30",
"SystemCallErrorNumber": "0",
"TTYReset": "no",
"TTYVHangup": "no",
"TTYVTDisallocate": "no",
"TimeoutStartUSec": "1min 30s",
"TimeoutStopUSec": "1min 30s",
"TimerSlackNSec": "50000",
"Transient": "no",
"Type": "notify",
"UMask": "0022",
"UnitFilePreset": "disabled",
"UnitFileState": "disabled",
"Wants": "system.slice",
"WatchdogTimestampMonotonic": "0",
"WatchdogUSec": "0"
}
}
ansible文档的使用
absible-doc -l 列出所有的模块
ansible-doc cron 查看指定模块的文档
ansible playbook的使用
相当于把模块写入到配置文件里
第一行需要有三个杠
host 参数指定了对哪些主机进行操作
remote_user 指定用户
tasks 指定一个任务
name 对任务的描述
shell ansible模块名字
执行ansible-playbook test.yml
#例如
[root@ansible-01 tmp]# cat /etc/ansible/test.yml
---
- hosts: 10.30.59.230
remote_user: root
tasks:
- name: test_playbook
shell: touch /tmp/ansible_test.txt
#执行
[root@ansible-01 ~]# ansible-playbook /etc/ansible/test.yml
PLAY [10.30.59.230] **************************************************************
TASK [Gathering Facts] ***********************************************************
ok: [10.30.59.230]
TASK [test_playbook] *************************************************************
[WARNING]: Consider using the file module with state=touch rather than running
'touch'. If you need to use command because file is insufficient you can add
'warn: false' to this command task or set 'command_warnings=False' in ansible.cfg
to get rid of this message.
changed: [10.30.59.230]
PLAY RECAP ***********************************************************************
10.30.59.230 : ok=2 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
在举一个例子
#例子创建用户
[root@ansible-01 tmp]# cat /etc/ansible/create_user.yml
---
- name: create_user
hosts: 10.30.59.230
user: root
gather_facts: false
vars:
- user: "test"
tasks:
- name: create user
user: name="{{ user }}"
name参数对该playbook实现的功能做一个概述,后面执行过程中,会打印 name变量的值 ,可以省略;gather_facts参数指定了在以下任务部分执行前,是否先执行setup模块获取主机相关信息,这在后面的task会使用到setup获取的信息时用到;vars参数,指定了变量,这里指定一个user变量,其值为test ,需要注意的是,变量值一定要用引号引住;user提定了调用user模块,name是user模块里的一个参数,而增加的用户名字调用了上面user变量的值。
ansible playbook中的循环
编写一个循环的.yml文件
##with_items为循环的对象
[root@ansible-01 ansible]# cat while.yml
---
- hosts: testhost
user: root
tasks:
- name: change mode for files
file: path=/tmp/{{ item }} mode=600
with_items:
- 1.txt
- 2.txt
- 3.txt
ansible playbook中的条件判断
编写一个条件判断的.yml文件
##只有条件等于10.30.59.230的主机才会执行任务
##ansible 10.30.59.230 -m setup可以查看到所有的facter信息
[root@ansible-01 ansible]# cat when.yml
---
- hosts: testhost
user: root
gather_facts: True
tasks:
- name: use when
shell: touch /tmp/when.txt
when: ansible_eno16780032.ipv4.address == "10.30.59.230"
ansible playbook中的handlers
执行tasks之后,服务器发生变化之后要执行一些操作,比如我们修改了配置文件后,需要重启一下服务。
##notify 定义一个关键字当我们执行了tasks有了实质性的操作,就会激活notify调用handlers
##只有copy模块真正执行后,才会去调用下面的handlers相关的操作。也就是说如果1.txt和2.txt内容是一样的,并不会去执行handlers里面的shell相关命令
[root@ansible-01 ansible]# cat handlers.yml
---
- name: handlers test
hosts: 10.30.59.230
user: root
tasks:
- name: copy file
copy: src=/etc/passwd dest=/tmp/aaa.txt
notify: test handlers
handlers:
- name: test handlers
shell: echo "111111" >> /tmp/aaa.txt
playbook实战-Nginx安装1(环境准备)
思路:现在一台机器上编译安装好nginx、打包,然后再用ansible去下发
1、使用wget下载Nginx包,下载地址http://mirrors.sohu.com/nginx/nginx-1.9.6.tar.gz
[root@ansible-01 ~]# wget http://mirrors.sohu.com/nginx/nginx-1.9.6.tar.gz
2、解压Nginx安装包
[root@ansible-01 ~]# tar -zxvf nginx-1.9.6.tar.gz
3、安装Nginx所需要的依赖
[root@ansible-01 ~]# cd nginx-1.9.6
[root@ansible-01 nginx-1.9.6]# yum install gcc gcc-c++ pcre-devel zlib-devel openssl-devel -y
可以提前把第二台机器的Nginx依赖也安装上
[root@ansible-02 ~]# yum install gcc gcc-c++ pcre-devel zlib-devel openssl-devel -y
4、执行configure脚本
[root@ansible-01 nginx-1.9.6]# ./configure --prefix=/usr/local/nginx
5、编译安装Nginx
[root@ansible-01 nginx-1.9.6]# make && make install
6、检查脚本是否出问题
[root@ansible-01 nginx-1.9.6]# echo $?
0
7、编辑/etc/init.d/nginx配置文件
[root@ansible-01 nginx]# cat /etc/init.d/nginx
#!/bin/bash
# chkconfig: - 30 21
# description: http service.
# Source Function Library
. /etc/init.d/functions
# Nginx Settings
NGINX_SBIN="/usr/local/nginx/sbin/nginx"
NGINX_CONF="/usr/local/nginx/conf/nginx.conf"
NGINX_PID="/usx/local/nginx/logs/nginx.pid"
RETVAL=0
prog="Nginx"
start()
{
echo -n $"Starting $prog: "
mkdir -p /dev/shm/nginx_temp
daemon $NGINX_SBIN -c $NGINX_CONF
RETVAL=$?
echo
return $RETVAL
}
stop()
{
echo -n $"Stopping $prog: "
killproc -p $NGINX_PID $NGINX_SBIN -TERM
rm -rf /dev/shm/nginx_temp
RETVAL=$?
echo
return $RETVAL
}
reload()
{
echo -n $"Reloading $prog: "
killproc -p $NGINX_PID $NGINX_SBIN -HUP
RETVAL=$?
echo
return $RETVAL
}
restart()
{
stop
start
}
configtest()
{
$NGINX_SBIN -c $NGINX_CONF -t
return 0
}
case "$1" in
start)
start
;;
stop)
stop
;;
reload)
reload
;;
restart)
restart
;;
configtest)
configtest
;;
*)
echo $"Usage: $0 {start|stop|reload|restart|configtest}"
RETVAL=1
esac
exit $RETVAL
8、编写/usr/local/nginx/conf/nginx.conf配置文件
##首先清空这个文件
[root@ansible-01 nginx-1.9.6]# > /usr/local/nginx/conf/nginx.conf
##编辑配置文件
[root@ansible-01 nginx]# cat /usr/local/nginx/conf/nginx.conf
user nobody nobody;
worker_processes 2;
error_log /usr/local/nginx/logs/nginx_error.log crit;
pid /usr/local/nginx/logs/nginx.pid;
worker_rlimit_nofile 51200;
events
{
use epoll;
worker_connections 6000;
}
http
{
include mime.types;
default_type application/octet-stream;
server_names_hash_bucket_size 3526;
server_names_hash_max_size 4096;
log_format combined_realip '$remote_addr $http_x_forwarded_for [$time_local]'
'$host "$request_uri" $status'
'"$http_referer" "$http_user_agent"';
sendfile on;
tcp_nopush on;
keepalive_timeout 30;
client_header_timeout 3m;
client_body_timeout 3m;
send_timeout 3m;
connection_pool_size 256;
client_header_buffer_size 1k;
large_client_header_buffers 8 4k;
request_pool_size 4k;
output_buffers 4 32k;
postpone_output 1460;
client_max_body_size 10m;
client_body_buffer_size 256k;
client_body_temp_path /usr/local/nginx/client_body_temp;
proxy_temp_path /usr/local/nginx/proxy_temp;
fastcgi_temp_path /usr/local/nginx/fastcgi_temp;
fastcgi_intercept_errors on;
tcp_nodelay on;
gzip on;
gzip_min_length 1k;
gzip_buffers 4 8k;
gzip_comp_level 5;
gzip_http_version 1.1;
gzip_types text/plain application/x-javascript text/css text/htm
application/xml;
server
{
listen 80;
server_name localhost;
index index.html index.htm index.php;
root /usr/local/nginx/html;
location ~ \.php$
{
include fastcgi_params;
fastcgi_pass unix:/tmp/php-fcgi.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /usr/1ocal/nginx/html$fastcgi_script_name;
}
}
}
9、检查一下配置文件
[root@ansible-01 nginx-1.9.6]# /usr/local/nginx/sbin/nginx -t
10、启动Nginx
#给文件权限
[root@ansible-01 nginx-1.9.6]# chmod 777 /etc/init.d/nginx
#可能有人之前装过httpd会占用Nginx端口先关掉httpd
[root@ansible-01 nginx-1.9.6]# systemctl stop httpd
##启动nginx
[root@ansible-01 nginx-1.9.6]# service nginx start
nginx编译安装完成
##创建打包nginx的环境配置文件
roles目录下有两个角色,common为一些准备操作,install为安装nginx的操作。每个角色下面又有几个目录,handlers下面是当发生改变时要执行的操作,通常用在配置文件发生改变,重启服务。files为安装时用到的一些文件,meta为说明信息,说明角色依赖等信息,tasks里面是核心的配置文件,templates通常存一些配置文件,启动脚本等模板文件,vars下为定义的变量。
11、创建文件打包的目录
[root@ansible-01 ~]# mkdir -p /etc/ansible/nginx_install/
[root@ansible-01 ~]# cd /etc/ansible/nginx_install/
[root@ansible-01 nginx_install]# mkdir -p roles/{common,install}/{handlers,files,meta,tasks,templates,vars}
12、打包nginx的环境配置文件
[root@ansible-01 nginx]# cd /usr/local/
[root@ansible-01 local]# tar -zcvf nginx.tar.gz nginx/
[root@ansible-01 local]# mv nginx.tar.gz /etc/ansible/nginx_install/roles/install/files/
[root@ansible-01 local]# cd nginx
[root@ansible-01 nginx]# cp conf/nginx.conf /etc/ansible/nginx_install/roles/install/templates/
[root@ansible-01 nginx]# cp /etc/init.d/nginx /etc/ansible/nginx_install/roles/install/templates/
playbook实战-Nginx安装2(文件编辑)
1、关闭另外一台主机的80端口 给nginx腾位置
[root@ansible-02 ~]# systemctl stop httpd
2、建立一个yml安装依赖软件
[root@ansible-01 local]# vim /etc/ansible/nginx_install/roles/common/tasks/main.yml
- name: install initializtion requre software
yum: name={{ item }} state=installed
with_items:
- zlib-devel
- pcre-devel
3、定义变量
[root@ansible-01 local]# vim /etc/ansible/nginx_install/roles/install/vars/main.yml
nginx_user: www
nginx_port: 80
nginx_basedir: /usr/local/nginx
首先要把所有用到的文档拷贝到目标机器
4、建立一个拷贝文档的yml
[root@ansible-01 local]# vim /etc/ansible/ngix_install/roles/install/tasks/copy.yml
- name: Copy Nginx Software
copy: src=nginx.tar.gz dest=/tmp/nginx.tar.gz owner=root group=root
- name: Uncompression Nginx Software
shell: tar zxf /tmp/nginx.tar.gz -C /usr/local/
- name: Copy Nginx Start Script
template: src=nginx dest=/etc/init.d/nginx owner=root group=root mode=0755
- name: Copy Nginx Config
template: src=nginx.conf dest={{ nginx_basedir }}/conf/ owner=root group=root mode=0644
playbook实战-Nginx安装3(执行)
1、接下来会建立用户,启动服务,删除压缩包
[root@ansible-01 local]# vim /etc/ansible/nginx_install/roles/install/tasks/install.yml
- name: Creat Nginx User
user: name={{ nginx_user }} state=present createhome=no shell=/sbin/nologin
- name: Start Nginx Service
shell: /etc/init.d/nginx start
- name: Add Boot Start Nginx Service
shell: chkconfig --level 345 nginx on
- name: Delete Nginx compression files
shell: rm -rf /tmp/nginx.tar.gz
2、创建一个main.yml调用copy和install
[root@ansible-01 local]# vim /etc/ansible/nginx_install/roles/install/tasks/main.yml
- include: copy.yml
- include: install.yml
3、定义一个入口配置文件(启动文件)
[root@ansible-01 local]# vim /etc/ansible/nginx_install/install.yml
---
- hosts: 10.30.59.230
remote_user: root
gather_facts: True
roles:
- common
- install
4、执行启动文件完成nginx的安装
[root@ansible-01 local]# ansible-playbook /etc/ansible/nginx_install/install.yml
管理配置文件
生产环境中大多时候是需要管理配置文件的,安装软件包只是在初始化环境的时候用一下。下面我们来写个管理nginx配置文件的playbook
1、首先创建一个目录
[root@ansible-01 ~]# mkdir -p /etc/ansible/nginx_install/roles/{new,old}/{files,handlers,vars,tasks}
2、新建一个虚拟主机的目录
[root@ansible-01 ~]# cd /usr/local/nginx/conf/
[root@ansible-01 conf]# mkdir vhosts/
[root@ansible-01 conf]# cd vhosts/
[root@ansible-01 vhosts]# touch 1.conf
3、修改nginx.conf文件,两台主机都修改
[root@ansible-01 conf]# cat nginx.conf
user nobody nobody;
worker_processes 2;
error_log /usr/local/nginx/logs/nginx_error.log crit;
pid /usr/local/nginx/logs/nginx.pid;
worker_rlimit_nofile 51200;
events
{
use epoll;
worker_connections 6000;
}
http
{
include mime.types;
default_type application/octet-stream;
server_names_hash_bucket_size 3526;
server_names_hash_max_size 4096;
log_format combined_realip '$remote_addr $http_x_forwarded_for [$time_local]'
'$host "$request_uri" $status'
'"$http_referer" "$http_user_agent"';
sendfile on;
tcp_nopush on;
keepalive_timeout 30;
client_header_timeout 3m;
client_body_timeout 3m;
send_timeout 3m;
connection_pool_size 256;
client_header_buffer_size 1k;
large_client_header_buffers 8 4k;
request_pool_size 4k;
output_buffers 4 32k;
postpone_output 1460;
client_max_body_size 10m;
client_body_buffer_size 256k;
client_body_temp_path /usr/local/nginx/client_body_temp;
proxy_temp_path /usr/local/nginx/proxy_temp;
fastcgi_temp_path /usr/local/nginx/fastcgi_temp;
fastcgi_intercept_errors on;
tcp_nodelay on;
gzip on;
gzip_min_length 1k;
gzip_buffers 4 8k;
gzip_comp_level 5;
gzip_http_version 1.1;
gzip_types text/plain application/x-javascript text/css text/htm
application/xml;
server
{
listen 80;
server_name localhost;
index index.html index.htm index.php;
root /usr/local/nginx/html;
location ~ \.php$
{
include fastcgi_params;
fastcgi_pass unix:/tmp/php-fcgi.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /usr/1ocal/nginx/html$fastcgi_script_name;
}
}
include /usr/local/nginx/conf/vhosts/*.conf;
}
[root@ansible-02 ~]# cat /usr/local/nginx/conf/nginx.conf
user nobody nobody;
worker_processes 2;
error_log /usr/local/nginx/logs/nginx_error.log crit;
pid /usr/local/nginx/logs/nginx.pid;
worker_rlimit_nofile 51200;
events
{
use epoll;
worker_connections 6000;
}
http
{
include mime.types;
default_type application/octet-stream;
server_names_hash_bucket_size 3526;
server_names_hash_max_size 4096;
log_format combined_realip '$remote_addr $http_x_forwarded_for [$time_local]'
'$host "$request_uri" $status'
'"$http_referer" "$http_user_agent"';
sendfile on;
tcp_nopush on;
keepalive_timeout 30;
client_header_timeout 3m;
client_body_timeout 3m;
send_timeout 3m;
connection_pool_size 256;
client_header_buffer_size 1k;
large_client_header_buffers 8 4k;
request_pool_size 4k;
output_buffers 4 32k;
postpone_output 1460;
client_max_body_size 10m;
client_body_buffer_size 256k;
client_body_temp_path /usr/local/nginx/client_body_temp;
proxy_temp_path /usr/local/nginx/proxy_temp;
fastcgi_temp_path /usr/local/nginx/fastcgi_temp;
fastcgi_intercept_errors on;
tcp_nodelay on;
gzip on;
gzip_min_length 1k;
gzip_buffers 4 8k;
gzip_comp_level 5;
gzip_http_version 1.1;
gzip_types text/plain application/x-javascript text/css text/htm
application/xml;
server
{
listen 80;
server_name localhost;
index index.html index.htm index.php;
root /usr/local/nginx/html;
location ~ \.php$
{
include fastcgi_params;
fastcgi_pass unix:/tmp/php-fcgi.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /usr/1ocal/nginx/html$fastcgi_script_name;
}
}
include /usr/local/nginx/conf/vhosts/*.conf;
}
4、把配置文件和虚拟主机一起复制到files目录
[root@ansible-01 conf]# cp -r nginx.conf vhosts /etc/ansible/nginx_config/roles/new/files/
5、创建yml文件
[root@ansible-01 ~]# cd /etc/ansible/nginx_install/
##创建一个变量
[root@ansible-01 nginx_config]# vim roles/new/vars/main.yml
nginx_basedir: /user/local/nginx
##重启nginx服务的yml
[root@ansible-01 nginx_config]# vim roles//new/handlers/main.yml
- name: restart nginx
shell: /etc/init.d/nginx reload
##将nginx和虚拟主机复制的yml
[root@ansible-01 nginx_config]# vim roles/new/tasks/main.yml
- name: copy conf file
copy: src={{ item.src }} dest={{ nginx_basedir }}/{{ item.dest }} backup=yes owne
r=root group=root mode=0644
with_items:
- { src: nginx.conf, dest: conf/nginx.conf }
- { src: vhosts, dest: conf/ }
notify: restart nginx
##定义入口配置文件
[root@ansible-01 nginx_config]# vim /etc/ansible/nginx_config/update.yml
---
- hosts: testhost
user: root
roles:
- new
6、回滚backup.yml对应的roles为old
##回滚操作就是把旧的配置覆盖,然后重新加载nginx服务,每次改动nginx配置文件之前先备份到old里,对应的目录为/etc/ansible/nginx_config/roles/old/files
[root@ansible-01 nginx_config]# rsync -av /etc/ansible/nginx_config/roles/new/ /etc/ansible/nginx_config/roles/old/
7、定义一个回滚的总入口配置
[root@ansible-01 nginx_config]# vim /etc/ansible/nginx_config/rollback.yml
---
- hosts: testhost
user: root
roles:
- old
8、最后执行回滚的文件
[root@ansible-01 nginx_config]# ansible-playbook /etc/ansible/nginx_config/rollback.yml
##ansible到此为止就学习完毕了
**
