#hosts文件[webserver]192.168.203.[129:130][dbserver]192.168.203.131[appsrvs]192.168.203.[129:131][all_servers]dbserverwebserver#配置文件vim /etc/ansible/ansible.cfg# uncomment this to disable SSH key host checking 是否输入yeshost_key_checking = False#修改默认模块-配置文件module_name = shell#生成秘钥ssh-keygen -f /root/.ssh/id_rsa -P' 'ip=192.168.203for i in {129..131};dossh-copy-id $ip.$idone[root@dba project]# ansible all -i hosts --list-hostshosts (3):192.168.203.129192.168.203.130192.168.203.131#ansible 资产 -i hosts 模块 参数ansible all -m ping[root@dba ~]# ansible webserver --list-hostshosts (2):192.168.203.129192.168.203.130#差集[root@dba ~]# ansible 'web:&app' --list-hostshosts (2):192.168.203.129192.168.203.130#并集[root@dba ~]# ansible web:db --list-hostshosts (3):192.168.203.129192.168.203.130192.168.203.131查看模块帮助[root@dba ~]# ansible-doc -s command- name: Execute commands on targetscommand:argv: # Passes the command as a list rather than a string. Use `argv' to avoid quoting values that would otherwise be interpreted incorrectly (for example "username"). Only the string or the list form can be provided, not both. One or the other must be provided.chdir: # Change into this directory before running the command.cmd: # The command to run.creates: # A filename or (since 2.0) glob pattern. If it already exists, this step *won't* be run.free_form: # The command module takes a free form command to run. There is no actual parameter named 'free form'.removes: # A filename or (since 2.0) glob pattern. If it already exists, this step *will* be run.stdin: # Set the stdin of the command directly to the specified value.stdin_add_newline: # If set to `yes', append a newline to stdin data.strip_empty_ends: # Strip empty lines from the end of stdout/stderr in result.warn: # Enable or disable task warnings.---[root@dba ~]# ansible web -a 'cat /etc/centos-release'192.168.203.130 | CHANGED | rc=0 >>CentOS Linux release 7.9.2009 (Core)192.168.203.129 | CHANGED | rc=0 >>CentOS Linux release 7.9.2009 (Core)
===============command与shell的区别:shell支持管道符和内置命令
copy
[root@dba ~]# ansible web -m copy -a “src=./nginx.repo dest=/etc/yum.repos.d/nginx.repo”
ansible web -a ‘ls /etc/yum.repos.d’
模块
script
[root@dba project]# ansible db -i hosts -m script -a '/root/project/test.sh'
copy
ansible web -m copy -a "src=./nginx.repo dest=/etc/yum.repos.d/nginx.repo"ansible web -a 'ls /etc/yum.repos.d'ansible web -m copy -a "src=./nginx.repo dest=/etc/yum.repos.d/nginx.repo backup=yes"ansible web -m shell -a 'ls /etc/yum.repos.d|grep nginx'#备份-根据hash来判断文件是否需要备份 如果没有改变则不会备份[root@dba ~]# ansible web -m copy -a "src=./nginx.repo dest=/etc/yum.repos.d/nginx.repo backup=yes"192.168.203.129 | SUCCESS => {"ansible_facts": {"discovered_interpreter_python": "/usr/bin/python"},"changed": false,"checksum": "c62d148a221da3d7de0451794fe32d5b7df8df9e","dest": "/etc/yum.repos.d/nginx.repo","gid": 0,"group": "root","mode": "0644","owner": "root","path": "/etc/yum.repos.d/nginx.repo","size": 398,"state": "file","uid": 0}#对文件的权限和属主进行设置[root@dba ~]# ansible web -m copy -a "src=./nginx.repo dest=/etc/yum.repos.d/nginx.repo backup=yes owner=nobody group=nobody mode=755"192.168.203.131 | CHANGED => {"ansible_facts": {"discovered_interpreter_python": "/usr/bin/python"},"changed": true,"checksum": "c62d148a221da3d7de0451794fe32d5b7df8df9e","dest": "/etc/yum.repos.d/nginx.repo","gid": 0,"group": "root","md5sum": "094165ee4178bb13167ff8980091fa12","mode": "0755","owner": "nobody",#1.拷贝文件文件至被控节点[root@m01 ~]# ansible oldboy -m copy -a "src=/etc/hosts dest=/tmp/test.txt"#2.对远端已有文件进行备份,按照时间信息备份[root@m01 ~]# ansible oldboy -m copy -a "src=/etc/hosts dest=/tmp/test.txt backup=yes"#3.向被控端主机写入数据,并且会覆盖远端文件内原有数据信息[root@m01 ~]# ansible oldboy -m copy -a "content='bgx' dest=/tmp/oldboy"src #推送数据的源文件信息dest #推送数据的目标路径backup #对推送传输过去的文件,进行备份content #直接批量在被管理端文件中添加内容group #将本地文件推送到远端,指定文件属组信息owner #将本地文件推送到远端,指定文件属主信息mode #将本地文件推送到远端,指定文件权限信息
yum_repository
- 一般直接拷贝
gpgcheck yes/no
enable
- name: Add multiple repositories into the same file (1/2)yum_repository:name: epeldescription: EPEL YUM repofile: external_reposbaseurl: https://download.fedoraproject.org/pub/epel/$releasever/$basearch/gpgcheck: noenabled: yes
[root@dba project]# ansible web -i hosts -m yum_repository -a "name=epel baseurl='http://mirrors.aliyun.com/repo/epel-7.repo' description='epel'"
yum
- present 确认安装但是不升级
- installed确认安装
- latest安装并升级
- absent、removed移除
#安装[root@dba project]# ansible db -i hosts -m yum -a "name=htop state=present"#删除[root@dba project]# ansible db -i hosts -m yum -a "name=htop state=absent"
systemd
- daemon_reload
- enabled
- name
- state started stopped restarted reloaded
#服务重启[root@dba project]# ansible db -i hosts -m systemd -a "name=sshd state=restarted"ansible管理服务的启动与停止,使用service、systemd#1.启动crond服务,并加入开机自启[root@m01 ~]# ansible webservers -m service -a "name=crond state=started enabled=yes"#2.停止crond服务,并删除开机自启[root@m01 ~]# ansible webservers -m service -a "name=crond state=stopped enabled=no"#3.重启crond服务[root@m01 ~]# ansible webservers -m service -a "name=crond state=restarted"#4.重载crond服务[root@m01 ~]# ansible webservers -m service -a "name=crond state=reloaded"name # 定义要启动服务的名称state # 指定服务状态started #启动服务stopped #停止服务restarted #重启服务reloaded #重载服务enabled #开机自启
group 模块
ansible db -i hosts -m group -a "name=db_admin"
user
创建用户添加到组
[root@dba project]# ansible db -i hosts -m user -a "user=foo group=db_admin append=yes"
删除
[root@dba project]# ansible db -i hosts -m user -a "user=foo group=db_admin state=absent"
file
- touch
- sbaent
- directory
- file
创建文件
[root@dba project]# ansible db -i hosts -m file -a "path=/tmp/file.sh state=touch"[root@dba project]# ansible db -i hosts -m file -a "path=/tmp/file.sh owner=nobody group=nobodymode=644"#连接的目录必须存在[root@dba project]# ansible db -i hosts -m file -a "src=/tmp/file.v1.sh dest=/tmp/file.sh state=link"192.168.203.131 | FAILED! => {"ansible_facts": {"discovered_interpreter_python": "/usr/bin/python"},"changed": false,"gid": 0,"group": "root","mode": "0644","msg": "src file does not exist, use \"force=yes\" if you really want to create the link: /tmp/file.v1.sh",#- name: Create two hard linksfile:src: '/tmp/{{ item.src }}'dest: '{{ item.dest }}'state: hardloop:- { src: x, dest: y }- { src: z, dest: k }1.直接修改被控端的权限[root@m01 ~]# ansible web01 -m file -a "path=/opt mode=0400" -i ./hosts2.在被控端创建目录[root@m01 ~]# ansible oldboy -m file -a "path=/tmp/oldboy state=directory"3.在被控端创建文件[root@m01 ~]# ansible oldboy -m file -a "path=/tmp/tt state=touch mode=555 owner=root group=root"4.递归授权目录权限[root@m01 ~]# ansible oldboy -m file -a "path=/data owner=bgx group=bgx recurse=yes"path #指定远程主机目录或文件recurse #递归授权state #状态directory #在远端创建目录touch #在远端创建文件link #创建链接文件absent #表示删除文件或目录mode #设置文件或目录权限owner #设置文件或目录属主group #设置文件或目录属组
cron
//新建一个任务
[root@dba project]# ansible db -i hosts -m cron -a "name='new job' minute='0' job='ls -alh>/dev/null'"[root@ansible3 tmp]# crontab -l#Ansible: new job0 * * * * ls -alh>/dev/null[root@dba project]# ansible db -i hosts -m cron -a "name='new job' state=absent"[root@dba project]# ansible db -m cron -a 'hour=2 minute=30 weekday=1-5 name="backup mysql" job=/root/mysql_bak.sh'[root@ansible3 tmp]# crontab -l#Ansible: backup mysql30 2 * * 1-5 /root/mysql_bak.sh#禁用执行计划ansible db -m cron -a 'hour=2 minute=30 weekday=1-5 name="backup mysql" job=/root/mysql_bak.sh disabled=yes'
debug
[root@dba project]# ansible db -i hosts -m debug -a "msg='haha'"192.168.203.131 | SUCCESS => {"msg": "haha"}
template
[root@dba project]# cat hello_world.j2hello {{var}} ![root@dba project]# ansible db -i hosts -m template -a "src=hello_world.j2 dest=/tmp/j2.txt" -e "var=2021"
unarchive
ansible db -m unarchive -a "src=/root/project/pro.tar.gz dest=/tmp "
lineinfile
<br />
mount
[root@m01 ~]# ansible web01 -m yum -a ‘name=nfs-utils state=present’ -i ./hosts
[root@m01 ~]# ansible web01 -m file -a ‘path=/data state=directory’ -i ./hosts
[root@m01 ~]# ansible web01 -m copy -a ‘content=”/data 172.16.1.0/24(rw,sync,no_all_squash)” dest=/etc/exports’ -i ./hosts
[root@m01 ~]# ansible web01 -m systemd -a “name=nfs state=started enabled=yes” -i ./hosts
[root@m01 ~]# ansible web02 -m mount -a “src=172.16.1.7:/data path=/data fstype=nfs opts=defaults state=present”
[root@m01 ~]# ansible web02 -m mount -a “src=172.16.1.7:/data path=/data fstype=nfs opts=defaults state=mounted”
[root@m01 ~]# ansible web02 -m mount -a “src=172.16.1.7:/data path=/data fstype=nfs opts=defaults state=unmounted”
[root@m01 ~]# ansible web02 -m mount -a “src=172.16.1.7:/data path=/data fstype=nfs opts=defaults state=absent”
present # 开机挂载,仅将挂载配置写入/etc/fstab
mounted # 挂载设备,并将配置写入/etc/fstab
unmounted # 卸载设备,不会清除/etc/fstab写入的配置
absent # 卸载设备,会清理/etc/fstab写入的配置
playbook
- hosts
- tasks 任务集
- variables
- Templates
- Hadnders和notify
- tags
[root@dba project]# cat nginx.yaml- hosts: webremote_user: rootgather_facts: notasks:- name: nginx installyum: name=nginx state=present- name: htmlcopy: src=index.html dest=/usr/share/nginx/html/index.html- name: start nginxservice: name=nginx state=started enabled=yes
安装httpd
- hosts: webtasks:- name: Installed Httpd Serveryum: name=httpd state=present- name: Start Httpd Serversystemd: name=httpd state=started enabled=yes- hosts: web01tasks:- name: Configure web01 Websitecopy: content='This is Web01' dest=/var/www/html/index.html- hosts: web02tasks:- name: Cofnigure webi-2 weisitecopy: content='This is Web02' dest=/var/www/html/index.html
安装nfs
#模板文件vim exports.j2/data 192.168.203.0/24(rw,sync,all_squash,anonuid=666,anongid=666)#服务端#1.安装nfs#2.配置挂载目录#创建目录 创建用户#3.启动加入自启#客户端#准备目录#启动rpcbind-安装nfs-utils#挂载共享目录- hosts: dbremote_user: rootgather_facts: notasks:- name: install nfsyum: name=nfs-utils state=present- name: config nfscopy: src=./exports.j2 dest=/etc/exports backup=yes- name: nfs groupgroup: name=www gid=666- name: nfs useruser: name=www uid=666 group=666 shell=/sbin/nologin create_home=no- name: nfs datafile: path=/data state=directory owner=www group=www recurse=yes- name: service startservice: name=nfs state=started enabled=yes- hosts: webgather_facts: notasks:- name: client datafile: path=/nfs_tt state=directory- name: client mountmount:src: 192.168.203.131:/datapath: /nfs_ttfstype: nfsopts: defaultsstate: mounted
变量的定义和使用
组变量
#vars[root@dba project]# cat dp.yaml- hosts: webvars:- webpkgs: httpd- ftppkgs: vsftpdtasks:- name: install {{ webpkgs }} {{ ftppkgs }} rpmyum:name:- "{{ webpkgs }}"- "{{ ftppkgs }}"state: present# 变量文件[root@dba project]# cat vars_pub.yamlwebpkgs: httpdftppkgs: vsftpd#cat vars2.yaml- hosts: webvars_files: ./vars_pub.yamltasks:- name: install rpmyum:name:- "{{ webpkgs }}"- "{{ ftppkgs }}"state: present新建#group_vars目录与主机清单的组名保持一致[root@dba project]# tree group_vars/group_vars/└── web.yaml#只对web组生效,与主机的组一致[root@dba project]# cat group_vars/web.yamlwebpkgs: wgetftppkgs: tree#对所有组都生效[root@dba project]# cat group_vars/allmlwebpkgs: wgetftppkgs: tree#系统提供了一个特殊组all 只需要在vars下建立all的文件变好变量,所以组都能使用,不需要指定变量文件#还可以通过命令-e指定变量[root@dba project]# ansible-playbook vars3.yaml- hosts: webtasks:- name: install {{ webpkgs }} {{ ftppkgs }} rpmyum:name:- "{{ webpkgs }}"- "{{ ftppkgs }}"state: present
主机变量
有主机的找主机没有的找组变量 ```yaml [root@dba host_vars]# cat 192.168.203.9 webpkgs: zmap
hosts: 192.168.203.129 tasks:
- name: install {{ webpkgs }} {{ ftppkgs }} rpm
yum:
name:
- “{{ webpkgs }}” state: present
- name: install {{ webpkgs }} {{ ftppkgs }} rpm
yum:
name:
hosts: 192.168.203.130 tasks:
- name: install {{ webpkgs }} {{ ftppkgs }} rpm
yum:
name:
- “{{ webpkgs }}” state: present
- name: install {{ webpkgs }} {{ ftppkgs }} rpm
yum:
name:
-e指定变量优先级最高
[root@dba project]# ansible-playbook var4.yaml -e ‘webpkgs=lrzsz’
> 总结:> gorup_vars 针对主机清单的组> host_vars 针对主机> gorup_vars/all 对所有的组都有效变量优先级--外置-e---->vars_files-------vars---主机清单-host_var-group_vars----group_vars/all<a name="Gyumx"></a>### 注册变量- debug会输出所有变量的结果- 然后在根据输出的结果取指定的值```yaml- hosts: webtasks:- name: check httpdshell: ps aux|grep httpdregister: check_httpd- name: output varsdebug:msg: "{{ check_httpd.stdout_lines }}"
facts变量
- 可以采集被监控端cpu,内存,网络,磁盘,系统版本等信息
```yaml
- hosts: web
tasks:
- name: facts debug: msg: “{{ ansible_fqdn }} ip is {{ ansible_default_ipv4.address }}”
- hosts: web
tasks:
TASK [facts] * ok: [192.168.203.129] => { “msg”: “ansible1 ip is 192.168.203.129” } ok: [192.168.203.130] => { “msg”: “ansible2 ip is 192.168.203.130” }
<a name="8063a08a"></a>#### template配合facts使用```shell[root@dba project]# ansible web -m setup -a 'filter=ansible_memtotal_mb'192.168.203.129 | SUCCESS => {"ansible_facts": {"ansible_memtotal_mb": 3770,"discovered_interpreter_python": "/usr/bin/python"},"changed": false}192.168.203.130 | SUCCESS => {"ansible_facts": {"ansible_memtotal_mb": 3770,"discovered_interpreter_python": "/usr/bin/python"},"changed": false}#[root@dba project]# cat memcached.j2PORT="11211"USER="memcached"MAXCONN="1024"CACHESIZE="{{ ansible_memtotal_mb//2 }}"OPTIONS=""#mem.yaml- hosts: webtasks:- name: installyum: name=memcached state=present- name: startservice: name=memcached state=started- name: check memcachedshell: ps aux|grep memcachedregister: check_memcached- name:template: src=./memcached.j2 dest=/etc/sysconfig/memcached- name: output varsdebug:msg: "{{ check_memcached.stdout_lines }}"#[root@dba project]# cat hostname.yaml- hosts: dbtasks:- name: get nameshell: echo $RANDOM|md5sum|head -c 8register: get_random- name: debugdebug:msg: "{{ get_random }}"- name: hostnamehostname: name={{ get_random.stdout }}
循环控制
when
[root@dba project]# cat when.yaml- hosts: webtasks:- name: install httpdyum: name=httpd state=present- name: install httpd2yum: name=httpd2 state=presentwhen: ( ansible_distribution == "Ubuntu" )[root@ans-mgr prod]# ansible web -m setup -a 'filter=ansible_hostname' -i hosts192.168.203.131 | SUCCESS => {"ansible_facts": {"ansible_hostname": "web01","discovered_interpreter_python": "/usr/bin/python"},"changed": false}192.168.203.132 | SUCCESS => {"ansible_facts": {"ansible_hostname": "web02","discovered_interpreter_python": "/usr/bin/python"},"changed": false}#epel- hosts: alltasks:- name:name: yum repoyum_repository: ansible epeldescription: EPEL YUM repobaseurl: http://mirrors.aliyun.com/epel/7/SRPMSgpgcheck: noenabled: yeswhen: (ansible_hostname is match ("web*"))# 根据check_httpd执行的结果来重启 如果结果是0则重启 如果不是则跳过- hosts: webtasks:- name: check_httpdcommand: systemctl is-active httpdignore_errors: yesregister: check_httpd- name: debugdebug:msg: "{{ check_httpd }}"- name:service: name=httpd state=restartedwhen: check_httpd.rc == 0#非零when: check_httpd.rc != 0
items
- 循环变量 ```yaml
hosts: web tasks:
- name: restart
service: name={{ item }} state=restarted
with_items:
- httpd
- vsftp
- name: restart
service: name={{ item }} state=restarted
with_items:
- hosts: web force_handlers: yes #强制调用,可选 tasks:
tags标签
[root@dba project]# ansible-playbook tags.yaml -t "status"
[root@dba project]# ansible-playbook tags.yaml --skip-tags "status"
#tags- hosts: webtasks:- name: installyum: name=httpd state=present- name: startservice: name=memcached state=started- name:template: src=./httpd.conf.j2 dest=/etc/httpd/conf/httpd.conf- name:shell: 'systemctl status httpd'tags: 'status'- hosts: webgather_facts: notasks:- name: install nfsyum: name=nfs-utils state=presenttags: "install"- name: client datafile: path=/nfs_tt state=directory- name: client rpcyum: name=nfs-utils state=present- name: client mounttags: 'mount'mount:src: 192.168.203.131:/datapath: /nfs_ttfstype: nfsopts: defaultsstate: mounted
include
cat svc_restart.yaml- name: Restart httpd serverservice: name=httpd state=restarted- hosts: webtasks:- name: cmdcommand: echo "a"- name: restart httpdinclude: svc_restart.yaml
change_when
- hosts: webtasks:- name: installyum: name=httpd state=present- name: startservice: name=httpd state=started- name:template: src=./httpd.conf.j2 dest=/etc/httpd/conf/httpd.confnotify: server restart httpd- name: check statuscommand: /usr/sbin/httpd -tregister: check_httpdchanged_when:- ( check_httpd.stdout.find('ok'))- false#notify: server nginx httpd -可以通知多个,配置发生变动通知#触发handlers:- name: server restart httpdservice: name=httpd state=retarted
jinra
#结合facts变量# cat memcached.j2PORT="11211"USER="memcached"MAXCONN="1024"CACHESIZE="{{ ansible_memtotal_mb//2 }}"OPTIONS=""#jinra#if{% if ansible_fqdn == "web01" %}echo "123"{% if ansible_fqdn == "web02" %}echo "456"{% endif %}#for{% for in range{1,10} %}echo $i{% endfor %}#1)主机变量host_vars/192.168.203.129state: MASTERpri: 150host_vars/192.168.203.130state: BACKUPpri: 100#2) conf.j2router_id ansible_fqdn3)分发- hosts: lbtasks:- name: conftemplate: src=./keepalived.conf.j2 dest=/etc/keepalived/keepalived.confwhen: ( ansible_fqdn == "web01" )notify: restart keepalived- name: restart keepalivedtemplate: src=./keepalived-slave.conf.j2 dest=/etc/keepalived/keepalived.confwhen: ( ansible_fqdn == "web02" )notify: restart keepalivedhandlers:- name: restart keepalivedservice: name=keepalived state=restartedjinra实现keepalived渲染配置:router_id ansible_fqdn{% if ansible_fqdn == "web01" %}state MASTERpriority 150{% endif ansible_fqdn == "web02" %}state BACKUPpriority 100{% endif %}
roles
[root@dba project2]# tree ..├── hosts├── memcached│ ├── files│ ├── handlers│ │ └── main.yaml│ ├── tasks│ │ └── main.yml│ ├── templates│ │ └── memcached.j2│ └── vars├── site.yaml
#tasks/main.yml- name: install memcachedyum: name=memcached state=present- name: configtemplate: src=memcached.j2 dest=/etc/sysconfig/memcachednotify: restart memcache#handlers/main.yaml- name: startservice: name=memcached state=started enabled=yescat handlers/main.yaml- name: restart memcacheservice: name=memcached state=restarted#memcached.j2[root@dba memcached]# cat templates/memcached.j2PORT="11211"USER="memcached"MAXCONN="1024"CACHESIZE="{{ ansible_memtotal_mb//2 }}"OPTIONS=""#site.yaml- hosts: dbroles:- memcached
galaxy
ansible-galaxy init test[root@dba test]# tree ..├── defaults│ └── main.yml├── files├── handlers│ └── main.yml├── meta│ └── main.yml├── README.md├── tasks│ └── main.yml├── templates├── tests│ ├── inventory│ └── test.yml└── vars└── main.yml
综合项目
lb01 192.168.203.130 nginx+keepalived
lb02 192.168.203.151 nginx+keepalived
web01 192.168.203.131 nginx+php
web02 192.168.203.132 nginx+php
backup 192.168.203.133 rsync-server
nfs 192.168.203.134
db 192.168.203.135 mysql+ redis
基础环境
#配置ssh免密#配置host文件cat hosts[web]192.168.203.131192.168.203.132[db]192.168.203.135[lb]192.168.203.130192.168.203.151[nfs]192.168.203.134[backup]192.168.203.133#前置环境mkdir base/{tasks,handlers,templates} -pvcat base/tasks/main.yaml#disable- name: disable firewallservice: name=firewalld state=stopped enabled=no- name: disble selinuxselinux: state=disabled#add user- name: add {{ web_user }} {{ web_user_id }} groupgroup: name={{ web_user }} gid={{ web_user_id }}- name: add useruser: name={{ web_user }} uid={{ web_user_id }} group={{ web_user }}#add repo- name: add base yum repoyum_repository:name: basedescription: Base aliyun repobaseurl: https://mirrors.aliyun.com/centos/$releasever/os/$basearch/gpgcheck: noenabled: yes- name: add epel yum repoyum_repository:name: epeldescription: EPEL aliyun repobaseurl: https://mirrors.aliyun.com/epel/7/$basearch/gpgcheck: noenabled: yes- name: add nginx yum repoyum_repository:name: nginxdescription: nginx repobaseurl: http://nginx.org/packages/centos/$releasever/$basearch/gpgcheck: noenabled: yeswhen: ( ansible_hostname is match ("web*")) or( ansible_hostname is match ("lb*"))- name: add php yum repoyum_repository:name: phpdescription: php repobaseurl: https://us-east.repo.webtatic.com/yum/el7/x86_64/gpgcheck: noenabled: yeswhen: ( ansible_hostname is match ("web*"))- name: install pksyum: name={{ packages }} state=presentvars:packages:- rsync- nfs-utils- net-tools- wget- tree- lrzsz- vim- unzip- httpd-tools- bash-completion- iotop#变量[root@dba project3]# cat group_vars/allweb_user: wwwweb_user_id: 666
nginx
[root@ans-mgr roles]# mkdir nginx/{tasks,handlers,templates} -pv
##基础模块nginx/#templates/nginx.conf.j2#修改nginx配置的如下部分其他地方不变user {{ web_user }};worker_processes {{ ansible_processor_cores }};events {worker_connections {{ ansible_processor_cores * 2048 }};}#tasks/main.yaml- name: install nginxyum: name=nginx state=present- name: config nginxtemplate: src=nginx.conf.j2 dest=/etc/nginx/nginx.confnotify: restart nginx service- name: check statuscommand: /usr/sbin/nginx -tregister: check_nginxchanged_when:- ( check_nginx.stdout.find('successfully'))- name: start nginxservice: name=nginx state=started#handlers/main.yaml- name: restart nginx serviceservice: name=nginx state=restarted#变量[root@dba project3]# cat group_vars/allweb_user: wwwweb_user_id: 666#site[root@dba project3]# cat site.yaml- hosts: allroles:- base- hosts: webroles:- role: nginxtags: nginx#运行ansible-playbook site.yaml -i hosts -t nginx
php
- name: install phpyum: name={{ item }} state=presentwith_items:- php71w- php71w-cli- php71w-common- php71w-devel- php71w-embedded- php71w-gd- php71w-mcrypt- php71w-mbstring- php71w-pdo- php71w-xml- php71w-fpm- php71w-mysqlnd- php71w-opcache- php71w-pecl-memcached- php71w-pecl-redis- php71w-pecl-mongodb- name: config phptemplate: src={{ item.src }} dest={{ item.dest }} mode={{ item.mode }}with_items:- { src: 'php.ini.j2', dest: '/etc/php.ini', mode: '0644'}- { src: 'www.conf.j2', dest: '/etc/php-fpm.d/www.conf', mode: '0644'}notify: restart nginx service- name: check statuscommand: /usr/sbin/nginx -tregister: check_nginxchanged_when:- ( check_nginx.stdout.find('successfully'))- name: start phpservice: name=php-fpm state=started#handlers/main.yaml- name: restart php serviceservice: name=php-fpm state=restarted#j2[root@ans-mgr php]# cat templates/php.ini.j2 | grep server_session.save_path = "tcp://{{ redis_server_ip }}:{{ redis_server_port }}"#group_vars/allredis_server_ip: 192.168.203.135redis_server_port: 6379[root@ans-mgr roles]# cat site.yaml- hosts: allroles:- base- hosts: webroles:- role: nginx- role: phptags: web
nfs
#nfs#客户端#准备目录#挂载共享目录#task/main.yaml- name: install nfsyum: name=nfs-utils state=present- name: config nfstemplate: src=exports.j2 dest=/etc/exportsnotify: restart nfs- name: nfs groupgroup: name={{ nfs_user }} gid={{ nfs_user_id }}- name: nfs useruser: name={{ nfs_user }} uid={{ nfs_user_id }} group={{ nfs_user }} shell=/sbin/nologin create_home=no- name: nfs share directoryfile: path={{ nfs_dir }} state=directory owner={{ nfs_user }} group={{ nfs_user }} recurse=yes- name: service startservice: name=nfs state=started enabled=yes###挂载- hosts: webgather_facts: notasks:- name: client datafile: path=/nfs_tt state=directory- name: client mountmount:src: 192.168.203.131:/datapath: /nfs_ttfstype: nfsopts: defaultsstate: mounted#handlers/main.yaml- name: restart nfsservice: name=nfs state=restarted#allweb_user: wwwweb_user_id: 666nfs_user: nfsnfs_user_id: 888nfs_dir: /datanfs_share_ip: 192.168.203.0/24#j2 exports{{ nfs_dir }} {{ nfs_share_ip }}(rw,sync,all_squash,anonuid={{ nfs_user_id }},anongid={{ nfs_user_id }})#site.yaml- hosts: allroles:- base- hosts: webroles:- role: nginxtags: nginx- hosts: nfsroles:- role: nfstags: nfs
redis
#redis- name: install redisyum: name=reids-server state=present- name: config redistemplate: src=redis.conf.j2 dest=/etc/redis.confnotify: restart redis- name: service startservice: name=redis state=started enabled=yes#handlers/main.yaml- name: restart redisservice: name=redis state=restarted#j2bindip {{ ansible_default_ipv4.address }}#- hosts: dbroles:- role: redistags: redis
mysql
#mysqlAnsible 角色:安装mysql(简易版)基于ansible一键部署mysql的角色,自动安装mysql-python 方便后期使用mysql相关模块便于操作,并且设置默认root账号登录密码一、版本要求被控节点:Centos7控制节点:Ansible2.9(控制节点其他版本的Ansible没有测试过)mysql 版本:mysql57-community-release-el7-9#前提做好yum源和ssh免密二、如何使用1、进入ansible默认角色目录cd /etc/ansible/roles1如果在ansible.cfg中更改了默认的角色目录,根据你自己角色目录进行更改2、创建一个角色ansible-galaxy init mysql_install5、主机清单[root@dba project4]# cat hosts[db]192.168.203.135#结构[root@dba mysql_install]# tree .defaults└─main.ymlfiles├─change_root_passwd.sh└─mysql57-community-release-el7-9.noarch.rpmhandlersmetatasks├─change_root_password.yml├─install.yml├─main.yml└─mysql-py_install.ymltemplatestests└─test.ymlvars三、实例剧本---- hosts: dbroles:- mysql_installvars:#一键部署,设置登录root密码mysql_passwd: "123456"8四、角色详解defaults└─main.ymlfiles├─change_root_passwd.shhandlersmetatasks├─change_root_password.yml├─install.yml├─main.yml└─mysql-py_install.ymltemplatestests└─test.ymlvars2、任务主任务main.yml---# tasks file for mysql_install#剧本执行顺序- include: install.yml- include: mysql-py_install.yml- include: change_root_password.yml安装任务install.yml---#创建临时文件夹任务- name: create directoryfile:path: "{{ mysql_temp_path }}"state: directory#复制rpm安装包任务- name: copy rpm packagecopy:src: "{{ rpm_package_name }}"dest: "{{ mysql_temp_path }}"#安装本地rpm安装包- name: install rpmyum:name: "{{ rpm_package_location }}"state: present#安装mysql-server- name: install mysql serveryum:name: mysql-serverstate: present#启动mysql- name: start mysqlservice:name: mysqldstate: started远程主机安装mysql-python模块任务mysql-py_install.yml---#安装epel扩展源任务- name: install Extended sourceyum:name: epel-releasestate: present#安装依赖包- name: install mysql-python dependency packagesyum:name: "{{ dependency_packages }}"state: present#安装mysql模块- name: install mysql-python modulepip:name: mysql-python更改root密码任务change_root_password.yml---#找到安装完成之后的临时密码任务- name: find temp passwdshell: "{{ find_temp_passwd_code }}"register: resultstags: passwd#复制脚本文件任务- name: copy script filecopy:src: change_root_passwd.shdest: "{{ change_passwd_sh }}"tags: passwd#为什么不直接使用script模块:# 脚本中有变量,如果使用script模块,参数不可以在ansible服务器上传入脚本#所以使用copy模块复制脚本到远程主机之后,使用lineinfile模块替换掉脚本中的#变量。#用临时密码的变量替换脚本中的临时密码变量任务- name: send temp root password to shell filelineinfile:path: "{{ change_passwd_sh }}"regexp: '^PASSWORD='line: "PASSWORD={{ temp_password }}"tags: passwd#用主任务定义的新密码的变量替换脚本中的新密码变量任务- name: send new root password to shell filelineinfile:path: "{{ change_passwd_sh }}"regexp: '^New_Pass='line: "New_Pass={{ new_pass }}"tags: passwd#跑脚本任务- name: change root passwordshell: "sh {{ change_passwd_sh }}"tags: passwd3、变量---# defaults file for mysql_install#剧本变量#mysql临时文件夹mysql_temp_path: "/etc/tmp/mysql"#rpm包名称rpm_package_name: "mysql57-community-release-el7-9.noarch.rpm"#rpm包位置rpm_package_location: "{{ mysql_temp_path }}/{{ rpm_package_name }}"#找到临时文件的命令find_temp_passwd_code: "grep 'temporary password' /var/log/mysqld.log"#更换root密码脚本change_passwd_sh: "{{ mysql_temp_path }}/change_root_passwd.sh"#临时密码,取值为找到临时文件命令输出切片temp_password: "{{ results.stdout[-14:] }}"#新密码,在主任务do.yml中定义new_pass: "{{ mysql_passwd }}"#依赖包dependency_packages:- mysql- mysql-devel- python-devel- python-pip4、脚本更改密码脚本change_root_passwd.sh#!/bin/bashHost=127.0.0.1User=rootPASSWORD=PORT=3306New_Pass=mysql -u$User -p'$PASSWORD' --connect-expired-password <<EOFset global validate_password_policy=LOW;set global validate_password_length=6;set password =password("$New_Pass");EOF————————————————版权声明:本文为CSDN博主「2huxy」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。原文链接:https://blog.csdn.net/qq_42267013/article/details/115368911
mysql 这里一直报错误密码不对 但是日志显示已经对了,没解决
网上看到的https://www.5axxw.com/questions/content/6027sc
--- name: root | stat to check whether /root/.my.cnf existsstat:path: /root/.my.cnfregister: cnf_file- block:- name: root | place temporary cnf filetemplate:src: temp_cnf.j2dest: /etc/my.cnfmode: '0644'- name: root | start mysql to add the debian-sys-maint usersystemd:name: mysqlstate: startedenabled: true- name: root | get temp root passwordshell: >-grep 'temporary password' /var/log/mysqld.log |awk '{print $NF}' | tail -n 1register: temp_root_pwno_log: true- name: root | set root passwordshell: >-mysqladmin -u root--password="{{ temp_root_pw.stdout }}"password "{{ mysql_root_password }}"no_log: true- name: root | set debian-sys-maint user and passwordmysql_user:name: debian-sys-maintpassword: "{{ mysql_system_password }}"priv: '*.*:ALL,GRANT'update_password: alwaysstate: presentlogin_unix_socket: /var/run/mysqld/mysqld.socklogin_user: rootlogin_password: "{{ mysql_root_password }}"no_log: true- name: root | copy root.cnftemplate:src: root.cnf.j2dest: /etc/mysql/root.cnfmode: '0600'owner: rootgroup: root- name: root | make symlink of file for root db accessfile:state: linksrc: /etc/mysql/root.cnfpath: /root/.my.cnf- name: root | delete anonymous connectionsmysql_user:name: ""host_all: truestate: absentno_log: true- name: root | secure root usermysql_user:name: roothost: "{{ item }}"no_log: trueloop:- ::1- 127.0.0.1- localhost- name: root | ensure test database is removedmysql_db:name: testlogin_user: rootstate: absent- name: root | stop mysql againsystemd:name: mysqlstate: stoppedenabled: true- name: root | remove mysqld log filefile:path: /var/log/mysqld.logstate: absentwhen: not cnf_file.stat.existsThe temp_cnf.j2:[client]socket=/var/run/mysqld/mysqld.sock[mysqld]server-id=1datadir=/var/lib/mysqlsocket=/var/run/mysqld/mysqld.socklog-error=/var/log/mysqld.logpid-file=/var/run/mysqld/mysqld.pid以及root.cnf.j2# {{ ansible_managed }}# This file is symlinked to /root/.my.cnf to use passwordless login for the root user[client]socket = {{ mysqld.socket }}user = debian-sys-maintpassword = {{ percona_system_password }}[mysql_upgrade]socket = {{ mysqld.socket }}user = debian-sys-maintpassword = {{ percona_system_password }}Some vars:mysql_root_password: my_passwordmysql_system_password: my_passwordmysqld:socket: /var/run/mysqld/mysqld.sock应该适用于CentOS 8、Rocky Linux和Oracle Linux。
结合项目: shell脚本调用的方式还是没有解决,直接不调了
cat mysql_install/tasks/main.yml# tasks file for mysql_install#创建临时文件夹任务- name: create directoryfile:path: "{{ mysql_temp_path }}"state: directory#复制rpm安装包任务# - name: copy rpm package# copy:# src: "{{rpm_package_name}}"# dest: "{{mysql_temp_path}}"#安装本地rpm安装包# - name: install rpm# yum:# name: "{{rpm_package_location}}"# state: present#安装mysql-server- name: install mysql serveryum:name: mysql-serverstate: present#启动mysql- name: start mysqlservice:name: mysqldstate: started# - name: install Extended source# yum:# name: epel-release# state: present#安装依赖包- name: install mysql-python dependency packagesyum:name: "{{ dependency_packages }}"state: present#安装mysql模块- name: install mysql-python modulepip:name: mysql-python# - name: install Extended source# yum:# name: epel-release# state: present#安装依赖包- name: install mysql-python dependency packagesyum:name: "{{ dependency_packages }}"state: present#安装mysql模块- name: install mysql-python modulepip:name: mysql-python- name: root | get temp root passwordshell: grep 'temporary password' /var/log/mysqld.log |awk '{print $NF}' | tail -n 1register: temp_root_pwno_log: true- name: root | set root passwordshell: mysqladmin -u root --password="{{ temp_root_pw.stdout }}" password "{{ mysql_passwd }}"no_log: true- name: root | secure root usermysql_user:name: roothost: "{{ item }}"no_log: trueloop:- '%'- 127.0.0.1- localhost
#mysql模块#base# Enable to use MySQL 5.7- name: add mysql yum repoyum_repository:name: mysqldescription: mysql repobaseurl: http://repo.mysql.com/yum/mysql-5.7-community/el/7/$basearch/gpgcheck: noenabled: yeswhen: ( ansible_hostname is match ("db*"))#mysql- name: install mysqlyum:name: ['mysql-server', 'MySQL-python']state: present- name: config mysqltemplate: src=my.cnf.j2 dest=/etc/my.cnf backup=yesnotify: restart mysql- name: service startservice: name=mysqld state=started enabled=yes#handlers/main.yaml- name: restart mysqlservice: name=mysqld state=restarted- name: create databasemysql_db:name: wordpressstate: presentlogin_user: rootlogin_password: "{{ mysql_pass }}"- name: create mysql user/pass grantmysql_user:name: "{{ db_user }}"password: "{{ db_pass }}"priv: '*.*:ALL'host: '%'state: presentlogin_user: rootlogin_password: "{{ mysql_passwd }}"#group/all 变量#dbdb_user: lcdb_pass: 123456mysql_pass: 123456
