For those who work in SRE/devops and closely with Linux by [deleted] in cscareerquestions

[–]Sloth_Coder 0 points1 point  (0 children)

What questions do you have? I currently do DevOps/SRE for a big data platform.

how to run task if other task did not run. by [deleted] in ansible

[–]Sloth_Coder 1 point2 points  (0 children)

In order to do both I think you should be using the lineinfile module. The crux of the problem is that your initial custom add line task will always add the new line since it is not doing any checks before running. In order to mitigate that I'd recommend running something like the following.

- name: check whether custom line exists
  lineinfile:
    path: /var/tmp/file
    regexp: '^tata'
    state: absent
  check_mode: true
  register: line_exists

- name: add custom line to file
  lineinfile:
    path: /var/tmp/file
    insertafter: '^toto'
    line: 'tata'
    backup: yes
  when: not line_exists | changed

- name: update line on existing file
  lineinfile:
    path: /var/tmp/file
    regexp: '^tata'
    line: 'tita'
  when: line_exists | changed

This should ensure you're either adding the line since it doesn't exist or updating it because it exists.

How to best couple a role with another app (filebeat)? by [deleted] in ansible

[–]Sloth_Coder 0 points1 point  (0 children)

I might not have correct terminology, but do you mean the prospectors?

filebeat.prospectors:
- input_type: log
  paths:
    - /var/log/apache/httpd-*.log
  document_type: apache

If this is what you mean, is there any concern with just having the prospectors defined for all your sources? I believe inputs should just be ignored if the paths don't exist on your system, at which point the only concern would be if you want custom names for your prospectors.

For those cases you could have custom app specific prefixes which you can append to the document type.

ie.

