大网数据广告活动
服务器运维问答

Iterating through an ansible hosts group to modify a templated file at playbook runtime

· 52CE 我爱测

Let's say I have the following hosts groups in my Ansible inventory [qrouters] devops-qr1 devops-qr2 [shards] devops-shrd1 devops-shrd2 devops-shrd3 I have to add shards to a mongodb cluster with a command similar as sh.addShard(…

问题原文

原帖链接 · J.F.Gratton · CC BY-SA 4.0

Let's say I have the following hosts groups in my Ansible inventory

[qrouters]
devops-qr1
devops-qr2

[shards]
devops-shrd1
devops-shrd2
devops-shrd3

I have to add shards to a mongodb cluster with a command similar as sh.addShard("<$REPLICASETNAME>/comma-separated-list-of-hosts") (ex: sh.addShard( "<replSetName>/s1-mongo1.example.net:27018,s1-mongo2.example.net:27018,s1-mongo3.example.net:27018")

I'd want to write that command in a templated file in my role (let's say roles/mongo_sharding/templates/addShards.j2), but do not know how to iterate through the inventory file.

Please keep in mind that the number of hosts in the [shards] group could change from time to time.

已采纳解答

原帖链接 · Vladimir Botka · CC BY-SA 4.0

The template

$ cat addShards.j2
sh.addShard( "<{{ my_replica_set }}>/{{ my_hosts }}")

and the playbook

$ cat my_playbook.yml
- hosts: localhost

  vars:
    my_replica_set: "replSetName"
    my_group: "shards"

  tasks:

    - set_fact:
        my_hosts: "{{ groups[my_group]|join( ':27018,') ~ ':27018' }}"
    - template:
        src: addShards.j2
        dest: my_command

give

$ cat my_command 
sh.addShard( "<replSetName>/devops-shrd1:27018,devops-shrd2:27018,devops-shrd3:27018")

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2020-02-10)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 4.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。