Accessing variables from template file in ansible - variables

I have a task:
- name: Copy celeryconfig.py to "proj_dir/monitor/"
copy:
src="templates/repo/celeryconfig.py.j2"
dest={{proj_dir}}/monitor/celeryconfig.py
run_once: true
Variables that is stored it vars\mail.yml. Inside this file I have rabbitmq_app_user, rabbitmq_app_pass, rabbitmq_app_vhost are defined.
And template file:
BROKER_URL = "apmq://{{rabbitmq_app_user}}:{{rabbitmq_app_pass}}#IP/{{rabbitmq_app_vhost}}"
But when I run the playbook, result looks exactly same as what in inside the template file. Seems the way I try to access to variables that are defined in /vars/main.yml is incorrect. What's the proper way of accessing to variables in my case?

If you want to use jinja template in Ansible you have to use the template module as well. Try something like this:
- name: Copy celeryconfig.py to "proj_dir/monitor/"
template:
src: "repo/celeryconfig.py.j2"
dest: "{{ proj_dir }}/monitor/celeryconfig.py"
run_once: true

Related

I need to copy the content of text file into yaml file at particular line using shell or ansible scripting language

My text file similarly looks like below
ICAgICAidHlwZSI6ICJhY2NlcHQiCiAgICB9CiAgXSwKICAidHJhbnNwb3J0cyI6IHsKICAgICJkb2NrZXIiOiB7CiAgICAgICJpbWFnZS1yZWdpc3RyeS5vcGVuc2hpZnQtaW1hZ2UtcmVnaXN0cnkuc3ZjOjUwMDAvaW1hZ2Utc2lnbmluZyI6IFsKICAgICAgICB7CiAgICAgICAgICAidHlwZSI6ICJzaWduZWRCeSIsCiAgICAgICAgICAia2V5VHlwZSI6ICJHUEdLZXlzIiwKICAgICAgICAgICJrZXlQYXRoIjogIi9ldGMvcGtpL3NpZ24ta2V5L2tleSIKICAgICAgICB9CiAgICAgIF0KIC
and YAML file as below
apiVersion: machineconfiguration.openshift.io/v1
kind: MachineConfig
metadata:
labels:
machineconfiguration.openshift.io/role: worker
name: image-policy
spec:
config:
ignition:
config: {}
security:
tls: {}
timeouts: {}
version: 3.2.0
networkd: {}
passwd: {}
storage:
files:
- contents:
source: data:text/plain;charset=utf-8;base64,<<copy_text_here>>
now I need to copy the content of the text file into the YAML file at the source parameter in place of <<copy_text_here>>.
any suggestions on this?
Thanks in advance
Something like that should do de trick, you load the content of the file with lookup. Then you find the string and replace it with the replace module
---
- hosts: localhost
tasks:
- name: replace
replace:
path: subst.yml
regexp: '<<copy_text_here>>'
replace: "{{lookup('file', 'text.yml')}}"

Using python variables in ansible

I tried this one
---
- name: py
hosts: master
tasks:
- name:
command: /home/vagrant/test.py
register: csvfile
changed_when: false
- debug:
var: csvfile
- name: Create csvfile directories
file:
path: "/tmp/{{ item.host }}_{{ item.app }}"
state: directory
with_dict: "{{ csvfile }}"
Test.py results are:
{'key': 'stdout_lines', 'value': ["{'host': '123', 'app': 'abc'}", "{'host': '2345', 'app': 'def'}", "{'host': '8484', 'app': 'ghju'}", "{'host': '89393', 'app': 'yruru'}"]}
and i'm getting error at "/{{ item.host }}_{{ item.app }}"
Can someone help me?
The registered variable csvfile must have the attribute stdout_lines
csvfile:
stdout_lines:
- {'host': '123', 'app': 'abc'}
- {'host': '2345', 'app': 'def'}
- {'host': '8484', 'app': 'ghju'}
- {'host': '89393', 'app': 'yruru'}
The simple loop should do the job
- name: Create csvfile directories
file:
path: "/tmp/{{ item.host }}_{{ item.app }}"
state: directory
loop: "{{ csvfile.stdout_lines }}"
The key/value decomposition was added very probably by with_dict. Please confirm, update and fix the question. Post the output of the task
- debug:
var: csvfile
There are a bunch of things wrong, so while this is an "answer" because it is too big to fit into a comment here on S.O., it is not the fix to your problem because there is so much wrong with your code.
As your debug output demonstrates, the register: captures the output of the whole task, and not just the output from your program. Thus, at the very least you would need with_dict: "{{ csvfile.stdout }}" but that, too, will not work because the output is not an interoperability format that ansible can use. Just because it is written in python and your script is written in python does not mean they can communicate
You will need to have the test.py call json.dump or json.dumps on the results, and not just print() or repr or whatever it is calling now, so that the output can be parsed by ansible back into an actual data structure in your playbook
Then, what happens next depends on whether you continue to write out each dictionary from test.py on a per-line basis, or you choose to package them all into a list of dictionaries and dump that as JSON
Start by fixing the output from test.py to be parseable by ansible, and we'll go from there
Sumanth, you can try the same approach but using with_items:
- name: Create csvfile directories
file:
path: "/tmp/{{ item.host }}_{{ item.app }}"
state: directory
with_items: "{{ csvfile.stdout_lines }}"

