Ansible study notes 09-use variables in the script 2

1. Goals

Ways to use variables in several scripts

Two, examples

1. Define parameters in the script and use parameters in the script

# 给目标主机组zabbix_agent执行操作
- hosts: zabbix_agent
# 剧本以root身份执行
  user: root
# 在剧本中定义参数,变量叫xuser,值是user1
  vars:
    - xuser: "user1"
  tasks:
    - name: create user to system by kahn
# user模块、present是添加,absent是删除{
   
   { xuser }}调用上面定义的参数
      user: name={
   
   { xuser }} state=present

 

2. Define parameters for each host in the ansible host group

2-1. Edit /etc/ansible/hosts, define the corresponding parameters behind each host, such as:

[zabbix_agent]
10.100.100.30 xuser="userA"
10.100.100.40 xuser="userB"

 2-2. Write script call parameters

# 给目标主机组zabbix_agent执行操作
- hosts: zabbix_agent
# 剧本以root身份执行
  user: root
  tasks:
    - name: create user to system by kahn
# user模块、present是添加,absent是删除{
   
   { xuser }}调用别的地方定义的参数
      user: name={
   
   { xuser }} state=present

2-3. Execute the script and see the effect

3. Create group-level variables in the ansible host group

3-1. Edit /etc/ansible/hosts, create a group-level variable for the host group [zabbix_agent], add a line [zabbix_agent:vars] to the configuration, and write the variable kv under it. As shown below

Format:
[host group name: vars]
variable key="variable value value"

 3-2. The script remains the same as above

3-3. Execute the script to see the effect

Guess you like

Origin blog.csdn.net/xoofly/article/details/126696174