I need to retrieve some parameters from AWS SSM with ansible to create an env file. I tried this tasks:
- name: Get enviroment vars
local_action: set_fact "{{ lookup('aws_ssm', '/myi-homemade-apps-config/{{ service_environment }}/{{ stack_name }}', region='eu-west-1', shortnames=true, bypath=true, recursive=true, on_missing='skip' ) }}"
- name: Create .env file
ansible.builtin.template:
src: env.file.j2
dest: /opt/docker-swarm-stack/{{ stack_name }}/.env
mode: "0600"
become: true
I set local_action because I need this task being executed in the local host, not in remote.
The template has:
{% for key, value in env_content.items() %}
{{key}}={{value}}
{% endfor %}
When I play the playbook, I get this error:
fatal: [remote_host -> localhost]: FAILED! => {"msg": "template error while templating string: unexpected end of template, expected ','.. String: \"{{ lookup('aws_ssm', '/myi-homemade-apps-config/{{ service_environment }}/{{ stack_name }}', region"}
What I'm doing wrong?
Thanks
I tried this task:
local_action: set_fact "{{ lookup('aws_ssm', '/myi-homemade-apps-config/{{ service_environment }}/{{ stack_name }}', region='eu-west-1', shortnames=true, bypath=true, recursive=true, on_missing='skip' ) }}"
Without the {{ before lookup and without the last }} but I get this error:
TASK [docker-swarm-stack : Get enviroment vars] **************************************************************************************************************************************************************
An exception occurred during task execution. To see the full traceback, use -vvv. The error was: NoneType: None
fatal: [remote_host -> localhost]: FAILED! => {"changed": false, "msg": "The variable name '\" lookup('aws_ssm', '/myi-homemade-apps-config/development/service', region' is not valid. Variables must start with a letter or underscore character, and contain only letters, numbers and underscores."}
The main problem is that set_fact is not being given a parent fact to store all your parameters from SSM.
Here's an updated code that will work for you.
- name: Get SSM parameters
local_action:
module: ansible.builtin.set_fact
env_content: "{{ lookup('aws_ssm', '/myi-homemade-apps-config/{{ service_environment }}/{{ stack_name }}', region='eu-west-1', shortnames=true, bypath=true, recursive=true, on_missing='skip' ) }}"
shortnames=true, bypath=true,
recursive=true) }}"
- name: Create .env file
ansible.builtin.template:
src: env.file.j2
dest: /opt/docker-swarm-stack/{{ stack_name }}/.env
mode: "0600"
become: true
This solution will pull all parameters from SSM that match your path, and store them as directory entries to the env_content
fact. Your template is already iterating over the env_content
to pull the key/value pairs.
Hope that helps!