我希望在/etc/security.limits.conf中创建条目 数据结构如下所示:
limits:
- root:
- "soft nproc unlimited"
- "hard nfile unlimited"
- ec2-user:
- "soft nproc 4096"
在/etc/security.conf中生成行,如下所示:
root soft nproc unlimited root hard nfile unlimited ec2-user soft nproc 4096
数据定义生成数组字典。外部字典由用户键入,每个字典都有自己的行数组来添加。
我希望代码看起来像这个伪代码:
for user in $limits
for line in $user
lineinfile $line ...
end
end
我无法通过Ansible看到如何做到这一点。
我一直在调试调试任务,所以我可以看到{{item}}包含的内容 - 就像这样:
- name: limits | Set limits in /etc/security/limits.conf
debug:
msg: item is {{ item }}
loop: "{{ limits }} "
但是如何获得数组的各个元素?最多可能有16个数组元素 - 每个可调参数一个。
我发现这对谷歌来说是不可能的 - 所有结果都是指Ansible docs,我已经彻底阅读了 - 并不总是理解。
任何指针都非常感激,如果我错过了一些明显的东西,我会道歉!
答案 0 :(得分:3)
Using with_subelements
:
File varloops.yml
:
---
- name: Loop using with_subelements
hosts: localhost
connection: local
vars_files:
- vars.yml
gather_facts: no
tasks:
- name: create a test file
file:
path: "{{ mytestfile }}"
state: touch
- name: create required entries in file
lineinfile:
dest: "{{ mytestfile }}"
line: "{{ item.0.name }} {{ item.1 }}"
with_subelements:
- "{{ limits }}""
- contents
File vars.yml
:
---
mytestfile: ~/ansible-projects/test.txt
limits:
- name: root
contents:
- "soft nproc unlimited"
- "hard nfile unlimited"
- name: ec2-user
contents:
- "soft nproc 4096"
I run this with:
$ ansible-playbook varloops.yml
and $ cat test.txt
shows:
root soft nproc unlimited
root hard nfile unlimited
ec2-user soft nproc 4096
答案 1 :(得分:2)
The best I've got is using subelements module. It is necessary to change the data structure, but it is also a best practice to use named elements instead of just nested lists:
limits:
- user: root
limits:
- "soft nproc unlimited"
- "hard nfile unlimited"
- user: ec2-user
limits:
- "soft nproc 4096"
And the task:
- debug:
msg: "username is {{ item.0.user }}, security limits are {{item.1 }}"
loop: "{{ query('subelements', limits, 'limits') }}"