使用Ansible在sysctl中设置多个值

时间:2019-02-28 18:57:30

标签: ansible sysctl

我有一本有多个任务的剧本,将值设置为sysctl。不用为每个设置分配一个任务,而是如何使用sysctl模块通过一个任务设置所有值?

剧本片段:

- name: Set tcp_keepalive_probes in sysctl
  become: yes
  sysctl:
    name: net.ipv4.tcp_keepalive_probes
    value: 3
    state: present
    reload: yes

- name: Set tcp_keepalive_intvl in sysctl
  become: yes
  sysctl:
    name: net.ipv4.tcp_keepalive_intvl
    value: 10
    state: present
    reload: yes

- name: Set rmem_default in sysctl
  become: yes
  sysctl:
    name: net.core.rmem_default
    value: 16777216
    state: present
    reload: yes

2 个答案:

答案 0 :(得分:2)

简单解决方案:将变量定义为字典

示例剧本:

---
- hosts: all
  gather_facts: false
  become: true
  vars:
    ansible_python_interpreter: /usr/bin/python3
    sysctl_config:
      net.ipv4.ip_forward: 1
      net.ipv4.conf.all.forwarding: 1
      net.ipv6.conf.all.forwarding: 1

  tasks:
   - name: Change various sysctl-settings
     sysctl:
       name: '{{ item.key }}'
       value: '{{ item.value }}'
       sysctl_set: yes
       state: present
       reload: yes
       ignoreerrors: yes
     with_dict: '{{ sysctl_config }}'

输出:

TASK [Change various sysctl-settings] **********************************************************************************************************************************************************************
changed: [10.10.10.10] => (item={'key': 'net.ipv4.ip_forward', 'value': 1}) => {
    "ansible_loop_var": "item",
    "changed": true,
    "item": {
        "key": "net.ipv4.ip_forward",
        "value": 1
    }
}
changed: [10.10.10.10] => (item={'key': 'net.ipv4.conf.all.forwarding', 'value': 1}) => {
    "ansible_loop_var": "item",
    "changed": true,
    "item": {
        "key": "net.ipv4.conf.all.forwarding",
        "value": 1
    }
}
changed: [10.10.10.10] => (item={'key': 'net.ipv6.conf.all.forwarding', 'value': 1}) => {
    "ansible_loop_var": "item",
    "changed": true,
    "item": {
        "key": "net.ipv6.conf.all.forwarding",
        "value": 1
    }
}

答案 1 :(得分:1)

在var文件中定义所有变量:

例如

sysctl:
  - name: test
    value: test

...   ...

剧本:

- hosts: "{{ }}"
  tasks: 
    - name: update sysctl param
      sysctl:
        name: "{{ item.name }}"
        value: "{{ item.value }}"
        state: present
        reload: yes
      with_items:
        - "{{ hosts }}"