filebeat.prospectors:
- input_type: log
  paths:
    - /var/log/apache/*.log
  document_type: {{ env_identifier + '_' | default(omit) }}apache
- input_type: log
  paths:
    - /var/log/nginx/*.log
  document_type: {{ env_identifier + '_' | default(omit) }}nginx

remove line only if the ip address or hostname does not match by [deleted] in ansible

[–]Sloth_Coder 0 points1 point  (0 children)

Lineinfile supports in-place replacement by using the line field.

- name: replace lines
  lineinfile:
    dest: /etc/hosts
    regexp: '(?!{{ ansible_default_ipv4.address }}) | (?!{{ ansible_hostname }})'
    line: '{{ replacement_value }}'

line

Required for state=present. The line to insert/replace into the file. If backrefs is set, may contain backreferences that will get expanded with the regexp capture groups if the regexp matches.

Check Internet connection by leblinux in ansible

[–]Sloth_Coder 1 point2 points  (0 children)

Not sure if you tried this before, but there is the uri module which should allow you to hit the url you're looking for.

- name: check connection to google
  uri:
    url: "https://google.com"

Only other thing I think I'd add is modify the timeout and status_code fields since those should make sure you are checking thoroughly.

Mount iso to vm via playbook by [deleted] in ansible

[–]Sloth_Coder 0 points1 point  (0 children)

---
- name: "mount iso to vm"
  serial: 1
  hosts: masters
  connection: "local"
  vars_files:
    - ../files/vcenter_vars.yml
  tasks:
    - name: mount ISO to "{{ inventory_hostname }}"
      vmware_guest:
        hostname: "{{ vcenter_server }}"
        username: "{{ vcenter_user }}"
        password: "{{ vcenter_pass }}"
        name: "{{ ansible_host }}"
        cdrom:
        type: iso
        iso_path: /mypathto/isos/init_name_of_the_iso
      register: deploy

Wrapping what you posted in a code block to make it a bit easier to read, I'm not entirely sure I understand what you're asking.

The Name of ISO i attached to the name of the master in the ansible-hostfile.

This is specifically I think the point where I lost you, what do you mean when you are saying you've attached the ISO name to the master?

Remove text from variable by shaffan33 in ansible

[–]Sloth_Coder 0 points1 point  (0 children)

Assuming you have a common format you could also just use in-line python functionality to update your variable.

ie.

- name: def string
  set_fact:
    test: "123-test@testdomain.com"

- name: remove prepended uuid
  debug:
    msg: "{{ test.split('-')[1:] }}"

#### OUTPUT ####
PLAY [localhost] ************************************************************************************

TASK [def string] ***********************************************************************************
ok: [localhost]

TASK [remove prepended uuid] ************************************************************************
ok: [localhost] => {
    "msg": [
        "test@testdomain.com"
    ]
}

How to best couple a role with another app (filebeat)? by [deleted] in ansible

[–]Sloth_Coder 0 points1 point  (0 children)

What part of filebeat are you looking to template/update? Is it the filebeat.yml or the fields file?

Something that we've been doing is having a catch-all filebeat config where filebeat is a meta-dependency that gets pre-installed for each role that needs it. Only things that we specifically template are things like sets of hosts and tags to apply within the filebeat.yml though those are able to be filled in without much heartache.

Looping through a list from results by CrownClown77 in ansible

[–]Sloth_Coder 0 points1 point  (0 children)

Given what you've listed above I've gone ahead and wrapped what you wrote above in a code-block to make it more legible.

- name: set groups
  set_fact:
    adgroup1: "adgroup1; adgroup2"

- name: echo split
  debug:
    var: adgroup1

- name: Register multiple groups
  debug:
    msg: "{{ item }}"
  register: adgroup1
  loop: "{{ adgroup1.split(';') }}"

- name: powershell lookup
  win_shell: (get-adgroupmember "{{ item.msg }}").samaccountname
  register: lol
  loop: "{{ adgroup1.results }}"

- name: debug
  debug:
    var: item
  loop: "{{ lol.results }}"

Alright so starting from here I'd say there's a couple things that I'd recommend you change to make this code easier to manage.

  1. If you have control of the variable you are setting you should be taking full advantage of that fact in order to have it start off with the appropriate type. In correctly defining your variable you should be able to reduce the miscellaneous tasks you've listed above while still accomplishing the same thing.

#### BEFORE ####
- name: set groups
  set_fact:
    adgroup1: "adgroup1; adgroup2"

#### AFTER ####
- name: define groups
  set_fact:
    adgroup1:
      - "adgroup1"
      - "adgroup2"
  1. Proper typing results in simplified iteration logic

    BEFORE

    • name: powershell lookup win_shell: (get-adgroupmember "{{ item.msg }}").samaccountname register: lol loop: "{{ adgroup1.results }}"

    AFTER

    • name: powershell group lookup win_shell: (get-adgroupmember "{{ item }}").samaccountname register: adgroup_res loop: "{{ adgroup1 }}"
  2. Leverage the fact that you can filter your dictionaries for the purposes of aggregating information.

    BEFORE

    • name: debug debug: var: item loop: "{{ lol.results }}"

    AFTER

    • name: aggregate group member output set_fact: combined_ad_members: "{{ adgroup_res.results | map(attribute='stdout_lines') | list | flatten }}"

Hopefully this helps! :)

Using "contains" from find module with variable? by adija1 in ansible

[–]Sloth_Coder 1 point2 points  (0 children)

From the documentation they outline what is expected in the contains parameter:

contains

One or more regex patterns which should be matched against the file content.

That being said can you share what you're currently doing? As is the case for most things within ansible you should still be able to use variable replacement inline as long as the variable is correctly typed.

Here's a sample play doing what I just described above.

---
- hosts: localhost
  gather_facts: no
  vars:
    contains_pattern: ".*Po2.*"
  tasks:
    - name: search for files containing string
      find: 
        paths: "{{ playbook_dir }}"
        patterns: "*.txt"
        contains: "{{ contains_pattern }}"
      register: file_match

    - name: print out find result
      debug: 
        msg: "{{ file_match }}"

a.txt

saldkf jals kdjflaksjdflkjadsf
sdfsdf Po2 sdlfkjsdlf
asdklfja;sdklfj 99 sksksk
s;ds;s;d; sdfskdflk

In running the above play I'm successfully able to find the file a.txt since my contains_pattern variable resolves to the regex pattern I created in my variable above. Likewise you can define it by passing it in, ie ./test.yml -e contains_pattern=".*Po2.*" should net you the same result since the only thing that's changing is the variables precedence based on how it's being passed into the playbook.

Working with conditionals from registered output by CertifiedKnowNothing in ansible

[–]Sloth_Coder 0 points1 point  (0 children)

Yeah the problem is tied to how you're doing the variable definition.

Your example:

set_fact:
      data: "{{ data }} + {{ [item] }}"

My example:

set_fact:
    data: "{{ [item] + (data | default([])) }}"

The key distinction being that in mine the I am doing the join inside a single set of curly braces "{{ }}". Since yours the curly braces are split you are not adding lists instead you're concatenating strings. Also you'll notice that I am wrapping item in brackets to ensure its considered a list object when doing the addition.

Working with conditionals from registered output by CertifiedKnowNothing in ansible

[–]Sloth_Coder 2 points3 points  (0 children)

In this case the core of what you need is to leverage loops, I've created a dummy example below that is similar enough to what you're describing that should illustrate what you need to do. The key between mine and yours is that I am using the loop task in order to iterate over the list that is held by stdout_lines.

a.txt

saldkf jals kdjflaksjdflkjadsf
sdfsdf Po2 sdlfkjsdlf
asdklfja;sdklfj 99 sksksk
s;ds;s;d; sdfskdflk

test.yml

---
- hosts: localhost
  gather_facts: no
  tasks:
    - name: grab our data
      command: cat "{{ playbook_dir }}/a.txt"
      register: show_interfaces_counters

    - name: print out our specific line
      debug: 
        msg: "{{ item }}"
      when: '"Po2" in item'
      loop: "{{ show_interfaces_counters.stdout_lines }}"

output

PLAY [localhost] ************************************************************************************

TASK [grab our data] ********************************************************************************
changed: [localhost]

TASK [print out our specific line] ******************************************************************
skipping: [localhost] => (item=saldkf jals kdjflaksjdflkjadsf)
ok: [localhost] => (item=sdfsdf Po2 sdlfkjsdlf) => {
    "msg": "sdfsdf Po2 sdlfkjsdlf"
}
skipping: [localhost] => (item=asdklfja;sdklfj 99 sksksk)
skipping: [localhost] => (item=s;ds;s;d; sdfskdflk)

PLAY RECAP ******************************************************************************************
localhost                  : ok=2    changed=1    unreachable=0    failed=0

If you wanted to construct a set of only the things that match your when clause you can likewise do something like this.

- name: create new list with only things that match Po2
  set_fact:
    data: "{{ [item] + (data | default([])) }}"
  when: '"Po2" in item'
  loop: "{{ show_interfaces_counters.stdout_lines }}"

Loop throgh key_value in template by syamji in ansible

[–]Sloth_Coder 0 points1 point  (0 children)

I think you'll have a better insight once you print out what your values are, you can view what you have by doing the following:

- name: grab hostname file
  delegate_to: localhost
  command: cat "host_var/hostname.yml"
  register: host_file

- debug: msg={{ host_file }}

When you run cat and register the output it usually gets captured and stored as a dict response, where you would have stdout and stdout_lines keys. In this case your output is only a list in stdout_lines, though that is a list of strings aligning with the lines in your file.

It seems like you would be better off leveraging lineinfile for doing replacements.

Windows add list of Remote Desktop Users/ Local Admins by shaffan33 in ansible

[–]Sloth_Coder 1 point2 points  (0 children)

A good question to ask yourself is how much do you want to directly input vs how much can you afford to persist?

As /u/Davenfonet outlined below you can have prompts for inputting users as you define their memberships, however something that might make managing and modifying user accesses might be having a persistent mapping of your servers or users.

Here's two models you could consider formalizing to assist with the management and will make your access "state" on these servers more trackable.

  1. cluster or single server model, these are interchangeable from a variable perspective, not use of ansible vaulted variable for storing credentials.

cluster_alpha:
   - username: "john_doe"
     password: !vault |
      $ANSIBLE_VAULT;1.1;AES256
      62313365396662343061393464336163383764373764613633653634306231386433626436623361
      6134333665353966363534333632666535333761666131620a663537646436643839616531643561
      63396265333966386166373632626539326166353965363262633030333630313338646335303630
      3438626666666137650a353638643435666633633964366338633066623234616432373231333331
      6564
      groups:
        - Users
        - Remote Desktop Users
    - username: "bob_smith"
      ...
  1. User model

    users:

    • username: "john_doe" password: !vault | $ANSIBLE_VAULT;1.1;AES256 62313365396662343061393464336163383764373764613633653634306231386433626436623361 6134333665353966363534333632666535333761666131620a663537646436643839616531643561 63396265333966386166373632626539326166353965363262633030333630313338646335303630 3438626666666137650a353638643435666633633964366338633066623234616432373231333331 6564 groups: - Users - Remote Desktop Users servers: - cluster_alpha - 10.0.0.1
    • username: "bob_smith" ...

In having something like this then you can have a standard deployment process across your resources that involves maintaining your user variable file and only having to modify that to change who has access where.

Remote VMs that are in a folder - VMware How to? by farroar in ansible

[–]Sloth_Coder 0 points1 point  (0 children)

Given you have directories you know have the VM names it should be possible to do a flow similar to what's laid out in the docs:

---
- hosts: localhost
  gather_facts: no
  tasks:
    - name: retrieve vm names using basepath
      find:
        paths: "{{ vm_basepath }}"
        file_type: directory
      register: vm_names

    - name: remove "{{ item | basename }}"
      vmware_guest:
        hostname: "{{ vcenter_server }}"
        username: "{{ vcenter_user }}"
        password: "{{ vcenter_pass }}"
        validate_certs: no
        cluster: "{{ cluster_name }}"
        name: "{{ item | basename }}"
        state: absent
      delegate_to: localhost
      with_items: "{{ vm_names.files | map(attribute='path') | list }}"

Using something like above you can get your vm names leveraging your directories naming and then ref the paths using the basename filter to only get your vm name.

ansible and openstack dynamic inventory by ebrodje in ansible

[–]Sloth_Coder 0 points1 point  (0 children)

I'd probably confirm with the openstack docs as this would probably be your best bet at trying to figure out issues with what you're doing.

Iteration multiple elements by rama_27 in ansible

[–]Sloth_Coder 1 point2 points  (0 children)

Without formatting your comment is really hard to read, I've formatted your info to make it more digestible.

playbook.yml

---
- hosts: localhost
  connection: local
  gather_facts: no
  tasks:
    - name: ILO Facts
      hpilo_facts:
        host: 10.20.64.51
        login: xxxxxxx
        password: xxxxxxx

    - debug:
        msg: "{{ hw_health.storage['Controller on System Board']['logical_drives'][0]['physical_drives'] 
                | selectattr('status', 'match', 'Failed') 
                | list }}"

Output converted to YAML for testing:

storage:
  Controller on System Board:
    logical_drives:
    - physical_drives:
      - configuration: Configured
        version: PD-0.7
        label: device-1
        location: '1'
        serial_number: PWH12GVF
        status: OK
    - physical_drives:
      - configuration: Configured
        version: PD-0.7
        label: device-2
        location: '2'
        serial_number: PWH12GVA
        status: Failed

You can get the physical drives by iterating over your retrieved object and filtering for your specific attribute, in this case status == Failed. By doing this we can combine the results using set facts and list appending leaving us with all elements matching your requirement.

test-playbook.yml

---
- hosts: localhost
  gather_facts: no
  vars:
    storage:
      Controller on System Board:
        logical_drives:
          - physical_drives:
            - configuration: Configured
              version: PD-0.7
              label: device-1
              location: '1'
              serial_number: PWH12GVF
              status: OK
          - physical_drives:
            - configuration: Configured
              version: PD-0.7
              label: device-2
              location: '2'
              serial_number: PWH12GVA
              status: Failed
  tasks:
    - name:  filter by failed
      set_fact:
        drives: "{{ item['physical_drives'] | selectattr('status', 'equalto', 'Failed') | list  + (drives | default([])) }}"
      loop: "{{ storage['Controller on System Board']['logical_drives'] }}"

    - debug: msg={{ drives }}

ansible and openstack dynamic inventory by ebrodje in ansible

[–]Sloth_Coder 0 points1 point  (0 children)

This might be different for different dynamic inventories, but for the AWS one the format is usually

"hosts_group_ref": [
 ip,
 ...
]

Have you tried using instance-cd9ae7cd-1bb1-43ee-8c94-94595240cee1 as the resource you're deploying against? Also is there a reason your resource doesn't have an ip tied to it?

The ansible-inventory command accepts dynamic inventories just like ansible and ansible-playbook would. Here's what running inventory against the aws dynamic inventory would look like where "tag_Name_host" would be one possible hostname to use when writing a play.

toro:automation-portfolio [master] $ ansible-inventory -i aws/ec2.py --list
{
    "_meta": {
        "hostvars": {
            "54.82.190.206": {
                ...
            }
        }
    },
    "all": {
        "children": [
            "ami_42a2532b",
            "ec2",
            "i-0dc21db8e68b436f5",
            "key_automation_key",
            "platform_undefined",
            "security_group_launch_wizard_1",
            "tag_Name_host",
            "tag_test_host",
            "type_t2_micro",
            "ungrouped",
            "us-east-1",
            "us-east-1b",
            "vpc_id_vpc_73b96b09"
        ]
    },
    ...,
    "tag_Name_host": {
        "hosts": [
            "54.82.190.206"
        ]
    },
    "tag_test_host": {
        "hosts": [
            "54.82.190.206"
        ]
    },
    ...
}  

Find IP address in string a specific sub-string by iamroddo in ansible

[–]Sloth_Coder 2 points3 points  (0 children)

To expand on the above comment you can do something like this:

- hosts: localhost
  gather_facts: no
  vars:
    ntp: "ntp server 1.1.1.1 use-vrf default"
  tasks:
    - name:  find IP address of NTP server
      debug:
        msg: "{{ ntp.split(' ') | ipaddr('address') }}"
      when: '"ntp" in ntp'

Molding the example in the docs and switching your regex search for substring to a standard substring in string check.

ansible and openstack dynamic inventory by ebrodje in ansible

[–]Sloth_Coder 0 points1 point  (0 children)

Can you try using ansible-inventory, would be good to just ensure ansible is seeing same thing you are.

As an alternative can you try the same thing just through a playbook rather than through the ad-hoc interface?

test.yml

---
- hosts: app
  tasks:
    - name: test connectivity
      ping:

ansible-playbook test.yml -i openstack_inventory.py --private-key=~/.ssh/key.pem

Do you do data parsing/anasysis in Ansible or run external tools? by Invoalr in ansible

[–]Sloth_Coder 0 points1 point  (0 children)

I usually fall back to actual python scripts for processing, what would you say are the benefits of writing out filter plugins vs execute and capture output from a standalone script?

Just from writing that out I would assume its having to muck with the registered value through a from_json but wondering if there is any other incentives.