StencilJS: compile scss and copy to dist folder

My goal is to provide a css file in the distribution package which can be used by the consumer if needed.
For that I would like to create a kind of global scss file, but I want to avoid that this style is attached to each component + it also won't be used directly by the components. So for that I would like to create my-style.scss file somewhere in the /src folder.
What would be the best way to compile this file to my-style.css and copy it to the dist folder?
It is possible to specify a global style with Stencil. Simply add the globalStyle property to your stencil.config.js and provide the entry scss file. Your config should look something like this:
const sass = require('#stencil/sass');
exports.config = {
namespace: 'my-component-lib',
outputTargets:[
{
type: 'dist'
},
{
type: 'www',
serviceWorker: false
}
],
globalStyle: 'src/globals/app.scss',
plugins: [
sass()
]
};
exports.devServer = {
root: 'www',
watchGlob: '**/**'
}
The build will successfully compile the scss to dist/my-component-lib.css.
From the docs: https://stenciljs.com/docs/config/#copy
The copy config is an array of objects that defines any files or
folders that should be copied over to the build directory. Each object
in the array must include a src property which can be either an
absolute path, a relative path or a glob pattern. The config can also
provide an optional dest property which can be either an absolute
path or a path relative to the build directory. Also note that any
files within src/assets are automatically copied to www/assets for
convenience.
In the copy config below, it will copy the entire directory from
src/docs-content over to www/docs-content.
Within stencil.config.ts:
copy: [
{ src: 'docs-content' }
]
For example I am copying my css file from src to the build directory and it's totally standalone, e.g. https://github.com/BlazeUI/blaze/blob/master/packages/atoms/stencil.config.ts#L14

How to pull a variable file from S3 in Ansible

My requirement is that I want to dynamically include a variable file in my Ansible script. I can do that by putting following in my ansible task-
- name: Include vars file
include_vars: vars/dev.yml
- name: Some other task
cp: copy something
Above works if I keep the dev.yml in my vars directory. Now I actually do not want to put the dev.yml in the directory, I want to pull it from S3 and then use the variable in it. Something like below-
- name: Get dev file
s3:
bucket: bucket_name
object: object_name
dest: "dest_directory" ## Here I want the destination to be vars/dev.yml
mode: get
aws_access_key: "{{ s3.aws_access_key }}"
aws_access_key: "{{ s3.aws_secret_key }}"
- name: Include vars file
include_vars: vars/dev.yml
- name: Some other task that uses vars in dev.yml
template: render some template using vars in dev.yml and copy to server
The above will actually not work. How do I do this?
Thanks Konstantin Suvorov for help. I just needed to add delegate_to in my task.
- name: Get dev file
s3:
bucket: bucket_name
object: object_name
dest: vars/dev.yml
mode: get
aws_access_key: "{{ s3.aws_access_key }}"
aws_access_key: "{{ s3.aws_secret_key }}"
delegate_to: localhost
- name: Include vars file
include_vars: vars/dev.yml

How to add more than one value to a variable in ansible playbook?

I have defined a value to variable in my playbook as :
war_name: abc
and i m calling this war_name in the roles as :
- name: Download war file
get_url:
url=http://url/directory/packages/tomcat/{{ war_name }}.war
Now the problem is I have to assign 2 values to variable war_name in playbook
like
war_name: abc,xyz
How can i do this in my playbook?
If used with_items as :
- name: Download war file
get_url:
url=http://url/directory/packages/tomcat/{{ item }}.war
with_items:
- abc
- xyz
when: "'server' in app_name"
It results in an error as :
TASK [tomcat : Download war file]
********************************************** failed: [10.x.x.x] (item=abc) => {"failed": true, "item": "abc", "msg": "missing required
arguments: dest"} failed: [10.x.x.x] (item=xyz) => {"failed": true,
"item": "xyz", "msg": "missing required arguments: dest"}
You are missing the dest argument that is required for get_url
Here is the modified version of your task:
- name: Download war file
get_url:
url: "http://url/directory/packages/tomcat/{{ item }}.war"
dest: "/path-where-you-want-to-place/{{ item }}"
with_items:
- abc
- xyz
when: "'server' in app_name"
Hope that help you
what you can do is something like this
war_name:
war1: one
war2: two
This is basically a dictionary. Though i am not sure what actually you wanna do here? I guess you want to place 2 wars at a same location with different names, if that is the case you can actually use with_items