Linux自动化工具之Ansible playbook
2020-02-21自动化运维90root466°c
A+ A-写一个playbook,在远程机器上touch一个文件
1、先进入ansible目录下
[[email protected] ~]# cd /etc/ansible/ [[email protected] ansible]# ls ansible.cfg hosts roles
2、创建一个文件,固定后缀为yml,一定要注意空格
[[email protected] ansible]# vim test.yml 1 --- 2 - hosts: testhosts 3 user: root 4 tasks: 5 - name: playbook_test 6 shell: touch /tmp/playbook.txt
注意:
hosts参数指定了对哪些主机进行参作;
user参数指定了使用什么用户登录远程主机操作;
tasks指定了一个任务,其下面的name参数同样是对任务的描述,在执行过程中会打印出来。
3、执行配置文件
[[email protected] ansible]# ansible-playbook test.yml PLAY [testhosts] *************************************************************** TASK [setup] ******************************************************************* ok: [101.200.148.30] ok: [127.0.0.1] TASK [playbook_test] *********************************************************** changed: [101.200.148.30] [WARNING]: Consider using file module with state=touch rather than running touch changed: [127.0.0.1] PLAY RECAP ********************************************************************* 101.200.148.30 : ok=2 changed=1 unreachable=0 failed=0 127.0.0.1 : ok=2 changed=1 unreachable=0 failed=0
4、查看有没有创建
[[email protected] ~]# ls -la /tmp/ total 32 drwxrwxrwt. 5 root root 4096 Jul 17 00:49 . dr-xr-xr-x. 22 root root 4096 Jul 15 23:23 .. -rw-r--r-- 1 root root 1099 Jul 16 04:26 123 drwxr-xr-x 3 root root 4096 Jul 16 04:45 456 srwxrwxrwx 1 root root 0 Jul 15 23:23 Aegis-<Guid(5A2C30A2-A87D-490A-9281-6765EDAD7CBA)> drwxr-xr-x 3 root root 4096 Jul 16 04:44 ansibletestowner=root -rw-r--r-- 1 root root 29 Jul 16 05:03 ansible_test.txt drwxrwxrwt 2 root root 4096 Jul 15 23:23 .ICE-unix -rw-r--r-- 1 root root 0 Jul 17 00:49 playbook.txt srwxrwxrwx 1 root root 0 Jul 15 23:23 qtsingleapp-aegisG-46d2 srwxrwxrwx 1 root root 0 Apr 21 21:08 qtsingleapp-aegiss-a5d2 -rwxr-xr-x 1 root root 46 Jul 16 05:01 test.sh
5、创建用户实例
[[email protected] ansible]# vi user.yml 1 --- 2 - name: create_user 3 hosts: testhosts 4 user: root 5 gather_facts: false 6 vars: 7 - user: "test" 8 tasks: 9 - name: create user 10 user: name="{{ user }}"
注意:
name参数对该playbook实现的功能做一个概述,后面执行过程中,会打印 name变量的值 ,可以省略;
gather_facts参数指定了在以下任务部分执行前,是否先执行setup模块获取主机相关信息,这在后面的task会使用到setup获取的信息时用到;
vars参数指定了变量,这里指字一个user变量,其值为test ,需要注意的是,变量值一定要用引号引住;
user提定了调用user模块,name是user模块里的一个参数,而增加的用户名字调用了上面user变量的值。
6、执行配置文件
[[email protected] ansible]# ansible-playbook user.yml PLAY [create_user] ************************************************************* TASK [create user] ************************************************************* changed: [101.200.148.30] changed: [127.0.0.1] PLAY RECAP ********************************************************************* 101.200.148.30 : ok=1 changed=1 unreachable=0 failed=0 127.0.0.1 : ok=1 changed=1 unreachable=0 failed=0
7、检查有没有创建
[[email protected] ~]# grep test /etc/passwd test:x:500:500::/home/test:/bin/bash