ansible的脚本

playbook剧本

1、playbook的组成

1、Tasks:任务,每一个task就是一个模块

2、Variables:变量,存储和传递数据,可以自定义变量也可以是全局变量,也可以是脚本外传参

3、Templates:模版,用生成配置文件和多任务的编排

4、Handlers:处理器,用于满足某些条件时触发的操作,一般用于重启等操作

5、Roles:角色,组织和封装剧本的过程,角色可以把任务、变量、模版、处理器,组合成一个可用单元

2、yaml文件的语法

vim test1.yaml

- name: first play
#定义剧本的名称,可以省略
  gather_facts: false
#表示在执行剧本之前是否收集目标主机的信息,false是不收集,可以加快执行速度。如果不写,默认就是收集
  hosts: 192.168.230.20
#指定目标主机,可以是组名也可以是ip地址
  remote_user: root
#在目标主机的执行用户
  tasks: 
    - name: test connection
#定义一个任务的名称,可以自定义
      ping:
#ping是模块名称
    - name: close selinux
      command: '/sbin/setenforce 0'
      ignore_errors: True
#如果在任务执行中报错,返回码非0报错,task就会停止,ignore_errors: True就会忽略错误,继续执行下一个任务
    - name: close firewalld
      service: name=firewalld state=stopped 
#调用service模块,关闭防火墙
    - name: install httpd
      yum: name=httpd state=latest
#latest表示安装当前库中的最新版本的软件
    - name: interview
      shell: echo "this is httpd" > /var/www/html/index.html
#执行shell模块,修改默认的访问页面
      notify: restart httpd
#ansible在执行完任务之后并不会立即执行重启,通过notify指令对应的名称传给触发器,让触发器在任务的最后执行重启,避免在任务中多次执行重启,影响执行的效率
  handlers:
    - name: restart httpd
      service: name=httpd state=restarted 

#运行
ansible-playbook test1.yaml

3、安装nginx

安装方式为yum,传一个配置文件到目标主机,修改默认端口为8080,访问页面内容this is nginx

vim test2.yaml

- name: first play
  gather_facts: false
  hosts: 192.168.230.30
  remote_user: root
  tasks:
    - name: test connection
      ping:
    - name: close selinux
      command: '/sbin/setenforce 0'
      ignore_errors: True
    - name: close firewalld
      service: name=firewalld state=stopped
    - name: install nginx
      yum: name=nginx state=latest
    - name: interview
      shell: echo "this is nginx" > /usr/share/nginx/html/index.html
    - name:
      copy: 'src=/opt/nginx.conf dest=/etc/nginx/'
      notify: restart nginx
  handlers:
    - name: restart nginx
      service: name=nginx state=restarted

#运行
ansible-playbook test2.yaml

4、定义变量,引用变量

脚本当中定义,以及脚本外传参

vim test3.yaml

- name: second play
  hosts: 192.168.230.30
  remote_user: root
  vars: 
    groupname: mysql
    username: nginx1
#定义变量
  tasks: 
    - name: create group
      group: 
        name: "{{ groupname }}"
        system: yes
        gid: 306
    - name: create user
      user:
        name: "{{ username }}"
        uid: 306
        group: "{{ groupname }}"

#运行
ansible-playbook test3.yaml

#往脚本里传参
ansible-playbook test1.yaml -e 'groupname=test1 username=test2'

#检查脚本语法是否有错
ansible-playbook test1.yaml --syntax-check

#检查脚本中有几个任务
ansible-playbook test1.yaml --list-task

#查看对哪些主机生效
ansible-playbook test1.yaml --list-hosts

#指定从哪个任务开始运行
ansible-playbook test1.yaml --start-at-task='create user' -e 'username=test3 groupname=test4'


#切换用户
- name: second play
  hosts: 192.168.230.30
  remote_user: dn
  become: yes
#先用普通用户执行,但是需要切换到其他的用户。例如切换到管理员
  become_user: root

5、在脚本中实现条件判断

when 满足条件的主机执行,不满足的跳过

vim test4.yaml

- name: this is if
  hosts: all
  remote_user: root
  tasks:
    - name: test when
      debug: msg='条件满足'
#debug相当于echo
      when: ansible_default_ipv4.address == "192.168.230.30"
      
ansible_default_ipv4.address != "192.168.230.30"   
#取反

#运行
ansible-playbook test4.yaml

6、循环结构

ansible有多种循环方式,一般都命名为with_items,定义循环的内容

#with_items 单循环输出

- name: item test
  hosts: 192.168.230.20
  remote_user: root
  gather_facts: false
  tasks:
    - debug:
        msg: "{{item}}"
      with_items:
        - [a,b,c,d]
        - [1,2,3,4]
      
输出item的值,with_items:a b c d 依次传入
with_list:整个列表作为一个整体进行输出
with_together:作为整体两两配对输出
with_nested:每一层都会遍历执行一遍输出结果

7、创建递归目录

条件判断,主机的ip=192.168.230.20才会执行,一次性创建4个文件 /opt/a /opt/b /opt/c /opt/d

vim test5.yaml
方法一:
- name:      
  hosts: 192.168.230.20
  gather_facts: false
  vars: 
    test:
      - /opt/test1
      - /opt/test2
      - /opt/test3
      - /opt/test4
  tasks:
    - name: create mulu
      file:
        path: "{{item}}"
        state: directory
      with_items: "{{test}}"

方法二:
- name:      
  hosts: 192.168.230.20
  gather_facts: false
  tasks:
    - name: create mulu
      file:
        path: "{{item}}"
        state: directory
      with_items: [/opt/test1,/opt/test2,/opt/test3/opt/test4]
      
#运行
ansible-playbook test5.yaml
### Ansible Script Module Usage and Examples The `ansible.builtin.script` module allows executing scripts on the target machines. This can be particularly useful when tasks require more complex logic than what ad-hoc commands or simple modules provide. #### Basic Syntax of Using Script Module To use a script with Ansible, one specifies the path to the local script file that should run remotely on all targeted nodes[^1]. The syntax generally looks like: ```yaml - name: Run custom script against managed nodes ansible.builtin.script: src: /path/to/local/script.sh ``` This command copies the specified script from the control machine to each host's temporary directory before running it there. After execution completes successfully, any generated files will remain behind unless explicitly cleaned up within the script itself. #### Example Playbook Utilizing Script Module Below demonstrates how to create an example playbook named `run_script.yml`, which executes a Python program located locally at `/home/user/scripts/hello.py`. ```yaml --- - hosts: webservers become: yes gather_facts: no tasks: - name: Execute hello world python script via script action plugin ansible.builtin.script: src: "/home/user/scripts/hello.py" ``` In this case, assuming the inventory defines `webservers` as a group containing web server instances where administrative privileges are required (`become: yes`). Also note that fact collection has been disabled here since not needed for simply invoking external programs through their absolute paths. #### Important Notes Regarding Script Execution When using the `script` module, several considerations apply regarding environment variables, permissions, and idempotency principles common across configuration management tools such as Ansible[^2]: - Environment Variables: By default, only essential environmental settings propagate over SSH connections made during task invocations; therefore, ensure critical configurations get passed along properly. - Permissions Handling: Depending upon the nature of operations performed inside your scripts, additional rights might need granting either temporarily (using privilege escalation mechanisms built into Ansible) or permanently (modifying system policies). - Idempotence Concerns: Since arbitrary code gets executed outside direct supervision of core framework constructs provided by Ansible, care must taken to avoid unintended side effects arising out repeated runs without proper checks ensuring consistent outcomes regardless number executions carried out sequentially.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值