Home > front end >  Ansible: variable parameters in modules
Ansible: variable parameters in modules

Time:07-13

Is there a way to add a list of parameters to a module from a predefined variable?

For instance, I might have the following vars defined:

common_keys_core:
  networks:
    - network1
  restart: always

common_keys_apps:
  networks:
    - network1
    - proxy1
  restart: unless-stopped

common_keys_media:
  networks:
    - network2
    - proxy1
  restart: "no"

And a docker container like this:

- name: Launch traefik container
  docker_container:
    name: traefik
    image: 'traefik:latest'
    state: started
    <insert common_keys_core here>
    ...

As outlined in the example above, I'd like to insert the common_keys_core variable as parameters for the docker container. I have many different containers that require different sets of parameters that can by grouped by core, apps or media. The example I gave is just a simplified version to illustrate my situation.

Docker has a way of doing this using extension fields as follows:

    
  traefik:
    <<: *common-keys-core
    container_name: traefik
    

CodePudding user response:

Docker has a way of doing this using extension fields

This is actually not docker-compose specific. It's a yaml feature called Merge Key Language-Independent Type. docker compose just added a way to define those in specific extension fields (starting with x-) that it will simply ignore at parse time so you can reuse them wherever you wish.

You can use the same feature in ansible as long as you define the anchor and the use of the alias in the same yaml file

Note that the keys you merge can be overridden where you use them. So your above example could be simplified as follow (pseudo untested playbook)

---
- name: pseudo example to use merge key syntax
  hosts: localhost
  gather_facts: false

  vars:
    docker_defaults: &ddef
      networks:
        - network2
        - proxy1
      state: started
      restart: unless-stoped

  tasks:
    - name: container using defaults
      docker_container:
        <<: *ddef
        name: traefik
        image: 'traefik:latest'

    - name: container we don't restart
      docker_container:
        <<: *ddef
        name: container1
        image: 'traefik:latest'
        restart: no

    - name: container we don't restart with alternative networks
      docker-container:
        <<: *ddef
        name: container3
        image: 'hello-world:latest'
        restart: no
        networks:
          - anOtherNetwork

  • Related