108 messages
Adnanabout 3 years ago
Hi. With sso and cross-account access, some of the options are:
• use users, groups and permission sets
• use users, groups and custom roles across accounts
Both can be managed via terraform, but what might be benefits or drawbacks of each?
Why would we choose one over the other?
• use users, groups and permission sets
• use users, groups and custom roles across accounts
Both can be managed via terraform, but what might be benefits or drawbacks of each?
Why would we choose one over the other?
Vinko Vrsalovicabout 3 years ago
~ task_definition = "arn:aws:ecs:eu-north-1:116778842250:task-definition/app-back-dev:23" -> "arn:aws:ecs:eu-north-1:116778842250:task-definition/app-back-dev:20"I added some CI/CD deployment of ECS tasks on Github Actions. It creates the new version based on the code using the aws CLI. When I come back to terraform to change something else, I see the above, so it downgrades the task version, even after a
terraform refreshVinko Vrsalovicabout 3 years ago
I think the problem is that the value is stored in the task definition, which is what's rebuilt in Github Actions and Terraform is not catching up even after a refresh. Can I somehow import the Github Actions task definition into my terraform state? Refresh is not cutting it
Jonas Steinbergabout 3 years ago
In case anyone has ever wondered: a Terraform Cloud annual contract provisioned for about 10K - 15K applies per month works out to approximately $40 USD/apply. That's not a guess.
Jonas Steinbergabout 3 years ago
Does anyone have recommendations on undrifting a "medium-sized" number of resources across numerous environments? This would be something on the order of say between 5 and 10 resource configurations that are drifted from current state across about 15 environments. I'm not sure if terraform import will help in this case? Also not sure if there is a better option.
Ericabout 3 years ago
Is there a good mechanism for "booping" a bug report?
rssabout 3 years ago(edited)
v1.3.7
1.3.7 (January 04, 2023)
BUG FIXES:
Fix exact version constraint parsing for modules using prerelease versions (#32377)
Prevent panic when a provider returns a null block value during refresh which is used as configuration via ignore_changes (<a href="https://github.com/hashicorp/terraform/issues/32428"...
1.3.7 (January 04, 2023)
BUG FIXES:
Fix exact version constraint parsing for modules using prerelease versions (#32377)
Prevent panic when a provider returns a null block value during refresh which is used as configuration via ignore_changes (<a href="https://github.com/hashicorp/terraform/issues/32428"...
Ray Bothaabout 3 years ago
Is anyone managing google workspace in terraform? Noticed they released a provider but it's not really clear to me in what situation that would be a good pattern
James Clintonabout 3 years ago
Hello * - does anyone know how to configure this ALB module in Terraform to have set Target Group attributes such as Stickiness? I have multiple instances in the group and need to pin the request to a healthy instance they first land on. https://github.com/terraform-aws-modules/terraform-aws-alb
oladabout 3 years ago
Hello,
Is there any mechanism in Terraform that let you run some tasks in between
Example task could be validate Change Request number or validate image in ECR is scanned&blessed and once validated successfully, then proceed from plan to apply. Appreciate any info.
Is there any mechanism in Terraform that let you run some tasks in between
terraform plan and terraform apply ? Trying to enforce some policies (not via sentinel) before provisioning AWS resources.Example task could be validate Change Request number or validate image in ECR is scanned&blessed and once validated successfully, then proceed from plan to apply. Appreciate any info.
PePe Amengualabout 3 years ago
Anyone here have implemented/used Drift detection for Iac (terraform base)? what was the user flow, did it work well, if not why? autoremediation was a thing?
sripeabout 3 years ago
hello all, looking for some guidance here, i m trying to deploy a k8s resource using terraform as below and have been sending
karpenter_instance_family = ["r5d","r5ad","r6gd","r6id"] as input to this and i m struggling to get this work. any suggestions please. error in the threadresource "kubectl_manifest" "default-pa" {
yaml_body = <<YAML
apiVersion: <http://karpenter.sh/v1alpha5|karpenter.sh/v1alpha5>
kind: Provisioner
metadata:
name: default-pa
spec:
requirements:
- key: karpenter.k8s.aws/instance-family
operator: In
values: ${var.karpenter_instance_family}
limits:
resources:
cpu: 1000
provider:
launchTemplate: 'karpenter'
subnetSelector:
<http://kubernetes.io/cluster/karpenter|kubernetes.io/cluster/karpenter>: '*'
labels:
type: karpenter
provisioner: default-pa
ttlSecondsAfterEmpty: 30
ttlSecondsUntilExpired: 2592000
YAML
}
variable "karpenter_instance_family" {
description = "Instance family"
type = list(string)
default = []
}David Lundgrenabout 3 years ago
Would I be able to get a review for https://github.com/cloudposse/terraform-aws-ec2-instance/pull/148 I currently have to manually set the
ssm_patch_manager_iam_policy_arn and can't use the ssm patch s3 bucket (as-is) easily on govcloud instancesmadoabout 3 years ago
I want to prepare for terraform certification, any recommendations? Material or guide welcome!
Bart Coddensabout 3 years ago
Hi al, I am using the module: terraform-aws-modules/vpc/aws and here I define one public subnet:
Bart Coddensabout 3 years ago
public_subnets = ["10.10.1.0/24"]
Bart Coddensabout 3 years ago
When I want to refer to this in my ec2 instance, it fails
Bart Coddensabout 3 years ago
subnet = module.vpc.public_subnets
Bart Coddensabout 3 years ago
Do I miss something ?
Marco Frömbgenabout 3 years ago
Hello everyone! I would like to get your opinion on the following issue and proposed implementation if anyone has time(https://github.com/cloudposse/terraform-aws-ecs-alb-service-task/issues/184).
Ramon de la Cruz Arizaabout 3 years ago
Hello!! Will this issue be addressed? https://github.com/cloudposse/terraform-aws-documentdb-cluster/issues/19 we can’t attach more than 1 SG in the VPC side for DocumentDB clusters
Thanks!!
Thanks!!
Stephen Bennettabout 3 years ago
Hi, is there a simple way to make a terraform resource with a dynamic lifecycle policy?
ie: I want my production s3 buckets to have
ie: I want my production s3 buckets to have
prevent_destory = true and all others to have false ive tried variables and adding a count = to crreate it. But both error.Alex Atkinsonabout 3 years ago
Checkout this dynamic backend configurator with env0. Can't put vars in backend config, it's fine. :)
https://github.com/env0/custom-flows-examples/blob/main/dynamic-backend/README.md
https://github.com/env0/custom-flows-examples/blob/main/dynamic-backend/README.md
Soren Jensenabout 3 years ago
I got an issue with the S3 etag. I'm building a custom authorizer lambda function like this, to make sure it's always rebuilt. The build.sh is checking out another repo and building the lambda zip.
The zip is then uploaded to an S3 bucket
In the
Applying the terraform code I end up with the following error on the etag
Anyone got an idea why I get this error? I got a feel it's because the zip exists and the value is taken before the build is complete but not sure.. Any help will be much appreciated
resource "null_resource" "custom_authorizer_build" {
triggers = {
always_run = timestamp()
}
provisioner "local-exec" {
command = "bash ${path.module}/../build.sh"The zip is then uploaded to an S3 bucket
resource "aws_s3_object" "custom_authorizer_s3_object" {
bucket = aws_s3_bucket.lambda_bucket.id
key = "custom-authorizer.zip"
source = "${path.module}/../dist/custom-authorizer/custom-authorizer.zip"
etag = fileexists("${path.module}/../dist/custom-authorizer/custom-authorizer.zip") ? filemd5("${path.module}/../dist/custom-authorizer/custom-authorizer.zip") : ""
depends_on = [
null_resource.custom_authorizer_build
]
}In the
aws_lambda_function I got the following like source_code_hash = aws_s3_object.custom_authorizer_s3_object.etagApplying the terraform code I end up with the following error on the etag
╷
│ Error: Provider produced inconsistent final plan
│
│ When expanding the plan for aws_s3_object.custom_authorizer_s3_object to include new values learned so far during apply, provider "<http://registry.terraform.io/hashicorp/aws|registry.terraform.io/hashicorp/aws>" produced an invalid
│ new value for .etag: was cty.StringVal("2be93e215ac8a6f3b243ceac4550e124"), but now cty.StringVal("36b50bace3da160d46f259118d41d359").
│
│ This is a bug in the provider, which should be reported in the provider's own issue tracker.
╵ Anyone got an idea why I get this error? I got a feel it's because the zip exists and the value is taken before the build is complete but not sure.. Any help will be much appreciated
Rayenabout 3 years ago
Hello everyone, I'm new with terraform and I'm using cloudposse modules. My question is how I create infrastructure when I have architecture like this
Rayenabout 3 years ago
not seperate folders with each module inside
Bradabout 3 years ago
Hi All,
I'm looking to output the aws_instance public IP address via the terminal following a TF config apply.
However, I'm using a terraform-aws-modules/ec2-instance/aws module and unsure how to output the ec2-instance IP address due to the instance being within a external module and not entered as a resource. Here's what I entered to attempt to get the intended output, but it was to no avail -
Please let me know if what I'm trying to achieve is possible and if so, how?! 🙂
I'm looking to output the aws_instance public IP address via the terminal following a TF config apply.
However, I'm using a terraform-aws-modules/ec2-instance/aws module and unsure how to output the ec2-instance IP address due to the instance being within a external module and not entered as a resource. Here's what I entered to attempt to get the intended output, but it was to no avail -
output "Public IP"
value = module.ec2_instance.aws_instance.public_ipPlease let me know if what I'm trying to achieve is possible and if so, how?! 🙂
Andres De Castroabout 3 years ago
Hi all!
Is there someone actively using the VPN cloudposse module? https://github.com/cloudposse/terraform-aws-ec2-client-vpn
I'm running into an issue when it tries to create the
Any idea of how can I fix this one?
Is there someone actively using the VPN cloudposse module? https://github.com/cloudposse/terraform-aws-ec2-client-vpn
I'm running into an issue when it tries to create the
aws_ec2_client_vpn_endpoint resource but it fails because the certificate (also created by the same module) does not have a domain.Any idea of how can I fix this one?
Soren Jensenabout 3 years ago
Hi all, I'm a happy user of the
My understanding from the AWS Documentation is to keep away from using ACL on new buckets. Still it looks like the module is using the ACL. Is there a more up to date example of how to use this module without ACL enabled?
cloudposse/s3-bucket/aws module. We are tightening security where we can, and trying to update everything to the latest best practice and recommendations ahead of an audit.My understanding from the AWS Documentation is to keep away from using ACL on new buckets. Still it looks like the module is using the ACL. Is there a more up to date example of how to use this module without ACL enabled?
source = "cloudposse/s3-bucket/aws"
# Cloud Posse recommends pinning every module to a specific version
version = "3.0.0"
enabled = true
bucket_name = random_pet.upload_bucket_name[each.key].id
acl = "private"
block_public_acls = true
block_public_policy = true
ignore_public_acls = true
restrict_public_buckets = trueRadhaabout 3 years ago
Hi all, I am using redis terraform module from https://github.com/cloudposse/terraform-aws-elasticache-redis.git. I want to add prevent_destroy lifecycle event in Redis. But I dont see this option available for input in the terraform module. Could someone let me know if there is an option to add it using this module?
Alex Atkinsonabout 3 years ago
As far as state migrations go, is there any downside to simply moving the state file from the old location to the new, updating the backend config, and verifying no change detected with tf apply?... I can't think of any, and you get to skip tf init -migrate-state, etc.
Alex Atkinsonabout 3 years ago
I googled state migration.... The internet would have you think it's something complicated, unless I'm missing something.
HSabout 3 years ago
Also on the subject of terraform => redis. I’m building a dashboard for our engineers where they can perform some configurations from the dashboard and when they click on deploy, we get the json payload, convert it into a tfvars file and use it to run terraform apply. However I’m looking for a better apporach to this.
Idea 1: Save all these config into redis, and create a terraform provider that gets the variables values from redis key store instead onf using tfvars or terraform environment variables.
What do you guys think of this? Does it make sense? or its a waste of time? or perhaps there’s a public provider that already does this?
Idea 1: Save all these config into redis, and create a terraform provider that gets the variables values from redis key store instead onf using tfvars or terraform environment variables.
What do you guys think of this? Does it make sense? or its a waste of time? or perhaps there’s a public provider that already does this?
Fredistelroyabout 3 years ago
Hello, it is stated here that the Cloudposse team no longer use AWS Beanstalk all that much anymore: https://github.com/cloudposse/terraform-aws-elastic-beanstalk-environment
Does anybody know the reasoning? What do you guys use instead these days?
Does anybody know the reasoning? What do you guys use instead these days?
Christopher Pieperabout 3 years ago
So having this issue now with my spacelift-workers.. And I am not exactly sure whats happening, me thinks its generating a new workspace after it inits the backend, and needs to maybe reverse order and gen workspace then gen backend then init.. But this hasn’t worked for me..
techpirateabout 3 years ago
here anyone know how to resolve this error?
techpirateabout 3 years ago
i am using terragrunt to create aurora-data
Vladimirabout 3 years ago
Hi, colleagues, does anyone know the best practice to create resources in different regions? Context: some services are not available in certain regions and need to be created in other regions
shamwowabout 3 years ago(edited)
hello folks, weird issue, I have a list of cidrs as type string, and a string variable that if filled should be added to the list if != null
Im trying to do this in locals{} to no avail, Im just playing with vars for now and testing locally with outputs set but it keeps adding the null to the array:
I have tried a bunch of different methods here like try(var.aaa, false) and != null etc but ultimately it just keeps appending a null value to the list, any ideas?
Im trying to do this in locals{} to no avail, Im just playing with vars for now and testing locally with outputs set but it keeps adding the null to the array:
variable "aaa" {
type = string
default = null
}
variable "bbb" {
description = "List of vpc cidr blocks to route this endpoint to"
type = list(string)
default = ["10.1.0.0/16", "10.2.0.0/16"]
}
locals {
# new_list = "${coalescelist(tolist(var.aaa),var.bbb)}"
newlist = (contains(var.bbb, var.aaa) ? var.bbb : concat(var.bbb, [var.aaa]))
}I have tried a bunch of different methods here like try(var.aaa, false) and != null etc but ultimately it just keeps appending a null value to the list, any ideas?
Wilabout 3 years ago
Hey there, I hope this is an easy question but I don't see how to do this.
Using the datadog module for synthetics here: https://github.com/cloudposse/terraform-datadog-platform/tree/master/examples/synthetics
Using the datadog module for synthetics here: https://github.com/cloudposse/terraform-datadog-platform/tree/master/examples/synthetics
Wilabout 3 years ago
Inside we've got all these nice YAML files that creates our alerts.. but some require certs that are in our secret store. I can get them using a
data.external command but can't seem to figure out how to get that injected into the YAML files inside the catalog.Wilabout 3 years ago
example YAML here https://github.com/cloudposse/terraform-datadog-platform/blob/master/examples/synthetics/catalog/http.yaml
Oleksandr Lytvynabout 3 years ago(edited)
Hello, i would like to ask advice regarding deployment of AWS CloudFormation stacks in multiple regions. (in this case is is about regular stacks and not StackSets).
Use case: I've deployed AWS Config inside AWS Organization via CloudFormation StackSets. Config was deployed in all selected regions and all AWS Org member accounts (except Management account, which is expected). Now i'm trying to deploy AWS Config inside AWS Org Management account in multiple regions, possibly without too much ctrl+c ctrl+v method 🙂
Looking at Terraform resource https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/cloudformation_stack i don't see there a way to specify region (and therefore can't iterate on it). Only 1 method that came to my mind is to use more aws providers (with aliases) and then just ctrl+c & ctrl+v resource aws_cloudformation_stack block and use different providers/aliases.
But maybe there is a better way ?
Use case: I've deployed AWS Config inside AWS Organization via CloudFormation StackSets. Config was deployed in all selected regions and all AWS Org member accounts (except Management account, which is expected). Now i'm trying to deploy AWS Config inside AWS Org Management account in multiple regions, possibly without too much ctrl+c ctrl+v method 🙂
Looking at Terraform resource https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/cloudformation_stack i don't see there a way to specify region (and therefore can't iterate on it). Only 1 method that came to my mind is to use more aws providers (with aliases) and then just ctrl+c & ctrl+v resource aws_cloudformation_stack block and use different providers/aliases.
But maybe there is a better way ?
sripeabout 3 years ago(edited)
hi , i m trying to create few resources reading data from yaml and unable to read/ values and getting errors. any ideas? error in comments
and the yaml file as below
YAML file
---
module "yaml_json_multidecoder" {
source = "levmel/yaml_json/multidecoder"
version = "0.2.1"
filepaths = ["./examples/*.yaml"]
}
locals {
team_members = module.yaml_json_multidecoder.files.team.team_members
project_team_mapping = module.yaml_json_multidecoder.files.project.project_team_mapping
}
resource "mongodbatlas_project" "test" {
for_each = local.project_team_mapping
name = each.key
org_id = var.organization_id
dynamic "teams" {
for_each = {
for team in each.value: team.team_name => team.roles
}
content {
team_id = each.key
role_names = each.value
}
}
}and the yaml file as below
YAML file
---
project_team_mapping:
Terraform-Project-1:
- team_name: dx-example-team-1
roles:
- GROUP_READ_ONLY
- GROUP_DATA_ACCESS_READ_WRITE
- team_name: dx-example-team-2
roles:
- GROUP_READ_ONLY
- GROUP_DATA_ACCESS_READ_WRITE
Terraform-Project-2:
- team_name: dx-example-team-3
roles:
- GROUP_READ_ONLY
- GROUP_DATA_ACCESS_READ_WRITE
- team_name: dx-example-team-4
roles:
- GROUP_READ_ONLY
- GROUP_DATA_ACCESS_READ_WRITEtechpirateabout 3 years ago
here can anyone help me with this why its throwing error
techpirateabout 3 years ago
ssh key path
Steve Wade (swade1987)about 3 years ago
does anyone know if its possible to leverage
aws_cloudwatch_log_subscription_filter but where kinesis firehose is in a different account?Steve Wade (swade1987)about 3 years ago
i want to run a firehose for datadog from our security account but have cloudwatch log groups push messages to it
rssabout 3 years ago(edited)
How to switch my Worker to TestWorker with Hilt?
I am doing end-to-end test which use WorkManager in my Application. My DelegatingWorkerFactory() is hilt injected and creates the different factories, which in turn create the different ListenableWorkers in my app.
For testing, I would like to bind to these workers to the test version i.e. TestListenableWorker(). What is the best way to do this using Hilt?
Appreciate there could be XY problem here and there might be a different approach to achieve this. Essentially I just want to seamlessly...
I am doing end-to-end test which use WorkManager in my Application. My DelegatingWorkerFactory() is hilt injected and creates the different factories, which in turn create the different ListenableWorkers in my app.
For testing, I would like to bind to these workers to the test version i.e. TestListenableWorker(). What is the best way to do this using Hilt?
Appreciate there could be XY problem here and there might be a different approach to achieve this. Essentially I just want to seamlessly...
rssabout 3 years ago(edited)
WorkManager is not initialized
I got this error on sentry panel only on production build variant.
IllegalStateException WorkManager is not initialized properly. You
have explicitly disabled WorkManagerInitializer in your manifest, have
not manually called WorkManager#initialize at this point, and your
Application does not implement Configuration.Provider.
java.util.concurrent.ThreadPoolExecutor in runWorker at line 1167
unlike the error i have no work manager dependency in project
could anyone help ...thanks in advance
I got this error on sentry panel only on production build variant.
IllegalStateException WorkManager is not initialized properly. You
have explicitly disabled WorkManagerInitializer in your manifest, have
not manually called WorkManager#initialize at this point, and your
Application does not implement Configuration.Provider.
java.util.concurrent.ThreadPoolExecutor in runWorker at line 1167
unlike the error i have no work manager dependency in project
could anyone help ...thanks in advance
rssabout 3 years ago(edited)
How to fix crash IllegalStateException: The file system on the device is in a bad state. WorkManager cannot access the app's internal data store
I have got this crash report in firebase crashlytics, titled -
SQLiteConnection.java
android.database.sqlite.SQLiteConnection.nativeExecute
and the stacktrace lists these error:
Fatal Exception: java.lang.IllegalStateException
The file system on the device is in a bad state. WorkManager cannot access the app's internal data store.
androidx.work.impl.utils.ForceStopRunnable.run (ForceStopRunnable.java:128)
androidx.work.impl.utils.SerialExecutor$Task.run (SerialExecutor.java:91)...
I have got this crash report in firebase crashlytics, titled -
SQLiteConnection.java
android.database.sqlite.SQLiteConnection.nativeExecute
and the stacktrace lists these error:
Fatal Exception: java.lang.IllegalStateException
The file system on the device is in a bad state. WorkManager cannot access the app's internal data store.
androidx.work.impl.utils.ForceStopRunnable.run (ForceStopRunnable.java:128)
androidx.work.impl.utils.SerialExecutor$Task.run (SerialExecutor.java:91)...
rssabout 3 years ago(edited)
OneTimeWorkRequest does not run when display is off
I need to do fast periodic background tasks, but PeriodicWorkRequest is limited to 15 mins, so I use OneTimeWorkRequest and set it again on itself.
I set constraints that do not force charging, but according to my test OneTimeWorkRequest does not run when the display is off and the charging cable is not connected (about after 1 minute stoped)
but when the charging cable is connected it works well!
I have this issue only on android 12 whether it works on android 6 - 7- 8 and 10 that tested!...
I need to do fast periodic background tasks, but PeriodicWorkRequest is limited to 15 mins, so I use OneTimeWorkRequest and set it again on itself.
I set constraints that do not force charging, but according to my test OneTimeWorkRequest does not run when the display is off and the charging cable is not connected (about after 1 minute stoped)
but when the charging cable is connected it works well!
I have this issue only on android 12 whether it works on android 6 - 7- 8 and 10 that tested!...
rssabout 3 years ago(edited)
Flutter: How to pause music playing with cron [workmanager]?
How can I pause music playing using workmanager?
I got an exception error: MissingPluginException(No implementation found for method pause on channel assets_audio_player) when trying to pause the music.
I want to implement a function Bed time which allow user to set their bed time, so I will pause the music on time set.
Dependencies:
workmanager: ^0.5.1
assets_audio_player: ^3.0.5
//GLOBLE
@pragma('vm:entry-point')
void callbackDispatcher() {
Workmanager().executeTask((taskName, inputData)...
How can I pause music playing using workmanager?
I got an exception error: MissingPluginException(No implementation found for method pause on channel assets_audio_player) when trying to pause the music.
I want to implement a function Bed time which allow user to set their bed time, so I will pause the music on time set.
Dependencies:
workmanager: ^0.5.1
assets_audio_player: ^3.0.5
//GLOBLE
@pragma('vm:entry-point')
void callbackDispatcher() {
Workmanager().executeTask((taskName, inputData)...
rssabout 3 years ago(edited)
WorkManager OneTimeWorkRequest shows only the last notification
my app tracks the movie release dates, notifying the user the day of the release date. It could happen that two or more elements have the same release date and then, at midnight on that day, more notifications must be sent. The problem is that the notifications instead of accumulating replace each other, only showing the latest one.
MainAcitvity:
createWorkRequest(element.getName(), notification_delay_in_seconds);
private void createWorkRequest(String message, long timeDelayInSeconds) {...
my app tracks the movie release dates, notifying the user the day of the release date. It could happen that two or more elements have the same release date and then, at midnight on that day, more notifications must be sent. The problem is that the notifications instead of accumulating replace each other, only showing the latest one.
MainAcitvity:
createWorkRequest(element.getName(), notification_delay_in_seconds);
private void createWorkRequest(String message, long timeDelayInSeconds) {...
rssabout 3 years ago(edited)
How to run CoroutineWorker synchronously with Android WorkManager?
I use WorkManager in my app to chain multiple CoroutineWorkers together. I am trying to test my app and have these workers run synchronously before continuing with rest of test.
As CoroutineWorker is a suspend function it does not use the SynchronousExecutor() provided to the workmanager Configuration. The Android Docs mentions that CoroutineContext can be...
I use WorkManager in my app to chain multiple CoroutineWorkers together. I am trying to test my app and have these workers run synchronously before continuing with rest of test.
As CoroutineWorker is a suspend function it does not use the SynchronousExecutor() provided to the workmanager Configuration. The Android Docs mentions that CoroutineContext can be...
rssabout 3 years ago(edited)
How can I use my ApiService and Room Dao into WorkManager with Hilt, implementing MVVM pattern?
I want to use my ApiService and my Room Dao in the WorkManager class implementing the MVVM pattern and Hilt as dependency injection.
This is my code:
ViewModel
@HiltViewModel
public class SyncViewModel extends ViewModel {
private final SyncRepository mRepository;
@Inject
public SyncViewModel(SyncRepository repository) {
mRepository = repository;
}
public LiveData getObservable() {
return mRepository.getFromDB();
}
public void launchSync(){...
I want to use my ApiService and my Room Dao in the WorkManager class implementing the MVVM pattern and Hilt as dependency injection.
This is my code:
ViewModel
@HiltViewModel
public class SyncViewModel extends ViewModel {
private final SyncRepository mRepository;
@Inject
public SyncViewModel(SyncRepository repository) {
mRepository = repository;
}
public LiveData getObservable() {
return mRepository.getFromDB();
}
public void launchSync(){...
rssabout 3 years ago(edited)
Updating foreground service everyday at an exact time
I've written an application with a foreground service.
The service notification must be updated precisely at 6 pm every day.
I've tried to achieve this functionality with AlarmManager but most of the time it is not working.
Would WorkManager solve this problem (if it is, please explain how I should use it in this case) or is there a way to do this?
I've written an application with a foreground service.
The service notification must be updated precisely at 6 pm every day.
I've tried to achieve this functionality with AlarmManager but most of the time it is not working.
Would WorkManager solve this problem (if it is, please explain how I should use it in this case) or is there a way to do this?
rssabout 3 years ago(edited)
Serializing list of Files with gson not working in Android 12+ (API 32, 33) [duplicate]
I do have an object with a list of Files (java.io.File):
class NewRequestBody {
val files: MutableList = ArrayList()
}
I need that object in my WorkManager class, so I use Gson to convert it to Json and add it to the WorkRequest.Builder as InputData:
val inputData = Data.Builder().putString(BODY_KEY, Gson().toJson(body)).build()
val myWorker = OneTimeWorkRequest.Builder(MyWorker::class.java)
.setInputData(inputData)
.build()
Then in my WorkManager class I'm converting it...
I do have an object with a list of Files (java.io.File):
class NewRequestBody {
val files: MutableList = ArrayList()
}
I need that object in my WorkManager class, so I use Gson to convert it to Json and add it to the WorkRequest.Builder as InputData:
val inputData = Data.Builder().putString(BODY_KEY, Gson().toJson(body)).build()
val myWorker = OneTimeWorkRequest.Builder(MyWorker::class.java)
.setInputData(inputData)
.build()
Then in my WorkManager class I'm converting it...
rssabout 3 years ago(edited)
Detect if Expedited is OutOfQuota for WorkManager Android
When use WorkManager with one of these:
.setExpedited(OutOfQuotaPolicy.RUN_AS_NON_EXPEDITED_WORK_REQUEST)
.setExpedited(OutOfQuotaPolicy.DROP_WORK_REQUEST)
At this time, I want to detect if the device could not run as expedited. Is it possible to Try-catch or any other ways to detect when OutOfQuota?
Thank you.
When use WorkManager with one of these:
.setExpedited(OutOfQuotaPolicy.RUN_AS_NON_EXPEDITED_WORK_REQUEST)
.setExpedited(OutOfQuotaPolicy.DROP_WORK_REQUEST)
At this time, I want to detect if the device could not run as expedited. Is it possible to Try-catch or any other ways to detect when OutOfQuota?
Thank you.
rssabout 3 years ago(edited)
How to set a Work Manager to listen to an unlock screen event (android.intent.action.USER_PRESENT)
I'm trying to set up an Android Work Manager in Java which is triggered every Time the screen gets unlocked.
With Android
I'm trying to set up an Android Work Manager in Java which is triggered every Time the screen gets unlocked.
With Android
rssabout 3 years ago(edited)
How to start a startForegroundService using WorkManager
Hi due to issues with startForegroundService not able to run in the background on certain android version. I am trying to startForegroundService using a WorkManager but unable to get it to work. this is what I tried so far.
Forground service that needs to start
ContextCompat.startForegroundService(context, CarInfoProcessingService.createIntent(context = applicationContext,
pushMsgData = message.data))
class that starts the foreground service
class BackupWorker(private val...
Hi due to issues with startForegroundService not able to run in the background on certain android version. I am trying to startForegroundService using a WorkManager but unable to get it to work. this is what I tried so far.
Forground service that needs to start
ContextCompat.startForegroundService(context, CarInfoProcessingService.createIntent(context = applicationContext,
pushMsgData = message.data))
class that starts the foreground service
class BackupWorker(private val...
rssabout 3 years ago(edited)
Android WorkManager sometimes retries after a success
I have a SyncWorker class I am using to capture offline actions and relay them to the server. It works, but I am currently trying to improve the success rate by investigating cases of failed sync operations captured in logs. A substantial number of these failures were reported as missing the data provided for sync (stored in a local database). I initially assumed these to be indications of local database failures, but upon investigating specific cases of this failure I found that every single...
I have a SyncWorker class I am using to capture offline actions and relay them to the server. It works, but I am currently trying to improve the success rate by investigating cases of failed sync operations captured in logs. A substantial number of these failures were reported as missing the data provided for sync (stored in a local database). I initially assumed these to be indications of local database failures, but upon investigating specific cases of this failure I found that every single...
rssabout 3 years ago(edited)
How to listen to an unlock screen event on Android
I'm trying to get a function to trigger whenever the screen gets unlocked, even if the app is not running.
With Android
I'm trying to get a function to trigger whenever the screen gets unlocked, even if the app is not running.
With Android
rssabout 3 years ago(edited)
I want to implement WorkManager for Periodic work every one minute but WorkManager not work properly so how to implement?
Here is my worker class:
public class DataContinueWork extends Worker {
public DataContinueWork(Context context,
WorkerParameters workerParams) {
super(context, workerParams);
}
@Override
public Result doWork() {
addInDatabase();
return Result.Success.success();
}
private void addInDatabase() {
DatabaseHelper database = Room.databaseBuilder(getApplicationContext(), DatabaseHelper.class,...
Here is my worker class:
public class DataContinueWork extends Worker {
public DataContinueWork(Context context,
WorkerParameters workerParams) {
super(context, workerParams);
}
@Override
public Result doWork() {
addInDatabase();
return Result.Success.success();
}
private void addInDatabase() {
DatabaseHelper database = Room.databaseBuilder(getApplicationContext(), DatabaseHelper.class,...
rssabout 3 years ago(edited)
Where should WorkManager be placed within Clean Architecture?
I created a WorkManager that retrieves the current Bitcoin price from an API every 60 minutes and displays it to the user as a notification. However, I am confused about how to integrate WorkManager with Clean Architecture.
I created an infrastructure layer for WorkManager. Do you think this is correct? In your opinion, where should WorkManager be placed in Clean Architecture?
Scheme of Current Architecture
<a...
I created a WorkManager that retrieves the current Bitcoin price from an API every 60 minutes and displays it to the user as a notification. However, I am confused about how to integrate WorkManager with Clean Architecture.
I created an infrastructure layer for WorkManager. Do you think this is correct? In your opinion, where should WorkManager be placed in Clean Architecture?
Scheme of Current Architecture
<a...
rssabout 3 years ago(edited)
WorkManager - @HiltWorkManager
I have viewmodel:
@HiltViewModel
class SplashViewMode @Inject constructor(
private val repository: DataStoreRepository,
private val workManager: PeriodicNotificationWorkManager
) : ViewModel() {
init {
workManager.startPeriodicNotifications()
}
}
and a class where I start my periodic work
class PeriodicNotificationWorkManager @Inject constructor(
private val context: Context,
private val workManager: WorkManager
) {
private val WORK_TAG = "my_work"...
I have viewmodel:
@HiltViewModel
class SplashViewMode @Inject constructor(
private val repository: DataStoreRepository,
private val workManager: PeriodicNotificationWorkManager
) : ViewModel() {
init {
workManager.startPeriodicNotifications()
}
}
and a class where I start my periodic work
class PeriodicNotificationWorkManager @Inject constructor(
private val context: Context,
private val workManager: WorkManager
) {
private val WORK_TAG = "my_work"...
rssabout 3 years ago(edited)
Is it possible to use workmanager in Flutter to relaunch the app after a few hours (depending on the situation) when the app is completely closed?
I want to create an app that shows an alarm screen that sounds when the app is restarted when certain conditions are met after communicating with the api using workmanager in Flutter. However, the app does not restart even if I use the code below.
void callbackDispatcher() {
Workmanager().executeTask((task, inputData) async {
do{
code that api communication....
}while(When conditions are satisfied)
Restart.restartApp();//When I try to relaunch the app, nothing happens...
I want to create an app that shows an alarm screen that sounds when the app is restarted when certain conditions are met after communicating with the api using workmanager in Flutter. However, the app does not restart even if I use the code below.
void callbackDispatcher() {
Workmanager().executeTask((task, inputData) async {
do{
code that api communication....
}while(When conditions are satisfied)
Restart.restartApp();//When I try to relaunch the app, nothing happens...
rssabout 3 years ago(edited)
Is it good approach to cancel WorkManger task in executeTask() function in flutter
I have to cancel/dispose workmanager task as soon as it gets completed, but most of the times app is not in running state. So is it good or bad to cancel that task in executeTask() function.
Here is code example:
Register task first
Workmanager().registerOneOffTask('taskABC','taskABC',
inputData: {'data':'some data here'},);
And here is an code inside callbackDispathcer()
Workmanager().executeTask((taskName, inputData) async {
try {
switch(taskName) {
case 'taskABC':...
I have to cancel/dispose workmanager task as soon as it gets completed, but most of the times app is not in running state. So is it good or bad to cancel that task in executeTask() function.
Here is code example:
Register task first
Workmanager().registerOneOffTask('taskABC','taskABC',
inputData: {'data':'some data here'},);
And here is an code inside callbackDispathcer()
Workmanager().executeTask((taskName, inputData) async {
try {
switch(taskName) {
case 'taskABC':...
rssabout 3 years ago(edited)
Observers don't get notified when LiveData is set through FileObserver
I have a sharedViewModel with LiveData properties.
MainActivity:
private val logViewModel by viewModels()
fun startLocationUpdates() {
val locationItem = LocationItem(...)
logViewModel.addLogEntry(locationItem)
}
override fun onCreate(savedInstanceState: Bundle?) {
val observer = object : FileObserver(applicationContext.filesDir.path + "/" + jsonFileName) {
override fun onEvent(event: Int, file: String?) {
if (event ==...
I have a sharedViewModel with LiveData properties.
MainActivity:
private val logViewModel by viewModels()
fun startLocationUpdates() {
val locationItem = LocationItem(...)
logViewModel.addLogEntry(locationItem)
}
override fun onCreate(savedInstanceState: Bundle?) {
val observer = object : FileObserver(applicationContext.filesDir.path + "/" + jsonFileName) {
override fun onEvent(event: Int, file: String?) {
if (event ==...
rssabout 3 years ago(edited)
is there any way or package which can run background tasks every minute periodically in flutter
I am trying to build a flutter app for my company (just for android), in which we assign tasks to employees and track their location.
What I want to do, is to send http request every minute periodically to track their location, but I could not find any package or way to do that in the way I want.
any help would be appreciated, thanks.
I have tried a lot of packages for background tasks. Including alarm_manager_plus, background_location, and work_manager package. the best one was workmanager...
I am trying to build a flutter app for my company (just for android), in which we assign tasks to employees and track their location.
What I want to do, is to send http request every minute periodically to track their location, but I could not find any package or way to do that in the way I want.
any help would be appreciated, thanks.
I have tried a lot of packages for background tasks. Including alarm_manager_plus, background_location, and work_manager package. the best one was workmanager...
rssabout 3 years ago(edited)
I want to make a DayCounter app that add one day to my TextView everyday and save it in Data base And do in background when phone turned off in Kotlin
Var count = 0
If(textClock.text == "00:00") {
Count++
TextDayCount.text = count.toString()
}
//Do I have to Use WorkManager?
Var count = 0
If(textClock.text == "00:00") {
Count++
TextDayCount.text = count.toString()
}
//Do I have to Use WorkManager?
rssabout 3 years ago(edited)
SynchronousExecutor not running WorkManager synchronously for CoroutineWorkers
Following Android's documentation, I created the following minimal viable example:
@RunWith(AndroidJUnit4::class)
class UpdatePlatformEndpointTest {
private lateinit var context: Context
@Before
fun setUp() {
context = ApplicationProvider.getApplicationContext()
val config = Configuration.Builder()...
Following Android's documentation, I created the following minimal viable example:
@RunWith(AndroidJUnit4::class)
class UpdatePlatformEndpointTest {
private lateinit var context: Context
@Before
fun setUp() {
context = ApplicationProvider.getApplicationContext()
val config = Configuration.Builder()...
rssabout 3 years ago(edited)
Android AppWidget using WorkManager experiencing network issues
I have an application in production that contains an AppWidget that schedules periodic refreshes via a WorkManager CoroutineWorker. My RefreshWidgetWorker simply requests some data from a Retrofit service & then persists that data via a Room DAO. I am receiving hundreds of crash logs of network connectivity issues & reports from users that the widget will not load for them. The exception is typically:
java.net.UnknownHostException: Unable to resolve host "[my-server]": No address associated...
I have an application in production that contains an AppWidget that schedules periodic refreshes via a WorkManager CoroutineWorker. My RefreshWidgetWorker simply requests some data from a Retrofit service & then persists that data via a Room DAO. I am receiving hundreds of crash logs of network connectivity issues & reports from users that the widget will not load for them. The exception is typically:
java.net.UnknownHostException: Unable to resolve host "[my-server]": No address associated...
rssabout 3 years ago(edited)
non-local notification using workManager flutter
i tried to send notification to another device when the app is terminated using workManager
it does not work, however the same function works if i use it without workManager
here is the code
in the main
await Workmanager().initialize(callBAckDispatcher, isInDebugMode: true);
callBackDispathcer
callBAckDispatcher() {
WidgetsFlutterBinding.ensureInitialized();
Firebase.initializeApp();
Workmanager().executeTask((taskName, inputData) async {
if (taskName == "t") {
int id =...
i tried to send notification to another device when the app is terminated using workManager
it does not work, however the same function works if i use it without workManager
here is the code
in the main
await Workmanager().initialize(callBAckDispatcher, isInDebugMode: true);
callBackDispathcer
callBAckDispatcher() {
WidgetsFlutterBinding.ensureInitialized();
Firebase.initializeApp();
Workmanager().executeTask((taskName, inputData) async {
if (taskName == "t") {
int id =...
rssabout 3 years ago(edited)
Getting Exception kotlinx.coroutines.JobCancellationException: Job was cancelled in CoroutineWorker in Kotlin android
I have created a simple CoroutineWorker that run loop for 1000 time with delay of 1000 milliseconds.
This worker is unique periodic worker with 15 minutes as repeat interval and with ExistingPeriodicWorkPolicy as KEEP
But When I start worker and after some time during execution worker gets cancelled with Exception JobCancellationException
The Full Exception:
Exception kotlinx.coroutines.JobCancellationException: Job was cancelled; job=JobImpl{Cancelling}@ba57765
12:55:47.088 WM-Wor...rapper...
I have created a simple CoroutineWorker that run loop for 1000 time with delay of 1000 milliseconds.
This worker is unique periodic worker with 15 minutes as repeat interval and with ExistingPeriodicWorkPolicy as KEEP
But When I start worker and after some time during execution worker gets cancelled with Exception JobCancellationException
The Full Exception:
Exception kotlinx.coroutines.JobCancellationException: Job was cancelled; job=JobImpl{Cancelling}@ba57765
12:55:47.088 WM-Wor...rapper...
rssabout 3 years ago(edited)
Compose WorkManager not getting triggered
I have an app that uses a Worker to update its services via the internet.
However, the worker is not getting triggered.
Worker.kt:
class MyWorker(
private val container: AppContainer,
ctx: Context,
params: WorkerParameters
) : CoroutineWorker(ctx, params) {
override suspend fun doWork(): Result {
return withContext(Dispatchers.IO) {
return@withContext try {
val response = container.onlineRepository.getData()
// Load the...
I have an app that uses a Worker to update its services via the internet.
However, the worker is not getting triggered.
Worker.kt:
class MyWorker(
private val container: AppContainer,
ctx: Context,
params: WorkerParameters
) : CoroutineWorker(ctx, params) {
override suspend fun doWork(): Result {
return withContext(Dispatchers.IO) {
return@withContext try {
val response = container.onlineRepository.getData()
// Load the...
rssabout 3 years ago(edited)
Flutter workmanager with BLOC and repository pattern
I use bloc and with repository pattern. There was a need to execute the code in the background according to the schedule, for this I use workmanager The problem is that the workmanager is executed in a separate method, which is initialized outside the main method, and it does not know anything about the context or the code below like MyApp...
I use bloc and with repository pattern. There was a need to execute the code in the background according to the schedule, for this I use workmanager The problem is that the workmanager is executed in a separate method, which is initialized outside the main method, and it does not know anything about the context or the code below like MyApp...
rssabout 3 years ago(edited)
Where do you store your WorkManager files in a Multi-Module app?
For most classes it can be intuitive what module you would want to place them in, but for WorkManager it is less clear. For example you could place it in
top level app module
designated worker module
domain or data module
Then there is the question of the actual workers and worker factories themselves and if they would be placed in the module they are used or all aggregated into some higher level directory.
Is there any consensus or best practice on how you structure WorkManager in...
For most classes it can be intuitive what module you would want to place them in, but for WorkManager it is less clear. For example you could place it in
top level app module
designated worker module
domain or data module
Then there is the question of the actual workers and worker factories themselves and if they would be placed in the module they are used or all aggregated into some higher level directory.
Is there any consensus or best practice on how you structure WorkManager in...
lorenabout 3 years ago
ahh what is happening please stop
PePe Amengualabout 3 years ago
I was about to mute the channel
Alex Atkinsonabout 3 years ago
Is there a limit to the size of a variable map?
Alex Atkinsonabout 3 years ago
4MB too much?
Alex Jurkiewiczabout 3 years ago
I don't think there's a limit, but that much data sounds a little unusual and would count as a code smell IMO
Alex Atkinsonabout 3 years ago
It turned out to be more like 2 and change. It's a vpc cidr map and subnet cidr map. Together they lay out all the breakdowns for 10.0.0.0/8 into a combo of /20 and /19 subnets. Now when folks get assigned a new cidr it's just updating the key to the assignment groups name and they're good to go.
Bart Coddensabout 3 years ago
HI all, while using the dynamic subnets module, I want to assign a route table to all the subnet id's in the vpc
Bart Coddensabout 3 years ago
I have this:
Bart Coddensabout 3 years ago
resource "aws_route_table_association" "all" {
subnet_id = [module.subnets.private_subnet_ids[*]]
route_table_id = aws_route_table.other.id
}
subnet_id = [module.subnets.private_subnet_ids[*]]
route_table_id = aws_route_table.other.id
}
Bart Coddensabout 3 years ago
but terraform requires a string
Bart Coddensabout 3 years ago
what am I doing wrong ?
Bart Coddensabout 3 years ago
can anyone give me some assistance with this ? I am getting confused
Si Walkerabout 3 years ago(edited)
@Bart Coddens if
In this case, without complicating things, you might have to have a code block for each az/subnet, something like:
subnet_id is singular not plural, the value would normally be a single object or string, not contained in square brackets. Brackets are to pass it a list or a tuple or map or whatever.In this case, without complicating things, you might have to have a code block for each az/subnet, something like:
resource "aws_route_table_association" "all" {
subnet_id = module.subnets.private_subnet_ids[0]
route_table_id = aws_route_table.other.id
}
resource "aws_route_table_association" "all" {
subnet_id = module.subnets.private_subnet_ids[1]
route_table_id = aws_route_table.other.id
}Bart Coddensabout 3 years ago
well I tried doing this:
Bart Coddensabout 3 years ago
resource "aws_route_table_association" "gatewayendpoints" {
count = length(var.availability_zones)
subnet_id = module.subnets.private_subnet_ids[count.index]
route_table_id = aws_route_table.other.id
}
count = length(var.availability_zones)
subnet_id = module.subnets.private_subnet_ids[count.index]
route_table_id = aws_route_table.other.id
}
Bart Coddensabout 3 years ago
but this fails with :
Bart Coddensabout 3 years ago
Resource.AlreadyAssociated: the specified association for route table
Si Walkerabout 3 years ago
And is it already associated? In the AWS console, if you view the subnet, does it have the route(s) in question? If so you've got 2 options, either import it (bit of a faff), or remove it in the console and let terraform re-add it, wouldn't be doing anything like that for production systems though 😉
Bart Coddensabout 3 years ago
no it's a demo setup
Bart Coddensabout 3 years ago
but nothing is associated
Bart Coddensabout 3 years ago
that confuses me a bit
Si Walkerabout 3 years ago(edited)
Hi all, didn't know if this classed as either a bug or feature request so joined here instead.
We previously had a local copy of the Label module and we had a lot of security alerts from Dependabot on github.com with regards to the gopkg version being used.
Our github alerts are an easy fix, map to the module instead of having a local copy and don't push
We previously had a local copy of the Label module and we had a lot of security alerts from Dependabot on github.com with regards to the gopkg version being used.
Our github alerts are an easy fix, map to the module instead of having a local copy and don't push
.terraform up to github, but I believe the security issue still exists with 3 or 4 references to versions less than v.2.2.4Si Walkerabout 3 years ago(edited)
@Bart Coddens
Try this
or
As long as AZ's match private subnet numbers i.e. 1 to 1, then the top one should work, don't think the
Try this
resource "aws_route_table_association" "gatewayendpoints" {
count = length(var.availability_zones)
subnet_id = module.subnets[count.index].private_subnet_ids
route_table_id = aws_route_table.other.id
}or
resource "aws_route_table_association" "gatewayendpoints" {
count = length(module.subnets.private_subnet_ids)
subnet_id = module.subnets[count.index].private_subnet_ids
route_table_id = aws_route_table.other.id
}As long as AZ's match private subnet numbers i.e. 1 to 1, then the top one should work, don't think the
count.index should be at the end though, often it's before the elementBart Coddensabout 3 years ago
I think I solved it
Bart Coddensabout 3 years ago
by default the dynamic subnets module creates a route table for the private subnets, you cannot associate two route tables to a subnet
Bart Coddensabout 3 years ago
so I disabled the creation of the default route table for the subnet, created one with my gateway endpoints in and assigned that
Bart Coddensabout 3 years ago
now it works fine
aimbotdabout 3 years ago
Hey friends. I'm peeping at the dynamic subnets tf module. I notice that the NAT Instances cannot be set up with
SPOT instances. I am ignorant in this space so just looking for clarity. Is it a bad idea to set up nat's as spot instances? If so, why is that?PePe Amengualabout 3 years ago
CloudPosse folks, is there a way, elegant way to populate the entire
module.this.context output to parameter store?PePe Amengualabout 3 years ago(edited)
How does CloudPosse deal with ECS service task definitions and the deployment of services?( from the point of view of using atmos and the null-label module to infer information to then deploy the task and custom image from a github action)(related to the previous question)