I'm having the following jinja template:
# Configure static IP for Ubuntu 22.04 machine
network:
ethernets:
eth0:
addresses:
- {{ item.new_static_ip }}/24
nameservers:
addresses: [{{ item.netplan_name_servers }}] # Populate this list with the DNS servers necessary.
renderer: networkd
routes:
- to: default
via: {{ item.netplan_router_gateway }}
version: 2
In my task, I have the following:
- name: Copy the template 00-installer-config.yaml over
template:
src: 00-netplan-static-ip-config-ubuntu.j2
dest: /etc/netplan/00-installer-config.yaml
owner: root
group: root
mode: 0644
backup: yes
with_items:
- { new_static_ip: "{{ ansible_default_ipv4.address }}", netplan_name_servers: "1.1.1.1", netplan_router_gateway: "{{ router_gateway_address }}" }
I get an error like this:
FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: 'new_static_ip' is undefined
Is there anything that I'm missing here?
Fixed it by using vars like this:
# Set Static IP using netplan
- name: Copy the template 00-installer-config.yaml over
vars:
new_static_ip: "{{ ansible_default_ipv4.address }}"
netplan_name_servers: "1.1.1.1"
netplan_router_gateway: "{{ router_gateway_address }}"
template:
src: 00-netplan-static-ip-config-ubuntu.j2
dest: /etc/netplan/00-installer-config.yaml
owner: root
group: root
mode: 0644
backup: yes
Related
I have been trying to get this conditional to work for a few hours now.
The solution is eluding me.
The "when" is always evaluating as false.
This is confusing as template/src works perfectly.
- name: Copy PHP Pool Config
template:
src: "{{ src_conf }}"
dest: /etc/php/{{ php_version }}/fpm/pool.d/{{ user.name }}.conf
mode: u=rw,g=r,o=r
with_flattened:
- "{{ users|default([]) }}"
notify: reload PhpFpm
vars:
user: "{{ item }}"
src_conf: "../files/etc/php/fpm/pool.d/{{ group_names | first }}/{{ user.name }}.conf"
tags:
- php
when: src_conf is exists
This works as expected if I remove the "when".
The issue is not all "{{ user.name }}.conf" files exist.
Does "when: src_conf is exists" search in different place?
Update:
I also tried it with location_action, but it still resulted in false.
- name: Copy PHP Pool Config files
local_action: stat path="../../files/etc/php/fpm/pool.d/{{ group_names | first }}/{{ user.name }}.conf"
register: phpPools
with_flattened:
- "{{ users|default([]) }}"
become: no
vars:
user: "{{ item }}"
tags:
- php
- name: Copy PHP Pool Config
template:
src: item.invocation.module_args.path
dest: /etc/php/{{ php_version }}/fpm/pool.d/{{ user.name }}.conf
mode: u=rw,g=r,o=r
with_flattened:
- "{{ phpPools.results }}"
notify: reload PhpFpm
vars:
user: "{{ item.item }}"
tags:
- php
when: item.stat.exists == true
I'd like to share a custom inventory plugin across multiple playbooks and users.
Is it possible to host a custom inventory plugin on git and the like roles with requirements.yml do something like:
ansible-galaxy install -r requirements.yml
I tried to embbed it in a role using:
/myrole/library/inventory_plugins/custom_inventory.py
/myrole/plugins/inventory_plugins/custom_inventory.py
/myrole/inventory_plugins/custom_inventory.py
but so far no luck.
Q: "Is it possible to install custom Ansible plugin from git?"
A: Yes. It's possible. For example
1) Download and extract the plugins
vars:
ma_src_path: "/usr/local/ansible/src"
ma_plugins_path: "/usr/local/ansible/plugins"
map_mitogen_ver: 0.2.8
map_mitogen_sha256: "sha256:1bfca66bcc522346c9167a3a9829feac5ee3b84431e49354fb780e4b9a4b0eee"
ma_plugins:
- archive: mitogen-{{ map_mitogen_ver }}.tar.gz
archive_url: https://networkgenomics.com/try/mitogen-{{ map_mitogen_ver }}.tar.gz
checksum: "{{ map_mitogen_sha256 }}"
plugins:
- path: mitogen-{{ map_mitogen_ver }}/ansible_mitogen/plugins/strategy
ini_key: strategy_plugins
enable: true
tasks:
- name: "plugins: Download archives"
get_url:
url: "{{ item.archive_url }}"
dest: "{{ ma_src_path }}"
checksum: "{{ item.checksum }}"
loop: "{{ ma_plugins }}"
- name: "plugins: Extract archives"
unarchive:
src: "{{ ma_src_path }}/{{ item.archive }}"
dest: "{{ ma_plugins_path }}"
loop: "{{ ma_plugins }}"
2) Configure the plugins with template ansible-plugins.cfg.j2
vars:
ma_config:
- path: "/etc/ansible/ansible.cfg"
template: "ansible-plugins.cfg.j2"
owner: "root"
group: "root"
mode: "0644"
config:
- { section: "defaults", key: "inventory", value: "/etc/ansible/hosts" }
- { section: "defaults", key: "strategy", value: "mitogen_linear" }
tasks:
- name: "configure: Ansible configuration from template"
template:
src: "{{ item.template }}"
dest: "{{ item.path }}"
owner: "{{ item.owner }}"
group: "{{ item.group }}"
mode: "{{ item.mode }}"
backup: "{{ ma_backup_conf }}"
loop: "{{ ma_config }}"
when: ma_config|length > 0
See the complete role at Ansible Galaxy.
How do i loop using "with_fileglob". I am trying to copy files matching wildcard, but with different permissions at the destination.
- hosts: myhost
gather_facts: no
tasks:
- name: Ansible copy test
copy:
src: "{{ item.origin }}"
dest: /home/user1/tmps/
owner: user1
mode: "{{item.mode}}"
with_fileglob:
- { origin: '/tmp/hello*', mode: '640'}
- { origin: '/tmp/hi*', mode: '600'}
It throws error as below:
An exception occurred during task execution. To see the full traceback, use
-vvv. The error was: AttributeError: 'dict' object has no attribute 'rfind'
I think the cleanest way is to implement this, would be a nested loop with include_tasks.
Where you main playbook file contains:
...
vars:
my_patterns:
- origin: "/tmp/hello*"
mode: "0640"
- origin: "/tmp/hi*"
mode: "0600"
tasks:
- include_tasks: "my_glob.yml"
with_items: "{{ my_patterns }}"
loop_control:
loop_var: my_pattern
...
and a subordinate my_glob.yml-tasks file:
---
- name: Ansible copy test
copy:
src: "{{ item }}"
dest: /home/user1/tmps/
owner: user1
mode: "{{ my_pattern.mode }}"
with_fileglob: "{{ my_pattern.origin }}"
Alternative method
Using Jinja2 to populate a list of objects { 'path': '...', 'mode': '...' }' based on fileglob-lookup plugin results.
vars:
my_patterns:
- origin: '/tmp/hello*'
mode: '0640'
- origin: '/tmp/hi*'
mode: '0600'
tasks:
- copy:
src: "{{ item.paht }}"
dest: /home/user1/tmps/
owner: user1
mode: "{{ item.mode }}"
with_items: "[{% for match in my_patterns %}{% for file in lookup('fileglob', match.origin, wantlist=True) %}{ 'path':'{{ file }}','mode':'{{ match.mode }}'}{% if not loop.last %},{% endif %}{% endfor %}{% if not loop.last %},{% endif %}{% endfor %}]"
The above works if patterns are matched, you'd need to add checks if the results are not empty.
according to the documentation, you cant pass to the fileglob a dictionary variable, adding the desired file permissions after copy as you have attempted (i mean the declaration { origin: '/tmp/hello*', mode: '640'}).
simple module call that will work for you:
- hosts: localhost
gather_facts: no
tasks:
- name: Ansible copy test
copy:
src: "{{ item }}"
dest: /SAMBA_ROOT/TEMP/
owner: root
with_fileglob:
- '/tmp/hello*'
- '/tmp/hi*'
if you want to have each of the file group have different file permissions, i suggest you use 2 different calls where the mode is "hardcoded", for example:
- hosts: localhost
gather_facts: no
tasks:
- name: copy hello files
copy:
src: "{{ item }}"
dest: /SAMBA_ROOT/TEMP/
owner: root
mode: 0640
with_fileglob:
- '/tmp/hello*'
- name: copy hi files
copy:
src: "{{ item }}"
dest: /SAMBA_ROOT/TEMP/
owner: root
mode: 0600
with_fileglob:
- '/tmp/hi*'
I'm trying to use templates with different sets of variables for each itteration of a determined set of tasks. For example, in one of the tasks I'd like to set specific values for postgres:
- name: Define values for postgres-ds
template:
src: postgres-ds.xml.j2
dest: /opt/ear_{{ instance_control.value }}/postgres-ds.xml
vars: "{{ postgres_desenv }}"
notify: Restart Service
In role/vars/main.yaml, I defined:
postgres_desenv:
var1: somevalue
var2: someothervalue
...
Still, I get the following error:
fatal: [rmt]: FAILED! => {
"failed": true,
"reason": "Vars in a Task must be specified as a dictionary, or a list of dictionaries
...
When I try to use the same variable in another context, it works fine:
- debug:
msg: "{{ item.key }} - {{ item.value }}"
with_dict: "{{ postgres_desenv }}"
I tried following the answers to this question but I'm still stuck.
My next step is to use a variable to call the variable inside vars, something like:
- name: Define values for postgres-ds
template:
src: postgres-ds.xml.j2
dest: /opt/ear_{{ instance_control.value }}/postgres-ds.xml
vars: postgres_{{ another_var }}
notify: Restart Service
You can do something like this:
- name: Define values for postgres-ds
template:
src: postgres-ds.xml.j2
dest: /opt/ear_{{ instance_control.value }}/postgres-ds.xml
vars:
settings: "{{ postgres_desenv }}"
notify: Restart Service
Then within the template you could refer to, e.g.,
{{ settings.var1 }}
In my case, following the answer above, all i had to do is using {{ item.value.(mydictkey) }} and that's it
In my case i defined a global variable like so:
vars:
vhosts:
web1
port: 8080
dir: /mywebsite
web2:
...
Then in the task I used:
- name: Render template
template:
src: "../templates/httpd.vhost.conf.j2" # Local template
dest: "/etc/httpd/conf.d/{{ item.key }}.conf" # Remote destination
owner: root
group: root
mode: 644
with_dict: "{{ vhosts }}"
In the template I used:
<VirtualHost *:{{ item.value.port }}>
DocumentRoot /var/www/{{ item.value.dir }}
</VirtualHost>
If postgres_desenv is defined in vars/main.yml that will be loaded automatically and be available to the role and rest of the playbook. Why do you have to specify that again using "vars" option in the template module task?
I'm trying to fetch the names of host groups in Ansible that have a specific prefix. Right now, I'm trying to delegate a template task to servers under host groups with the prefix "config_".
I'm using json_query which uses JMESPath expressions. The query however is incorrect. Can anyone guess what I'm missing?
- name: Create configsvr config file
template: src=mongod.conf.j2 dest={{ mongod.conf.path }} owner=mongod group=mongod mode=0600
delegate_to: "{{ groups|json_query([?starts_with(#, `config_`)]) }}"
Error msg:
FAILED! => {"failed": true, "msg": "template error while templating string: unexpected char u'?' at 22. String: {{ groups|json_query([?starts_with(#, `config_m`)]) }}"}
You should simply use built-in patterns to select your target hosts.
---
- hosts: conf_*
tasks:
- name: Create configsvr config file
template:
src: mongod.conf.j2
dest: "{{ mongod.conf.path }}"
owner: mongod
group: mongod
mode: 0600
You can improve your inventory by using groups of groups, like so:
[conf:children]
conf_a
conf_b
conf_c
[conf_a]
srv1
[conf_b]
srv2
[conf_c]
srv3
And then target conf group in your playbook:
---
- hosts: conf
tasks:
- name: Create configsvr config file
template:
src: mongod.conf.j2
dest: "{{ mongod.conf.path }}"
owner: mongod
group: mongod
mode: 0600